Skip to content

Instantly share code, notes, and snippets.

@degiere
Created April 14, 2016 07:25
Show Gist options
  • Select an option

  • Save degiere/e68b95ef2ef03418c20478177bd05f6d to your computer and use it in GitHub Desktop.

Select an option

Save degiere/e68b95ef2ef03418c20478177bd05f6d to your computer and use it in GitHub Desktop.
# Try to get futures working with Zipline
import pytz
import pandas as pd
import matplotlib.pyplot as plt
import Quandl
from zipline.api import *
from zipline.algorithm import TradingAlgorithm
from zipline.finance.trading import TradingEnvironment
def quandl_to_zipline(df):
df = df[['Open', 'High', 'Low', 'Last', 'Volume']]
df.columns = ['open', 'high', 'low', 'close', 'volume']
df['price'] = df['close']
df.index = df.index.tz_localize(pytz.utc)
return df
def initialize(context):
context.contracts = 2
def handle_data(context, data):
order(symbol(ticker), context.contracts)
if __name__ == "__main__":
# Fetch a continuous futures contract from Quandl
ticker = 'ES1'
df = Quandl.get("CHRIS/CME_" + ticker)
df = quandl_to_zipline(df['2014-01-01':])
# zipline wants a panel keyed by symbol
data = pd.Panel({ticker: df})
# Define futures data and point value / multiplier
metadata = {55555: {
'symbol': 'ES1',
'root_symbol': 'ES1',
'multiplier': 50.0,
'tick_size': 12.5,
'name': 'E-Mini S&P 500',
'asset_type': 'future'
}}
# Build environment, define and backtest algo
env = TradingEnvironment()
env.write_data(futures_data=metadata)
backtest = TradingAlgorithm(initialize=initialize, handle_data=handle_data, env=env)
perf = backtest.run(data)
# Show ending portfolio value
# TODO: unchanged by multiplier, what's missing?
print perf.portfolio_value[-1]
@pauljherrera
Copy link

Hello,

Could you run a futures script run in zipline?
I am trying to run this script you made but I get this error:

File "zipline_futures.py", line 23, in handle_data
order(symbol(ticker), context.contracts)
NameError: global name 'ticker' is not defined

I hardcoded the ticker name ('ES1') but I get this other error:

File "C:\Users\paulj\AppData\Local\conda\conda\envs\zipline2\lib\site-packages\zipline\assets\assets.py", line 708, in _lookup_symbol_strict
raise SymbolNotFound(symbol=symbol)
zipline.errors.SymbolNotFound: Symbol 'ES1' was not found.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment