Back to Community
Moving average crossover codes buys throughout the crossover

Hi all,

My team has put together a relatively simple code that looks to buy into a stock with 50% of my portfolio whenever the 13 day moving average cross over the 48 day moving average. The sell is triggered when the 48 crosses over the 30, and all shares are sold.

The main problem is that the buys seem to execute for as long as the 13 is above the 48, instead of at the close of the minute when the 13 crosses. Is there a way to fix this?

Clone Algorithm
Backtest from to with initial capital
Total Returns
Max Drawdown
Benchmark Returns
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
import talib
import numpy as np
import pandas as pd

def initialize(context):
    #using Google (solid blue chip stock)
    context.stock = symbol('AAPL')

def handle_data(context, data):
    stock = context.stock
    context.pct_per_stock = .50 #/ len(context.stocks)
    #current and historic data from AAPL
    stock_data = data.history(stock, 'price', 48, '1d')
    #moving average price data
    price_hist = data.history(stock, 'price', 13, '1d')
    shortmavg = price_hist.mean()
    longmavg = stock_data.mean()
    #mavg_short_buy = stock_data.mavg(5)
    #mavg_long_buy = stock_data.mavg(20)
    # current price of the stock
    # log.debug(type(stock_data))
    # log.debug(len(stock_data))
    # log.debug(stock_data)
    # current_price = stock_data[stock]
    # log.debug(current_price)
    #or = stock_price. need to check

    # how much cash in portfolio
    #cash =
    if shortmavg > longmavg: #and current_position < 1: #and cash > current_price:
        # place the buy order
         order_target_percent(stock, context.pct_per_stock) 
    elif shortmavg < longmavg and current_position > 0:
        #how many shares we have
        number_of_shares = context.portfolio.positions[stock.sid].amount
        #sell all shares
        order_target(stock, 0)
There was a runtime error.
6 responses

Bump anyone? Any feedback would be greatly appreciated!


The algorithm is executing every minute because the logic is in the handle_data function.
Placing the code in a separate function, and using schedule_function will cause it to be executed at a specific time (e.g. once a day at the market open).

More information about schedule_function can be found at the Getting Started tutorials.

Lotanna Ezenwa


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.


For lack of sufficient clarification, I find the API documentation confusing. I also read "Getting Started". Can you explain how to set the schedule_function() for daily, every 5 minutes?

This is every day, 1 minute before close ...... time_rules.market_open(hours=0, minutes=1)

Is this every 5 minutes?................................

time_rules.market_open(hours=0, minutes=0) or
time_rules.market_open(hours=0, minutes=5) or
time_rules.market_open(hours=0, minutes=10) or
time_rules.market_open(hours=0, minutes=15) or
time_rules.market_open(hours=0, minutes=20) or
.... etc.


There are multiple ways to go about it.
You could do something like this. It schedules a function to be run every five minutes.

for x in range(0,355,5):  
    schedule_function(my_func, date_rules.every_day(), time_rules.market_open(minutes=x))  

Or this way.
This exits the handle_data function if the minute isn't divisible by 5.

def handle_data(context, data):  
     now = get_datetime()  
     if now.minute % 5 !=0:  


Thanks. I now see a similar code snippet of your first example in the Overview document section. I had skipped over that to look at the API Document.

If I'm correct in my thinking, the schedule_function() and get_time() functions uses/returns end-of-period times. So 'time_rules.market_open(minutes=0)' equates to one minute after open. For equities, that makes the last minute period not tradable until the opening of the next day.

How does one trade the opening bell, that is before completion of the first one minute period?

time_rules.market_open(minutes= -1)

could you possibly post your updated code?