In [1]:
%load_ext watermark
%watermark -a 'cs224' -u -d -v -p numpy,pandas,matplotlib,seaborn,sklearn,h5py,zipline,pyfolio,dill,xlrd
cs224 
last updated: 2020-12-30 

CPython 3.6.12
IPython 7.16.1

numpy 1.19.1
pandas 0.22.0
matplotlib 3.3.1
seaborn 0.11.0
sklearn 0.23.2
h5py 2.10.0
zipline 1.4.1
pyfolio 0.9.2
dill 0.3.2
xlrd 1.2.0
In [2]:
%matplotlib inline
In [3]:
import zipline
from zipline.api import future_symbol,  set_commission, set_slippage, schedule_function, date_rules, time_rules, continuous_future, order_target
from datetime import datetime
import pytz
import matplotlib.pyplot as plt
import pyfolio as pf
import pandas as pd
import numpy as np  
from zipline.finance.commission import PerTrade, PerContract
from zipline.finance.slippage import VolumeShareSlippage, FixedSlippage, VolatilityVolumeShare

import warnings
import dill
In [4]:
from IPython.display import display, HTML

from IPython.display import display_html
def display_side_by_side(*args):
    html_str=''
    for df in args:
        if type(df) == np.ndarray:
            df = pd.DataFrame(df)
        html_str+=df.to_html()
    html_str = html_str.replace('table','table style="display:inline"')
    # print(html_str)
    display_html(html_str,raw=True)

CSS = """
.output {
    flex-direction: row;
}
"""

def display_graphs_side_by_side(*args):
    html_str='<table><tr>'
    for g in args:
        html_str += '<td>'
        html_str += g._repr_svg_()
        html_str += '</td>'
    html_str += '</tr></table>'
    display_html(html_str,raw=True)
    

display(HTML("<style>.container { width:70% !important; }</style>"))
In [5]:
import os

from zipline.utils.run_algo import load_extensions

load_extensions(
    default=True,
    extensions=['/home/cs/.zipline/extension.py'],
    strict=True,
    environ=os.environ,
)
In [6]:
from zipline.data.data_portal import DataPortal
from zipline.data import bundles
# from zipline.utils.calendars.calendar_utils import get_calendar
from trading_calendars import register_calendar, get_calendar

cal = get_calendar('us_futures')

bundle_name = 'csi_futures_data' # "a bundle name"
bundle_data = bundles.load(bundle_name)
In [7]:
data_por = DataPortal(bundle_data.asset_finder, 
                      cal,
                      bundle_data.equity_daily_bar_reader.first_trading_day,
                      equity_minute_reader=bundle_data.equity_minute_bar_reader,
                      equity_daily_reader=bundle_data.equity_daily_bar_reader,
                      future_daily_reader=bundle_data.equity_daily_bar_reader,
                      adjustment_reader=bundle_data.adjustment_reader)
In [8]:
base_symbol = 'CT'
In [9]:
data_por.asset_finder.retrieve_all(data_por.asset_finder._get_contract_sids(base_symbol))[:5]
Out[9]:
[Future(350 [CTV00]),
 Future(351 [CTZ00]),
 Future(352 [CTH01]),
 Future(353 [CTK01]),
 Future(354 [CTN01])]
In [10]:
sym = data_por.asset_finder.create_continuous_future(base_symbol, offset=0, roll_style='calendar', adjustment=None)
sym
Out[10]:
ContinuousFuture(91008776454275072, root_symbol='CT', offset=0, roll_style='calendar', adjustment=None)
In [11]:
frequency='1d'
bar_count=250
ldf1 = data_por.get_history_window(assets=[sym],
                                   end_dt=pd.Timestamp('2018-01-01', tz='utc'),
                                   bar_count=bar_count,
                                   frequency=frequency,
                                   data_frequency='daily',
                                   field='close')
ldf1.head()
Out[11]:
ContinuousFuture(91008776454275072 [CT, 0, calendar, None])
2017-01-13 00:00:00+00:00 0.723
2017-01-16 00:00:00+00:00 0.723
2017-01-17 00:00:00+00:00 0.721
2017-01-18 00:00:00+00:00 0.723
2017-01-19 00:00:00+00:00 0.727
In [12]:
ldf1.tail()
Out[12]:
ContinuousFuture(91008776454275072 [CT, 0, calendar, None])
2017-12-26 00:00:00+00:00 0.774
2017-12-27 00:00:00+00:00 0.790
2017-12-28 00:00:00+00:00 0.788
2017-12-29 00:00:00+00:00 0.786
2018-01-02 00:00:00+00:00 0.775
In [13]:
dt=pd.Timestamp('2018-01-01', tz='utc')
simulation_dt_func = lambda: pd.Timestamp(dt)
data_frequency = 'daily'
restrictions = zipline.finance.asset_restrictions.NoRestrictions()
data = zipline._protocol.BarData(data_por, simulation_dt_func, data_frequency, cal, restrictions)
In [14]:
fields=['close', 'volume']
h = data.history([sym], fields=fields, frequency=frequency, bar_count=bar_count)
ldf2 = h.xs(sym, 2)
ldf2.head()
Out[14]:
close volume
2017-01-13 00:00:00+00:00 0.723 12870.0
2017-01-16 00:00:00+00:00 0.723 12870.0
2017-01-17 00:00:00+00:00 0.721 16974.0
2017-01-18 00:00:00+00:00 0.723 12813.0
2017-01-19 00:00:00+00:00 0.727 13939.0
In [15]:
ldf2.tail()
Out[15]:
close volume
2017-12-26 00:00:00+00:00 0.774 9161.0
2017-12-27 00:00:00+00:00 0.790 19521.0
2017-12-28 00:00:00+00:00 0.788 13448.0
2017-12-29 00:00:00+00:00 0.786 14101.0
2018-01-02 00:00:00+00:00 0.775 22644.0
In [ ]: