How to add custom trading calendar in zipline?

by jabari_okon , in category: Technical Analysis , 3 months ago

How to add custom trading calendar in zipline?

Facebook Twitter LinkedIn Whatsapp

1 answer

by stevie_prohaska , 3 months ago

@jabari_okon 

To add a custom trading calendar in Zipline, you need to create a new calendar file and register it with Zipline. Here are the steps:

  1. Create a new Python file for your custom calendar, e.g., my_calendar.py.
  2. Import the required libraries:
1
2
3
from pandas.tseries.offsets import CustomBusinessDay
from pandas.tseries.holiday import GoodFriday, Holiday, EasterMonday
from trading_calendars import register_calendar, TradingCalendar


  1. Define your custom calendar class by inheriting from TradingCalendar:
1
2
3
4
5
6
7
8
9
class MyCustomCalendar(TradingCalendar):
    # Define your calendar metadata
    # ...

    # Define your calendar rules
    # ...

    # Define your calendar schedule
    # ...


  1. Implement the __init__() method to set the name and tz attributes of your calendar, as well as the custom holiday rules:
1
2
3
4
5
6
def __init__(self):
    self.name = 'MY_CALENDAR'
    self.tz = 'UTC'

    # Define your custom holiday rules
    # ...


  1. Implement the all_sessions property to specify the trading days in your calendar:
1
2
3
4
@property
def all_sessions(self):
    # Define your calendar's trading schedule
    # ...


  1. Implement any additional methods or properties as needed for your custom calendar.
  2. Register your custom calendar with Zipline by calling the register_calendar() function and passing in the name of the calendar class and the name you wish to use to refer to it:
1
register_calendar('my_custom_calendar', MyCustomCalendar)


  1. In your main trading algorithm code, import your custom calendar and set it as the trading_calendar in run_algorithm():
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from zipline.api import run_algorithm
from my_calendar import MyCustomCalendar

if __name__ == '__main__':
    # ...

    run_algorithm(
        trading_calendar=MyCustomCalendar(),
        # ...
    )


That's it! Your custom trading calendar is now available for use in Zipline. You can define your own calendar metadata, rules, and schedule based on your specific trading needs.