Solving Equations Part 2
Solution
p1 = sympy.Symbol("p1")
p2 = sympy.Symbol("p2")
def twoChoice(ret1,ret2,var1,var2,cov,goalReturn):
retEquation = sympy.Eq(goalReturn,p1*ret1+p2*ret2)
totalPercent = sympy.Eq(1,p1+p2)
dictionary = sympy.solve((retEquation,totalPercent))
percent1 = dictionary[p1]
percent2 = dictionary[p2]
variance = percent1**2*var1+percent2**2*var2+2*percent1*percent2*cov
print("Put "+str(percent1*100)+"% in asset 1.")
print("Put "+str(percent2*100)+"% in asset 2.")
print("Your variance will be "+str(variance))
twoChoice(.03,.09,.05,.07,.03,.06)
We could also solve instead for a variance we want by feeding the portfolio variance equation.
p1 = sympy.Symbol("p1")
p2 = sympy.Symbol("p2")
def twoChoice2(ret1,ret2,var1,var2,cov,goalVar):
varEquation = sympy.Eq(goalVar,p1**2*var1+p2**2*var2+2*p1*p2*cov)
totalPercent = sympy.Eq(1,p1+p2)
dictionary = sympy.solve((varEquation,totalPercent))
return dictionary
twoChoice2(.03,.09,.05,.07,.03,.045)
You’re probably confused now, why is there two different weights that cause the same variance? This is because of the covariance term, it introduces non-linearity so in this case we can have more than one combination that causes the variance.
Let’s create a function that prints out the combinations.
def twoChoice2(ret1,ret2,var1,var2,cov,goalVar):
varEquation = sympy.Eq(goalVar,p1**2*var1+p2**2*var2+2*p1*p2*cov)
totalPercent = sympy.Eq(1,p1+p2)
dictionaries = sympy.solve((varEquation,totalPercent))
for dictionary in dictionaries:
percent1 = dictionary[p1]
percent2 = dictionary[p2]
ret = percent1*ret1+percent2*ret2
print("Put "+str(percent1*100)+"% in asset 1.")
print("Put "+str(percent2*100)+"% in asset 2.")
print("Your return will be "+str(ret))
twoChoice2(.03,.09,.05,.07,.03,.045)
Challenge
Modify the function so that it only returns the weights with the highest return.