Sympy
The first step is installing sympy.
!pip install sympy
When we work with sympy, we create symbols to represent a variable. Let’s create a variable p1 to represent the percentage in asset 1.
import sympy
p1 = sympy.Symbol("p1")
print(p1)
Let’s expand our variables to have a two assets, two returns, and also a symbol for the total return.
p1 = sympy.Symbol("p1")
p2 = sympy.Symbol("p2")
totalReturn = sympy.Symbol("totalReturn")
ret1 = .03
ret2 = .09
At the core of sympy is equations. sympy.Eq() sets up an equation, and we can give it a left side and a right side (or just one side if we would like), so let’s set up the portfolio return equation.
retEquation = sympy.Eq(totalReturn,p1*ret1+p2*ret2)
The attributes lhs and rhs give the left and ride hand side of the equation.
print(retEquation)
print(retEquation.rhs)
print(retEquation.lhs)
You can plug into variables by doing .subs(variable_name,value), for example:
print(retEquation.subs(p1,.5))
You can also replace multiple values by feeding an array of tuples for replacements.
print(retEquation.subs([(p1,.5),(p2,.5)]))
Challenge