Portfolio Composition and Backtesting: Dakota Wixom
Portfolio Composition and Backtesting: Dakota Wixom
composition and
backtesting
IN TR OD U C TION TO P OR TFOL IO R ISK MAN AG E ME N T IN P YTH ON
Dakota Wixom
Quantitative Analyst | QuantCourse.com
Calculating portfolio returns
Portfolio Return Formula:
Rp = Ra1 wa1 + Ra2 wa2 + ... + Ran wa1
Rp : Portfolio return
Ran : Return for asset n
wan : Weight for asset n
import numpy as np
portfolio_weights = np.array([0.25, 0.35, 0.10, 0.20, 0.10])
port_ret = StockReturns.mul(portfolio_weights, axis=1).sum(axis=1)
port_ret
Date
2017-01-03 0.008082
2017-01-04 0.000161
2017-01-05 0.003448
...
StockReturns["Portfolio"] = port_ret
import numpy as np
numstocks = 5
portfolio_weights_ew = np.repeat(1/numstocks, numstocks)
StockReturns.iloc[:,0:numstocks].mul(portfolio_weights_ew, axis=1).sum(axis=1)
Date
2017-01-03 0.008082
2017-01-04 0.000161
2017-01-05 0.003448
...
mcapn
wmcapn = n
∑i=1 mcapi
import numpy as np
market_capitalizations = np.array([100, 200, 100, 100])
mcap_weights = market_capitalizations/sum(market_capitalizations)
mcap_weights
Dakota Wixom
Quantitative Analyst | QuantCourse.com
Pearson correlation
Examples of di erent correlations between two
random variables:
correlation_matrix = StockReturns.corr()
print(correlation_matrix)
σ : Asset volatility
ρ1,2 : Correlation between assets 1 and 2
cov_mat = StockReturns.cov()
cov_mat
import numpy as np
port_vol = np.sqrt(np.dot(weights.T, np.dot(cov_mat, weights)))
port_vol
0.035
Dakota Wixom
Quantitative Analyst | QuantCourse.com
100,000 randomly generated portfolios
Ra − rf
S=
σa
S: Sharpe Ratio
Ra : Asset return
rf : Risk-free rate of return
σa : Asset volatility
numstocks = 5
risk_free = 0
df["Sharpe"] = (df["Returns"] - risk_free) / df["Volatility
MSR = df.sort_values(by=['Sharpe'], ascending=False)
MSR_weights = MSR.iloc[0, 0:numstocks]
np.array(MSR_weights)
numstocks = 5
GMV = df.sort_values(by=['Volatility'], ascending=True)
GMV_weights = GMV.iloc[0, 0:numstocks]
np.array(GMV_weights)