Creating a Portfolio
Solution
fordSD = matrix[0][0]**.5
hondaSD = matrix[1][1]**.5
cov = matrix[0][1]
print(cov/(fordSD*hondaSD))
We are going to recreate the stock series without the percent change operation.
start = datetime.date(2015,1,1)
end = datetime.date(2016,1,1)
ford = pdr.get_data_yahoo("F", start, end)["Adj Close"]
honda = pdr.get_data_yahoo("HMC", start, end)["Adj Close"]
toyota = pdr.get_data_yahoo("TM", start, end)["Adj Close"]
Two really useful function are first and last which give you the first and last elements (depending on what argument you give, you get a different number of rows). To get only the first day, we give the argument “1D”.
print(ford.first('1D'))
print(ford.last('1D'))
What you get back is two series, not exactly what we want. We want the values, which we can get through the values attribute.
print(ford.first('1D').values)
Let’s see by what factor the Ford stock rose or fell.
print(ford.last('1D').values/ford.first('1D').values)
Looks like Ford ending up being worth about 95.5% of it’s original value at the end.
Let’s get the Ford and Toyota returns (we will subtract 1 from them to see the net return)
retFord = (ford.last('1D').values/ford.first('1D').values)[0]-1
retToyota = (toyota.last('1D').values/toyota.first('1D').values)[0]-1
What if we put 30% in Ford and 70% in Toyota? What would the return be?
print(retFord*.3+retToyota*.7)
What if we could invest $3,000 in Ford and $7,000 in Toyota? How many stocks (pretending we could have decimals for stocks) of each would we have?
fordStocks = 3000/ford.first('1D').values[0]
toyotaStocks = 7000/toyota.first('1D').values[0]
And what would they be worth at the end?
print(fordStocks*ford.last('1D').values[0])
print(toyotaStocks*toyota.last('1D').values[0])
Let’s do a sanity check and make sure this gives the same return as the weighted version.
print(((fordStocks*ford.last('1D').values[0]+toyotaStocks*toyota.last('1D').values[0])/10000)-1)