Back to Community
Example code for your first Quantopian Algorithm

Hi, for a class I'm giving at Harbour Space about Algotrading, I've created this example code, which can be used as a template to start with. Note that the algorithm is quite stupid, you switch from long to short and from short to long on each 5th day. So day 0, you are long, day 5 you go short, day 10 you go long again, etcetera.

Clone Algorithm
24
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
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
# Called once at the start of the simulation.
# 'context' is the variable which is kind of the global variables. Put all the important stuff which you need in other functions in there.
def initialize(context):
    """
    Called when the algorithm is started.
    """
    # Create a new global variable called 'sp500' and reference to the S&P500 ETF.
    # The 'sid' is the function which searches for the object by id of the security. Note that you can also just search on name of the product while filling in the id!!
    context.sp500 = sid(8554)
    
    # Set a global variable isShort
    context.isShort = False

    # 'schedule_function' will schedule a function (now the 'my_rebalance' function) for certain times. Rebalance every day, an hour after market open. For the apple stock this will be at 14:30 or 15:30 GMT depending on summer or winter time.
    schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open(hours=1))

def my_rebalance(context, data):
    """
    Called if scheduled.
    """
    # Example (weird) metric: change psoition from long to short or from short to long depending when the day is divisible by 5.(NOTE THAT WEEKENDS ARE NO TRADING DAYS)
    if get_datetime().day % 5 == 0 and context.isShort:
        # Go long
        order_target_percent(context.sp500, 1.00)
        context.isShort = False
    elif get_datetime().day % 5 == 0 and not context.isShort:
        # Go short
        context.isShort = True
        order_target_percent(context.sp500, -1.00)
        

def handle_data(context, data):
    """
    Called every time there is new data (most of the product have minute data).
    """
    pass
There was a runtime error.