Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually provide a benchmark in zipline

I want to create a reproducible example where the traded series and the benchmark are manually provided. This would make the life of people that are approaching to zipline incredibly easier. In fact, given the recent shut down of Yahoo!Finance API, even introductory examples with zipline are not going to work anymore since an HTTP error will be returned when trying to import the ^GSPC benchmark from Yahoo behind the scenes. As a consequence, nowadays there is not a single code snippet from the official tutorial that works AFAIK.

import pytz
from pandas_datareader import DataReader
from collections import OrderedDict
from zipline.algorithm import TradingAlgorithm
from zipline.api import order, record, symbol, set_benchmark
# Import data from yahoo
data = OrderedDict()
start_date = '01/01/2014'
end_date = '01/01/2017'
data['AAPL'] = DataReader('AAPL',
                          data_source='google',
                          start=start_date,
                          end=end_date)
data['SPY'] = DataReader('SPY',
                         data_source='google',
                         start=start_date,
                         end=end_date)
# panel.minor_axis is ['Open', 'High', 'Low', 'Close', 'Volume'].
panel = pd.Panel(data)
panel.major_axis = panel.major_axis.tz_localize(pytz.utc)

def initialize(context):
    set_benchmark(data['SPY'])

def handle_data(context, data):
    order(data['AAPL'], 10)
    record(AAPL=data.current(data['AAPL'], 'Close'))

algo_obj = TradingAlgorithm(initialize=initialize,
                            handle_data=handle_data,
                            capital_base=100000)
perf_manual = algo_obj.run(panel)

Returns: HTTPError: HTTP Error 404: Not Found

Question: how to make the strategy to work using AAPL as traded asset and SPY as benchmark? Constraint: AAPL and SPY must be manually provided as in the example.

like image 469
Elrond Avatar asked Oct 19 '25 03:10

Elrond


1 Answers

Disclaimer: I'm a maintainer of Zipline.

You can use the csvdir bundle to ingest csv files (tutorial here) and then make a call to set_benchmark() in your initialize() function. I'm also working a branch that allows zipline algorithms to run without a benchmark so even if you're not able to get benchmark data, your algorithm shouldn't crash.

like image 143
freddiev4 Avatar answered Oct 22 '25 00:10

freddiev4



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!