Skip to content

Example Algorithms

1. Buy and Hold

1
2
3
4
5
6
7
8
9
def initialize(context):
    # Run user defined function at a set time
    schedule_function('trade',daterule='every_day',timerule='market_close')
    # Store variables in the 'context' object
    context.spy = 'SPY'

def trade(context):
    # Order 100% of portfolio with SPY
    order_target_percent(context.spy, 1.0)

2. 5SMA/15SMA Crossover

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import pandas
import numpy
import talib

def initialize(context):
    schedule_function('trade', daterule='every_day', timerule='market_open', time_offset=45)
    context.spy = 'SPY'

def trade(context):
    price_5 = data.history(context.spy,'close',5)
    price_15 = data.history(context.spy,'close',15)
    price_5_average = price_5.mean()
    price_15_average = price_15.mean()

    if price_5_average > price_15_average:
        order_target_percent(context.spy,2)
    else:
        order_target_percent(context.spy,0)

3. RSI

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import talib as tb

def initialize(context):
    schedule_function('trade',daterule='every_day',timerule='market_close')
    context.spy = 'SPY'

def trade(context):
    price = data.history(context.spy, 'close', 3)
    rsi = tb.RSI(price, timeperiod=2)[-1]

    if rsi < 20:
        order_target_percent(context.spy, 1.0)
    if rsi > 60:
        order_target_percent(context.spy, 0.0)