Back to Community
using history() to calculate 60 and 20 minute moving averages

I'm trying to creating a minute-by-minute moving average crossover using the 60 and 20 minutes moving averages for the SPY ETF. Experienced C/C++ programmer but new to python and even newer to quantopian/zipline.

My initial thought was to use a .history() after setting my universe to include only the SPY ETF. I was able to figure out how to get the price for each minute for the previous hour, but I can't find a straight answer on how to select a certain amount of previous bars of price data and calculate the mean.

I could use help with this as well as a general guide to using pandas.

1 response

Attached should get you started. Since you already know C, should take you no time to learn Python, and the libraries/framework used in Python. Just hang in there, walk through the documents, then the codes of a few popular strategies. Before you know it, your mind will be speaking to you in Python.

Clone Algorithm
332
Loading...
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
import numpy as np
import pandas as pd
import math

resolution = '1m'
w_small = 20 
w_large = 60    
show_off = True


def initialize(context):    
    # initialize stock of interest
    context.spy = symbol('SPY')                
    if show_off:
        # give me some break    
        set_commission(commission.PerShare(cost=0.00))
        set_slippage(slippage.FixedSlippage(spread=0.00))   
        
def handle_data(context, data):
    myfunc(context, data)
    record(leverage = context.portfolio.positions_value / context.portfolio.portfolio_value)

def myfunc(context, data):
    # get historical price
    h = history(w_large, resolution, 'price')    
    
    # calculate moving average using predefined sizes
    mov_avg = {}
    for window in [w_small,w_large]:
        mov_avg[window] = h[context.spy].ix[window*-1:].mean()
        
    # logging
    log.info('window:avg, %r'%mov_avg)
    
    # moving average cross over strategy
    if mov_avg[w_small] > mov_avg[w_large]:
        direction = 1.0
    else:
        direction = -1.0
    order_target_percent(context.spy,1*direction)
There was a runtime error.