Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Feasibility of applying ADX, SAR, Moving averages as entry/exit constraints?

Hi all!

I am quite new to both python as well as back-testing strategies on Quantopian. I seek to eventually implement my strategies for live trading at some point. For now, I'm just happy learning the ropes.

I just wanted to ask if the following strategy could potentially be coded on the platform, given its current features/datas;

Conditions for entry / enter long if:
1) ADX (+ pdi > ndi) must be greater than certain threshold.
2) EMA (fast) is over SMA (slow)

Conditions for exit:
1) ADX (+ ndi > pdi) must be lower than certain threshold.
2) Parabolic SAR higher than current price

This algo will only seek to enter long. I would also ideally like to backtest this on multiple assets, including futures.

I already have the ADX part working, and I'm now looking to implement the second entry condition (moving average).

Thank you all for any guidance and help!

2 responses

This may help:

# ADX, PLUS_DI, MINUS_DI, SAR  
import talib  
# ---------------------------------------------------------------------  
stock, bond, period = symbol('QQQ'), symbol('TLT'), 14; bars = period*2  
# ---------------------------------------------------------------------  
def initialize(context):  
    schedule_function(trade , date_rules.every_day(), time_rules.market_open(minutes = 65))  

def trade (context, data):  
    if get_open_orders(): return  

    H = data.history(stock,'high', bars, '1d').dropna()  
    L = data.history(stock,'low', bars, '1d').dropna()  
    C = data.history(stock,'close', bars, '1d').dropna()  

    adx = talib.ADX(H, L, C, period)[-1]  
    mdi = talib.MINUS_DI(H, L, C, period)[-1]  
    pdi = talib.PLUS_DI(H, L, C, period)[-1]  
    sar = talib.SAR(H, L, 0.02, 0.2)[-1]  

    if (adx < 20 and mdi > pdi and sar > C[-1]):  
        wt_stk, wt_bnd = 0, 1.0  
    elif (adx > 20 and mdi < pdi):  
        wt_stk, wt_bnd = 1.0, 0  
    else: return  

    if all(data.can_trade([stock, bond])):  
        order_target_percent(stock, wt_stk)  
        order_target_percent(bond, wt_bnd)  

def before_trading_start(context,data):  
    record(leverage = context.account.leverage)  

Thank you very much for the code Vladimir. I just wanted to know if it would be possible to adjust the timeframes as well. Preferably it would be nice to see some hourly data. In addition to this, I am trying to apply this back-test to futures. I am using the function continuous_futures, but i get a syntax error message. I know that futures data is limited to certain periods only, but even when i try to adjust the back-test period i get the same error. Thanks for the help!