Sample code: Implementing moving average crossover strategy using IBridgePy

The moving average crossover strategy is a popular algorithmic trading approach. This moving average crossover strategy analyzes when fast and slow moving averages intersect to generate trading signals with Interactive Brokers and Python.

moving average crossover

Understanding Moving Average Crossover Strategy

Moving average crossover strategy is one of the popular strategies that lots of traders have paid attention to. The details of the strategy is described at Wikipedia. https://en.wikipedia.org/wiki/Moving_average_crossover

EXCLUSIVE OFFER

Extra 7% OFF All Quantra Courses

Level up your quant trading skills with courses from Quantra by QuantInsti — Python for trading, machine learning strategies, options trading, and more.

HUI7 Browse Courses → Use code HUI7 at checkout

In a short summary of moving average crossover strategy, the trend of the security is going up when the fast moving average line cross over the slow moving average line from the lower area and it is a signal about long positions.

In the following example, the code calculates the moving average of 5 (fast moving average line) and 15 (slow moving average line) at 15:59:00 US Eastern time, 1 min before the market closes, on every trading day. It places an order of SPY, ETF tracking S&P 500, when the fast moving average line starts to cross over the slow moving average line and exits the positions when crossover happens in the opposite direction.

The code can be backtested at Quantopian.com because IBridgePy can run most of the strategies posted at Quantopian without any changes.

Need help building this strategy?

Our Rent-a-Coder team builds custom automated trading programs. From simple scripts to complex multi-account strategies — we handle it all.

If you need any help to live trader your codes from Quantopian, please contact with us at IBridgePy@gmail.com

Rent-a-Coder

 

# -*- coding: utf-8 -*-
'''
There is a risk of loss in stocks, futures, forex and options trading. Please
trade with capital you can afford to lose. Past performance is not necessarily 
indicative of future results. Nothing in this computer program/code is intended
to be a recommendation to buy or sell any stocks or futures or options or any 
tradable securities. 
All information and computer programs provided is for education and 
entertainment purpose only; accuracy and thoroughness cannot be guaranteed. 
Readers/users are solely responsible for how they use the information and for 
their results.

If you have any questions, please send email to IBridgePy@gmail.com
'''

# This code can be backtested at Quantopian
import pandas as pd
def initialize(context):
    context.security=symbol('SPY') # Define a security, SP500 ETF
    
    # schedule_function is an IBridgePy function, also supported by Quantopian
    # date_rules.every_day : the dailyFunc will be run on every business day
    # time_rules.market_close(minutes=1) : the time to run dailyFunc is 
    # 1 mintue before U.S. market close (15:59:00 US/Eastern time)
    schedule_function(dailyFunc, date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_close(minutes=1))

    
def dailyFunc(context, data):
    # dailyFunc is scheduled by schedule_function
    # It will run at 15:59:00 US/Eastern time on every business day
    hist = data.history(context.security, 'close', 20, '1d')
    
    # Calculate 5 days and 15 days moving average
    MA5 = hist.rolling(window=5).mean()[-1]
    MA15 = hist.rolling(window=15).mean()[-1]
    current_price = hist[-1]
    
    # Get current position
    current_position = context.portfolio.positions[context.security].amount
    
    print('current_position=', current_position)
    print('current_price=', current_price, 'MA5=', MA5, 'MA15=', MA15)
    
    # Buy signal: MA5 crosses above MA15
    if MA5 > MA15 and current_position == 0:
        order_target_percent(context.security, 1.0)
        print('Buy', context.security)
    
    # Sell signal: MA5 crosses below MA15
    elif MA5 < MA15 and current_position > 0:
        order_target_percent(context.security, 0.0)
        print('Sell', context.security)

Implementation Tips

When implementing technical indicators, consider using longer lookback periods during volatile markets. Always backtest your parameters thoroughly before live deployment.

For more trading strategies and examples, check our tutorials or visit our documentation.

EXCLUSIVE OFFER

Extra 7% OFF All Quantra Courses

Level up your quant trading skills with courses from Quantra by QuantInsti — Python for trading, machine learning strategies, options trading, and more.

HUI7 Browse Courses → Use code HUI7 at checkout

Ready to Automate Your Trading?

Download IBridgePy free or let our coders build your strategy.

Download Free Hire a Coder

11 thoughts on “Sample code: Implementing moving average crossover strategy using IBridgePy”

  1. dancejj@yahoo.com

    Hi!

    The following message
    AttributeError: module ‘pandas’ has no attribute ‘rolling_mean’
    is displayed when running the code. Any ideas how to fix it? Thank you.

  2. Hi, I can show the real time price of ‘CASH,EUR,USD’ without any problem, but I got an error when I try to show the real time price of CL light sweet crude oil futures(WTI) Nov 2018 with the command line below. please let me know what the right format is for Futures, thanks a lot.

    print (“CL 201811 ask_price=”,show_real_time_price(symbol(‘FUT,CL,USD,201811′),’ask_price’))

  3. Hi,
    Tried importing pandas.rolling_mean but got an error below.
    ModuleNotFoundError: No module named ‘pandas.rolling_mean’
    Any idea to fix it? thanks

  4. Can I use only IBridgePy & TWS without Quantopian?
    Your code, as presented, above “runs” error-free but no results.
    Is there a complete example (single script) that does say MA crossover in Spyder(3.2.8) with Anaconda36_64 including connection to kernel?
    thanks

  5. I had a question what should I do if my algo gets disconnected due to some issue so all my information saved in context variables would lost what should I do if my algo gets disconnect and I reconnect all varible info is loaded again ?

    1. If you hard-code information in context variables and run your algo again, they will show up again. If you save information to context variables during your code, you may consider to write to a csv file and read them in as needed.

  6. what logic should one put to detect the algo has disconnected and when
    what is in my mind keeping the iteration count of handle data and one the algo gets disconnected iteration count and then i start algo say 5 minutes later say algo got disconnected at 10:15 and i restarted algo at say 10:30 . and lets handle data is running every minute so in my variable where i was recording the handle data iterration count it would have 60 assuming market started at 9:15 and when i restarted the algo at 10:30 iteration count of handle data should have been 75 which is not so program would know the algo was disconnected and load information in context variables through CSV where I have recorded them do u think this is a good logic to loading a previous information in context variables when algo gets disconnected or can u give some suggestions

Leave a Comment