I have some difficulties in coding a strategy and I'm looking for some help.
The strategy is on 4 ETFs : IEF, TLH, TLT, IEI
The goal is to allocate anywhere from 0-25% of the portfolio to each ETFs. This allocation is based on trailing 1,2,3,4,5-month total returns (21, 42, 63, 84 and 105 trading days), with each positive lookback contributing 5% to the total allocation for that ETF.
For example let's say for IEF we have :
1mo = +4%, 2mo = +3%, 3mo = +1%, 4mo = -3%, 5mo = +3.5%
Result = 4 / 5 lookbacks are positive so we allocate 20% of capital to IEF
This computation is only done with IEF , TLH , TLT. The remaining capital goes to IEI (considering as cash)
For example if we have 20% IEF + 15% TLH + 20% TLT = 55% of the portfolio is used, the remaining 45% goes to IEI
This is what I done for now
#------------------------------------------------------------------------------
asset=symbols('IEI','IEF','TLH','TLT'); M=21
#------------------------------------------------------------------------------
def initialize(context):
schedule_function(trade,date_rules.month_end(),
time_rules.market_close(minutes=30))
def trade(context,data):
price = data.history(asset,'close',M*12,'1d')
mom1 = price.pct_change(M).iloc[-1]
mom2 = price.pct_change(M*2).iloc[-1]
mom3 = price.pct_change(M*3).iloc[-1]
mom4 = price.pct_change(M*4).iloc[-1]
mom5 = price.pct_change(M*5).iloc[-1]
But my problem is that I have difficulties to code a line that counts the number of positive lookbacks for each ETF.
If somebody has an idea on the way to do it you are welcome.
Thanks