Hi guys,
I am trying to implement an adaptive asset allocation based on the following steps:
1. Trade 10 asset classes using ETFs (VTI, VGK, VPL, VWO, IEF, TLT, DBC, GLD, VNQ, VNQI)
2. Rank and filter the top 5 asset classes by momentum, as defined by exponential regression times coefficient of determination on closing prices for the past 20,40,60,...,240 days
3. For each sample, build a minimum variance portfolio using covariance matrices for each of the past 30,60,90,...,150 days and scale to 10% annualized volatility
4. All 60 portfolios are averaged together to form an optimal portfolio for that particular day, any position less than 5% weight will be left out
5. Rebalance only when there is more than 5% change in risk or 3% weight difference in any position
I am a newbie in programming and would like some help to complete my algorithm below:
Start of algo
import numpy as np
import scipy as sp
def initialize(context):
# ETFs: VTI, VGK, VPL, VWO, IEF, TLT, DBC, GLD, VNQ, VNQI
context.etfs = [sid(22739), sid(27100), sid(27101), sid(27102), sid(23870), sid(23921), sid(28054), sid(26807), sid(26669), sid(40337)]
def adj_mom(y):
x = np.arange(len(y))
slope, intercept, r_value, p_value, std_err = sp.stats.linregress(x,y)
return slope * (r_value **2)
n = 100
def before_trading_start(context,data):
# Get historical close prices for the past 300 days
hist = data.history(context.etfs,'close',300,'1d')
# Calculate momentum for each asset class
momentum = np.log(hist[-n:]).apply(adj_mom)
# Calculate log returns for each asset class
log_rtn = np.diff([np.array(np.log(hist[-n-1:-1])),(np.log(hist[-n:]))],axis=0)