Introduction to Portfolio Analysis in Python
Charlotte Werger
Data Scientist
$$
Changes in value over time
$ Return_t = \frac{V_t - V_{t-1}}{V_{t-1}} $
$$
df.head(2)
AAPL AMZN TSLA
date
2018-03-25 13.88 114.74 92.48
2018-03-26 13.35 109.95 89.79
# Calculate returns over each day
returns = df.pct_change()
returns.head(2)
AAPL AMZN TSLA
date
2018-03-25 NaN NaN NaN
2018-03-26 -0.013772 0.030838 0.075705
weights = np.array([0, 0.50, 0.25])
# Calculate average return for each stock
meanDailyReturns = returns.mean()
# Calculate portfolio return
portReturn = np.sum(meanDailyReturns*weights)
print (portReturn)
0.05752375881537723
# Calculate daily portfolio returns
returns['Portfolio']= returns.dot(weights)
# Let's see what it looks like
returns.head(3)
AAPL AMZN TSLA Portfolio
date
2018-03-23 -0.020974 -0.026739 -0.029068 -0.025880
2018-03-26 -0.013772 0.030838 0.075705 0.030902
# Compound the percentage returns over time
daily_cum_ret=(1+returns).cumprod()
# Plot your cumulative return
daily_cum_ret.Portfolio.plot()
Introduction to Portfolio Analysis in Python