quantopian / zipline

Zipline, a Pythonic Algorithmic Trading Library
https://www.zipline.io
Apache License 2.0
17.7k stars 4.73k forks source link

Zipline Custom Calendar #2412

Open bluesky9188 opened 5 years ago

bluesky9188 commented 5 years ago

Dear Zipline Maintainers,

Before I tell you about my issue, let me describe my environment:

Environment

asn1crypto==0.24.0 attrs==18.2.0 autobahn==19.1.1 Automat==0.7.0 backcall==0.1.0 bcolz==1.2.1 bleach==3.0.2 Bottleneck==1.2.1 certifi==2018.11.29 cffi==1.11.5 chardet==3.0.4 Click==7.0 colorama==0.4.1 constantly==15.1.0 contextlib2==0.5.5 cryptography==2.4.2 cycler==0.10.0 cyordereddict==1.0.0 Cython==0.29.2 dateparser==0.7.0 DateTime==4.3 decorator==4.3.0 defusedxml==0.5.0 empyrical==0.5.0 entrypoints==0.3 hyperlink==18.0.0 idna==2.8 incremental==17.5.0 inflection==0.3.1 intervaltree==3.0.2 ipykernel==5.1.0 ipython==7.2.0 ipython-genutils==0.2.0 ipywidgets==7.4.2 jedi==0.13.2 Jinja2==2.10 jsonschema==2.6.0 jupyter==1.0.0 jupyter-client==5.2.4 jupyter-console==6.0.0 jupyter-contrib-core==0.3.3 jupyter-contrib-nbextensions==0.5.1 jupyter-core==4.4.0 jupyter-highlight-selected-word==0.2.0 jupyter-latex-envs==1.4.6 jupyter-nbextensions-configurator==0.4.1 kiwisolver==1.0.1 Logbook==1.4.1 lru-dict==1.1.6 lxml==4.3.0 Mako==1.0.7 MarkupSafe==1.1.0 matplotlib==3.0.2 mistune==0.8.4 more-itertools==5.0.0 nbconvert==5.4.0 nbformat==4.4.0 networkx==2.2 notebook==5.7.4 numexpr==2.6.9 numpy==1.15.4+mkl pandas==0.23.4 pandas-datareader==0.7.0 pandocfilters==1.4.2 parso==0.3.1 pickleshare==0.7.5 prometheus-client==0.5.0 prompt-toolkit==2.0.7 pyasn1==0.4.5 pyasn1-modules==0.2.3 pycparser==2.19 Pygments==2.3.1 PyHamcrest==1.9.0 pyOpenSSL==18.0.0 pyparsing==2.3.0 python-binance==0.7.0 python-dateutil==2.7.5 python-editor==1.0.3 pytz==2018.9 pywinpty==0.5.5 PyYAML==3.13 pyzmq==17.1.2 qtconsole==4.4.3 Quandl==3.4.5 regex==2018.11.22 requests==2.21.0 scikit-learn==0.20.2 scipy==1.2.0 Send2Trash==1.5.0 service-identity==18.1.0 six==1.12.0 sklearn==0.0 sortedcontainers==2.1.0 SQLAlchemy==1.2.15 statsmodels==0.9.0 tables==3.4.4 terminado==0.8.1 testpath==0.4.2 toolz==0.9.0 tornado==5.1.1 trading-calendars==1.6.1 traitlets==4.3.2 Twisted==18.9.0 txaio==18.8.1 tzlocal==1.5.1 urllib3==1.24.1 wcwidth==0.1.7 webencodings==0.5.1 widgetsnbextension==3.4.2 win-unicode-console==0.5 wrapt==1.10.11 zipline==1.3.0 zope.interface==4.6.0

Now that you know a little about me, let me tell you about the issue I am having:

I try to build a 24/7 trading calendar for back testing of my data set. Here is the code I have for my exchange_calendar_TF.py

from datetime import time from pytz import timezone from pandas import date_range from .trading_calendar import TradingCalendar, HolidayCalendar from zipline.utils.memoize import lazyval from pandas.tseries.offsets import CustomBusinessDay

class TWTFCalendar(TradingCalendar): """ Round the clock calendar: 7/7, 24/24 """

@property
def name(self):
    return "TWTF"

@property
def tz(self):
    return timezone("UTC")

@property
def open_time(self):
    return time(0)

@property
def close_time(self):
    return time(23, 59)

@property
def regular_holidays(self):
    return []

@property
def special_opens(self):
    return []

def sessions_in_range(self, start_session, last_session):
    return date_range(start_session, last_session)

@lazyval
def day(self):
    return CustomBusinessDay(holidays=self.adhoc_holidays,
    calendar=self.regular_holidays,weekmask="Mon Tue Wed Thu Fri Sat Sun")

Then I import it in my notebook for back testing of strategies. The truncated codes are pasted below:

from collections import OrderedDict import pandas as pd import pytz from zipline.api import order, record, symbol, set_benchmark, order_target_percent, get_open_orders from zipline.utils.trading_calendars.exchange_calendar_TF import TWTFCalendar import zipline import matplotlib.pyplot as plt from datetime import datetime

........

perf = zipline.run_algorithm(start=datetime(2018, 12, 1, 0, 0, 0, 0, pytz.utc), end=datetime(2018, 12, 31, 0, 0, 0, 0, pytz.utc), initialize=initialize, trading_calendar=TWTFCalendar(), capital_base=10000, handle_data=handle_data, data_frequency='minute', data=panel)

However, I get this trackback error:


TypeError Traceback (most recent call last)

in 47 end=datetime(2018, 12, 31, 0, 0, 0, 0, pytz.utc), 48 initialize=initialize, ---> 49 trading_calendar=TWTFCalendar(), 50 capital_base=10000, 51 handle_data=handle_data, TypeError: Can't instantiate abstract class TWTFCalendar with abstract methods close_times, open_times I did define open_time and close_time in my calendar, so I am confused where this issue comes from. Can someone help me to take a look? Thanks bluesky9188
mustafa-qamaruddin commented 5 years ago

How have you solved this issue? I'm getting it too.

mustafa-qamaruddin commented 5 years ago

I have found these abstract methods which may signal the reason:

` @abstractproperty def open_times(self): """ Returns a list of tuples of (start_date, open_time). If the open time is constant throughout the calendar, use None for the start_date. """ raise NotImplementedError()

@abstractproperty
def close_times(self):
    """
    Returns a list of tuples of (start_date, close_time).  If the close
    time is constant throughout the calendar, use None for the start_date.
    """
    raise NotImplementedError()

`

mustafa-qamaruddin commented 5 years ago

`

@property def opentimes(self): return [(None, time(0, 0)) for in range(7)]

@property
def close_times(self):
    return [(None, time(23, 59)) for _ in range(7)]

`

This seems to solve the issue

ksyme99 commented 5 years ago

I have found the documentation to be out of date for the TFS calendar. This works for me (M-F):


class TFSExchangeCalendar(TradingCalendar):

    name = "TFS"

    tz = timezone("UTC")

    open_times = (
        (None, time(00, 00)),
    )

    close_times = (
        (None, time(23, 59)),
    )
zfei commented 5 years ago

Right, the documentation seems outdated. For 24/7 calendar though, I'm directly registering AlwaysOpenCalendar from trading_calendars.always_open.

ksyme99 commented 5 years ago

Right, the documentation seems outdated. For 24/7 calendar though, I'm directly registering AlwaysOpenCalendar from trading_calendars.always_open.

Note this is also open at the weekends, the default TradingCalendar is only open weekdays, so the version I showed is only open weekdays.

zfei commented 5 years ago

I see, what about WeekdayCalendar from trading_calendars.weekday_calendar?

ksyme99 commented 5 years ago

I see, what about WeekdayCalendar from trading_calendars.weekday_calendar?

Yeah that is exactly equivalent to what I showed, open every hour of weekdays.

class WeekdayCalendar(TradingCalendar):
    """
    A TradingCalendar for an exchange that is open every minute of every
    weekday.
    """
    name = '24/5'
    tz = UTC
    open_times = (
        (None, time(0)),
    )
    close_times = (
        (None, time(23, 59)),
    )
mustafa-qamaruddin commented 5 years ago

Thank you

geomuse commented 5 years ago

hi , anyone if i want to pass the date , how to do ?

'''
'''
from trading_calendars import register_calendar, TradingCalendar
class TwseCalendar(TradingCalendar):
    """
    Exchange calendar for the Taiwan Stock Exchange
    on 2001 https://www.ithome.com.tw/node/7930
    Open Time: 9:00 AM, GMT
    Close Time: 1:30 PM, GMT
    """
    @property
    def name(self):
        return "TWSE"

    @property
    def tz(self):
#         return pytz.timezone('Asia/Taipei')
        return pytz.timezone("UTC")
    open_times = (
        (None, time(0)),
    )
    close_times = (
        (None, time(23, 59)),
    )

    @property
    def regular_holidays(self):
        return  [datetime.datetime(2019, 2, 8, tzinfo=pytz.utc),\
                 datetime.datetime(2019, 4, 4, tzinfo=pytz.utc)]

same the error message

KeyError: 'the label [2019-02-08 00:00:00+00:00] is not in the [index]'