Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Seeking help on coding an ETF strategy

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

3 responses

@Tony,

Try this:

# Tony B momentum by Vladimir v2  
import pandas as pd  
# ---------------------------------------------------------------------------------------------------  
assets = symbols('TLT','TLH','IEF'); bond = symbol('IEI');  M = 21; MOM = [M*1, M*2, M*3, M*4, M*5];  
signals = pd.DataFrame(0., index = MOM, columns = assets); LEV = 1.0;  
# ---------------------------------------------------------------------------------------------------  
def initialize(context):  
    schedule_function(trade,date_rules.month_end(), time_rules.market_open(minutes = 65))     

def trade(context,data):  
    price = data.history(assets,'close', M*5 + 1,'1d')  

    for m in MOM:  
        mom = price.pct_change(m).iloc[-1]  
        for sec in assets:  
            if mom[sec] >= 0: signals[sec][m] = 1  
            if mom[sec] < 0: signals[sec][m] = 0 

    wt = LEV*signals.sum() / len(MOM) / len(assets)  
    wt[bond] = LEV - wt.sum()  

    for sec, weight in wt.items():  
        order_target_percent(sec, weight); record(**{sec.symbol: weight})  

    record(leverage = context.account.leverage)

Here is an approach which builds on what was started. Use the numpy where method to convert positive and negative returns into 1s and 0s respectively. Then add the resulting values. The result will be a numpy array. Probably create a series by adding an index to associate the values with the assets. One can also multiply by the desired 5% weighting.

def trade(context,data):  
    price = data.history(ETFS,'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]

    mom1_positive = np.where(mom1>0, 1, 0)  
    mom2_positive = np.where(mom2>0, 1, 0)  
    mom3_positive = np.where(mom3>0, 1, 0)  
    mom4_positive = np.where(mom4>0, 1, 0)  
    mom5_positive = np.where(mom5>0, 1, 0)

    positive_counts = mom1_positive + mom2_positive + mom3_positive + mom4_positive + mom5_positive

    weights = pd.Series(positive_counts * .05, index=price.columns)

However, if one wants actual month to month momentum (rather than assuming 21 days in a month), then the pandas resample method works great.

def trade(context, data):  
    price = data.history(ETFS, 'close', M*12, '1d')

    # resample to just get the month end prices  
    # only look at the last 5 months (6 including current month)  
    last_5_month_end_prices = price.resample('M').last().tail(6)

    # momentum will be positive if the current price > than the month end prices  
    positive_momentum_to_date = last_5_month_end_prices.iloc[-1] > last_5_month_end_prices

    # sum the positive momentums ie the True values  
    positive_momentum_counts = positive_momentum_to_date.sum()

    weights = positive_momentum_counts * .05

The attached algo implements this latter approach.

Good luck

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Hi @Vladimir, @Dan,

Thank you so much for your help and your advice