Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Help with algo!

Hi,

I'm brand new to quant programming and I would be so grateful if someone could help me with what I'm trying to do:

I would like for any stock to do the following:

  • buy when moving average 40 (ma40) crosses ma80 AND ma 40 & ma80 are both under ma120
  • sell when ma40>ma80>ma120

now I want this on a 1-minute chart not on a daily chart which seems to happen on my algo. Also anytime I clone ma crossover algos I seem to have all trades done between 9.30am and 11am why is that happening?

Thank you so much in advance for your help!

Max

5 responses

Maximilien,

This should get you started. Note that you are running the back test on minute bars, so the moving averages are on minute data (not daily).

# Talib average price data  
mavg_short_data = ta.MA(timeperiod=40)  
mavg_long_data = ta.MA(timeperiod=80)  
mavg_signal_data = ta.MA(timeperiod=120)

def initialize(context):  
    context.stock = sid(39840)


def handle_data(context, data):  
    stock_data = data[context.stock]  
    current_price = stock_data.price  
    mavg_short = mavg_short_data(data)[context.stock]  
    mavg_long = mavg_long_data(data)[context.stock]  
    mavg_signal = mavg_signal_data(data)[context.stock]

    record(price=current_price, fast=mavg_short, slow=mavg_long, signal=mavg_signal)

    # Log results  
    output = str('Date: {0}  Price: {1:.2f}  Short: {2:.2f}  Long: {3:.2f}  Signal: {4:.2f}'\  
             .format(stock_data.datetime.strftime('%Y-%b-%d  %H:%M'),current_price, mavg_short, mavg_long, mavg_signal))  
    log.info(output)  

I've fixed couple of things in your algo and added timestamps to debug output, so you can see when your orders are created. Hope this helps to debug it further.

Hey Maximilien,

I made a few edits to your algorithm, graphing the three moving averages as well as the price. Make sure to import talib and use the SMA (simple moving average) function. I do not see MA listed as a function in the TALib documentation (http://qtstalker.sourceforge.net/talib.html). There are many different types of moving averages given, and I assume you are looking for a simple moving average.

Ryan

MA is ta TALib function which defaults to SMA if no type is given.

The TALib function list is here.

The Quantopian description of the TALib functions is here.

Thank you all for your help it is exactly what I needed. Quick question if I were to remove mavg_signal how can I just code ema_short crossing ema_long from below vs. just ema_short crossing ema_long?