Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

SymPy

from datascience import *
import numpy as np
from sympy import *
import sympy
init_printing()
import matplotlib.pyplot as plt
%matplotlib inline
solve = lambda x,y: sympy.solve(x-y)[0] if len(sympy.solve(x-y))==1 else "Not Single Solution"

Python has many tools, such as the SymPy library that we can use for expressing and evaluating formulas and functions in economics.

Since SymPy helps with symbolic math, we start out by create a symbol using Symbol, which we assign to a variable name. Then, we can use the symbols to construct symbolic expressions.

x = Symbol('x')
x
Loading...

Now let’s try using SymPy to create a symbolic expression for some hypothetical supply and demand curves.

To define an upward sloping supply curve with price expressed as a function of quantity, we start off defining the symbol QQ, which represents quantity. Then, we set up a negative relationship expressing PSP_S, which denotes the price of the supplied good (how much the producer earns), in terms of QQ.

Q = Symbol('Q')
P_S = 2 * Q - 3
P_S
Loading...

Similarly, we will also use QQ to express a relationship with PDP_D, the price of the good purchased (how much the consumer pays), creating a downward sloping demand curve.

Note that both functions are of the variable QQ; this will be important in allowing us to solve for the equilibrium.

P_D = 2 - Q
P_D
Loading...

To solve for the equilibrium given the supply and demand curve, we know that the price paid by consumers must equal to the price earned by suppliers. Thus, PD=PSP_D = P_S, allowing us to set the two equations equal to each other and solve for the equilibrium quantity and thus equilibrium price. To solve this by hand, we would set up the following equation to solve for QQ:

PD=PS2Q=2Q3P_D = P_S\\ 2-Q = 2Q-3

Using SymPy, we call solve, which takes in 2 arguments that represent the 2 sides of an equation and solves for the underlying variable such that the equation holds. Here, we pass in PDP_D and PSP_S, both represented in terms of QQ, to solve for the value of QQ such that PD=PSP_D=P_S. It’s good to know that solve is a custom function built for this class, and will be provided in the notebooks for you.

Q_star = solve(P_D, P_S)
Q_star
Loading...

The value of QQ that equates PDP_D and PSP_S is known as the market equilibrium quantity, and we denote it as QQ^*. Here, Q=53Q^* = \frac{5}{3}.

With QQ^* determined, we can substitute this value as QQ to thus calculate PDP_D or PSP_S. We substitute values using the subs function, which follows the syntax expression.subs(symbol_we_want_to_substitute, value_to_substitute_with).

P_D.subs(Q, Q_star)
Loading...

We can also substitute QQ^* into PSP_S, and should get the same results.

P_S.subs(Q, Q_star)
Loading...

Thus, the equilibrium price and quantity are $0.33 and 53\frac{5}{3}, respectively.

Let’s try another example. Suppose our demand function is PriceD=2Quantity+10\text{Price}_{D}=-2 \cdot \text{Quantity} + 10. Using SymPy, this would be

demand = -2 * Q + 10
demand
Loading...

In addition, let the supply function be PriceS=3Quantity+1\text{Price}_{S}=3 \cdot \text{Quantity} + 1. Using SymPy, this would be

supply = 3 * Q + 1
supply
Loading...

We will now try to find the market equilibrium. The market price equilibrium PP^* is the price at which the quantity supplied and quantity demanded of a good or service are equal to each other. Similarly, the market quantity equilibrium QQ^* is the quantity at which the price paid by consumers is equal to the price received by producers.

Combined, the price equilibrium and quantity equilibrium form a point on the graph with quantity and price as its axes, called the equilibrium point. This point is the point at which the demand and supply curves intersect.

First, we solve for the quantity equilibrium.

Q_star = solve(demand, supply)
Q_star
Loading...

Next, we plug the quantity equilibrium into our demand or supply expression to get the price equilibrium:

demand.subs(Q, 9/5)
Loading...

Graphically, we can plot the supply and demand curves with quantity on the xx axis and price on the yy axis. The point at which they intersect is the equilibrium point.

[Following image is a graph with lines for supply and demand intersecting ]

def plot_equation(equation, price_start, price_end, label=None, color=None, linestyle=None):
    plot_prices = [price_start, price_end]
    plot_quantities = [equation.subs(list(equation.free_symbols)[0], c) for c in plot_prices]
    plt.plot(plot_prices, plot_quantities, label=label, color=color, linestyle=linestyle)
    
def plot_intercept(eq1, eq2):
    ex = sympy.solve(eq1-eq2)[0]
    why = eq1.subs(list(eq1.free_symbols)[0], ex)
    plt.scatter([ex], [why], color='black', label="Equilibrium")
    return (ex, why)
    
plot_equation(demand, 0, 5, label="Demand")
plot_equation(supply, 0, 5, label="Supply", color="#CB7432", linestyle="dashed")
equilibrium = plot_intercept(supply, demand)
plt.legend()
plt.ylim(0,20)
plt.xlabel("Quantity")
plt.ylabel("Price")
plot_intercept(supply, demand);
<Figure size 640x480 with 1 Axes>