Solving Equations
Solution
def findReturn(w1,w2):
return retEquation.subs([(p1,w1),(p2,w2)])
print(findReturn(.5,.5))
print(findReturn(.5,.5).rhs)
Now, we are going to say that you can only invest up to 100%, so we want to make an equation to represent this.
totalPercent = sympy.Eq(1,p1+p2)
print(totalPercent)
We can solve equations in sympy with sympy.solve(). Let’s make a return equation with 6% on the left hand side, and then what we need to do is give sympy a tuple of equations we want to solve.
retEquation = sympy.Eq(.06,p1*ret1+p2*ret2)
print(sympy.solve((retEquation,totalPercent)))
It correctly gives us 50% and 50%!
Turning this into a function which let’s us solve for weights….
def twoChoice(ret1,ret2,goalReturn):
retEquation = sympy.Eq(goalReturn,p1*ret1+p2*ret2)
totalPercent = sympy.Eq(1,p1+p2)
return sympy.solve((retEquation,totalPercent))
twoChoice(.03,.09,.06)
What we get back is a dictionary. In case you don’t know what a dictionary is, here is a quick overview. It is a data type which let’s us give it a key and then it will return the key’s value. So in this case we have two keys, p1 and p2, and what they return is the weights. You get the value for a key by writing dictionary[key].
d = twoChoice(.03,.09,.06)
print(d[p1])
print(d[p2])
Challenge