def test_force_registration(self): register_calendar("DMY", self.dummy_cal_type()) first_dummy = get_calendar("DMY") # force-register a new instance register_calendar("DMY", self.dummy_cal_type(), force=True) second_dummy = get_calendar("DMY") self.assertNotEqual(first_dummy, second_dummy)
def test_both_places_are_checked(self): dummy_cal = self.dummy_cal_type() # if instance is registered, can't register type with same name register_calendar('DMY', dummy_cal) with self.assertRaises(CalendarNameCollision): register_calendar_type('DMY', type(dummy_cal)) deregister_calendar('DMY') # if type is registered, can't register instance with same name register_calendar_type('DMY', type(dummy_cal)) with self.assertRaises(CalendarNameCollision): register_calendar('DMY', dummy_cal)
def test_register_calendar(self): # Build a fake calendar dummy_cal = self.dummy_cal_type() # Try to register and retrieve the calendar register_calendar('DMY', dummy_cal) retr_cal = get_calendar('DMY') self.assertEqual(dummy_cal, retr_cal) # Try to register again, expecting a name collision with self.assertRaises(CalendarNameCollision): register_calendar('DMY', dummy_cal) # Deregister the calendar and ensure that it is removed deregister_calendar('DMY') with self.assertRaises(InvalidCalendarName): get_calendar('DMY')
def run_example(example_name, environ): """ Run an example module from zipline.examples. """ mod = EXAMPLE_MODULES[example_name] register_calendar("YAHOO", get_calendar("NYSE"), force=True) return run_algorithm( initialize=getattr(mod, 'initialize', None), handle_data=getattr(mod, 'handle_data', None), before_trading_start=getattr(mod, 'before_trading_start', None), analyze=getattr(mod, 'analyze', None), bundle='test', environ=environ, # Provide a default capital base, but allow the test to override. **merge({'capital_base': 1e7}, mod._test_args()))
def run_example(example_name, environ): """ Run an example module from zipline.examples. """ mod = EXAMPLE_MODULES[example_name] register_calendar("YAHOO", get_calendar("NYSE"), force=True) return run_algorithm( initialize=getattr(mod, 'initialize', None), handle_data=getattr(mod, 'handle_data', None), before_trading_start=getattr(mod, 'before_trading_start', None), analyze=getattr(mod, 'analyze', None), bundle='test', environ=environ, # Provide a default capital base, but allow the test to override. **merge({'capital_base': 1e7}, mod._test_args()) )
def run_example(example_modules, example_name, environ, benchmark_returns=None): """ Run an example module from zipline.examples. """ mod = example_modules[example_name] register_calendar("YAHOO", get_calendar("NYSE"), force=True) return run_algorithm( initialize=getattr(mod, "initialize", None), handle_data=getattr(mod, "handle_data", None), before_trading_start=getattr(mod, "before_trading_start", None), analyze=getattr(mod, "analyze", None), bundle="test", environ=environ, benchmark_returns=benchmark_returns, # Provide a default capital base, but allow the test to override. **merge({"capital_base": 1e7}, mod._test_args()))
tz = timezone('UTC') weekmask = '1110011' open_times = ( (None, time(9, 31)), ) close_times = ( (None, time(16)), ) # register 'tse' calendar register_calendar('TSE', TehranExchangeCalendar( start=start_session, end=end_session)) # register the bundle """ command: zipline ingest --bundle tse_stocks """ register( 'tse_stocks', # name we select for the bundle csvdir_equities( # name of the directory as specified above (named after data frequency) ['daily'], # path to directory containing the path ), calendar_name='TSE', start_session=start_session,
def buyapple_example(): trading_calendars.register_calendar("YAHOO", trading_calendars.get_calendar("NYSE"), force=True) def initialize(context): context.asset = zipline.api.symbol("AAPL") # Explicitly set the commission/slippage to the "old" value until we can rebuild example data. # https://github.com/quantopian/zipline/blob/master/tests/resources/rebuild_example_data#L105 context.set_commission( zipline.finance.commission.PerShare(cost=.0075, min_trade_cost=1.0)) context.set_slippage(zipline.finance.slippage.VolumeShareSlippage()) def handle_data(context, data): zipline.api.order(context.asset, 10) zipline.api.record(AAPL=data.current(context.asset, "price")) # Note: this function can be removed if running this algorithm on quantopian.com. def analyze(context=None, results=None): import matplotlib.pyplot as plt # Plot the portfolio and asset data. ax1 = plt.subplot(211) results.portfolio_value.plot(ax=ax1) ax1.set_ylabel("Portfolio value (USD)") ax2 = plt.subplot(212, sharex=ax1) results.AAPL.plot(ax=ax2) ax2.set_ylabel("AAPL price (USD)") # Show the plot. plt.gcf().set_size_inches(18, 8) plt.show() start = datetime.datetime(2014, 1, 1, 0, 0, 0, 0, datetime.timezone.utc).date() #start = datetime.datetime(2014, 1, 1, 0, 0, 0, 0, pytz.utc).date() #start = pd.Timestamp("2014-01-01", tz="utc") end = datetime.datetime(2012, 11, 1, 0, 0, 0, 0, datetime.timezone.utc).date() #end = datetime.datetime(2014, 11, 1, 0, 0, 0, 0, pytz.utc).date() #end = pd.Timestamp("2014-11-01", tz="utc") zipline.run_algorithm( start=start, end=end, initialize=initialize, capital_base=1e7, handle_data=handle_data, before_trading_start=None, analyze=analyze, data_frequency="daily", bundle="quantopian-quandl", # zipline ingest -b quantopian-quandl bundle_timestamp=None, trading_calendar=None, metrics_set="default", benchmark_returns=None, default_extension=True, extensions=(), strict_extensions=True, environ=os.environ, blotter="default")
start_session, end_session, cache, show_progress, output_dir, start=start, end=end): if start is None: start = start_session if end is None: end = end_session sid_map = list(zip(range(len(symbols)), symbols)) adjustment_writer.write() asset_db_writer.write(equities=get_metadata(sid_map), exchanges=pd.DataFrame( data=[['binance', 'UTC']], columns=['exchange', 'timezone'])) minute_bar_writer.write(get_historical_minute_klines( sid_map, start, end, cache, show_progress), show_progress=show_progress) daily_bar_writer.write(get_historical_daily_klines( sid_map, start, end, cache, show_progress), show_progress=show_progress) return ingest register_calendar('BINANCE', BinanceCalendar())
@property def open_time(self): """ The time in which our exchange will open each day. """ return dt.time(0, 0) @property def close_time(self): """ The time in which our exchange will close each day. """ return dt.time(23, 59) @lazyval def day(self): """ The days on which our exchange will be open. """ weekmask = "Mon Tue Wed Thu Fri Sat Sun" return CustomBusinessDay(weekmask=weekmask) start_session = pd.Timestamp('2000-01-07', tz='utc') end_session = pd.Timestamp('2099-12-31', tz='utc') try: register_calendar( 'TFS', TFSExchangeCalendar(start=start_session, end=end_session)) except CalendarNameCollision: pass
"NYSE": NYSEExchangeCalendar, "OSE": OSEExchangeCalendar, "SEHK": SEHKExchangeCalendar, "SEHKNTL": SEHKNTLExchangeCalendar, "SBF": SBFExchangeCalendar, "SFB": SFBExchangeCalendar, "SGX": SGXExchangeCalendar, "TSE": TSEExchangeCalendar, "TSEJ": TSEJExchangeCalendar, } _ib_calendar_aliases = { "NASDAQ": "NYSE", "ARCA": "NYSE", "AMEX": "NYSE", "BATS": "NYSE", "IEX": "NYSE", "PINK": "NYSE", "ENEXT": "ENEXT.BE", "SEHKSZSE": "SEHKNTL" } ib_calendar_names = sorted( chain(_ib_calendar_factories.keys(), _ib_calendar_aliases.keys())) for name, calendar in _ib_calendar_factories.items(): register_calendar(name, calendar(), force=True) for alias, real_name in _ib_calendar_aliases.items(): register_calendar_alias(alias, real_name, force=True)
class AlgoSeekCalendar(XNYSExchangeCalendar): """ A calendar for trading assets before and after market hours Open Time: 4AM, US/Eastern Close Time: 19:59PM, US/Eastern """ @property def name(self): """ The name of the exchange that zipline looks for when we run our algorithm """ return "AlgoSeek" @property def tz(self): return timezone("US/Eastern") open_times = ((None, time(4, 1)), ) close_times = ((None, time(19, 59)), ) register_calendar('AlgoSeek', AlgoSeekCalendar()) register('algoseek', algoseek_to_bundle(), calendar_name='AlgoSeek', minutes_per_day=960)
def run_algorithm(start, end, initialize, capital_base=5e+6, handle_data=None, before_trading_start=None, analyze=None, data_frequency='daily', bundle='mydb', bundle_timestamp=None, trading_calendar=None, metrics_set='default', benchmark_returns=None, default_extension=True, extensions=(), strict_extensions=True, environ=os.environ, blotter='cn_blotter'): """ 运行交易策略算法. Parameters ---------- start : datetime 回测的开始时间. end : datetime 回测的结束时间. initialize : callable[context -> None] 策略算法的初始化函数, 每个回测开始前只运行一次, 用来设置策略算法的全局变量. capital_base : float 回测的初始资金. handle_data : callable[(context, BarData) -> None], optional 策略算法处理行情/执行下单操作的函数, 按照设置的策略频率执行. before_trading_start : callable[(context, BarData) -> None], optional 每个交易日开盘前执行的函数(在第一天的初始化函数结束后执行) analyze : callable[(context, pd.DataFrame) -> None], optional 在回测结束以后执行的分析函数. 传入参数为 ``context`` 和回测结果数据. data_frequency : {'daily', 'minute'}, optional 策略的执行频率. bundle : str, optional *zipline* 专用的数据格式组成的数据包. bundle_timestamp : datetime, optional 数据包的时间戳, 用来区分不同时间点的数据. trading_calendar : TradingCalendar, optional 回测用的交易日历. metrics_set : iterable[Metric] or str, optional 记录的回测性能指标集, :func:`zipline.finance.metrics.load` 根据名称调用. default_extension : bool, optional Should the default zipline extension be loaded. This is found at ``$ZIPLINE_ROOT/extension.py`` extensions : iterable[str], optional The names of any other extensions to load. Each element may either be a dotted module path like ``a.b.c`` or a path to a python file ending in ``.py`` like ``a/b/c.py``. strict_extensions : bool, optional Should the run fail if any extensions fail to load. If this is false, a warning will be raised instead. environ : mapping[str -> str], optional The os environment to use. Many extensions use this to get parameters. This defaults to ``os.environ``. blotter : str or zipline.finance.blotter.Blotter, optional 交易信息记录类, 调用前需要用 ``zipline.extensions.register`` 先注册. 默认为 :class:`zipline.finance.blotter.SimulationBlotter`, 永远不会取消订单. Returns ------- perf : pd.DataFrame 交易策略的每日回测结果. See Also -------- zipline.data.bundles.bundles : 可用的数据包. """ from trading_calendars import register_calendar from zipline_extensions_cn.utils import AShareCalendar from trading_calendars.errors import CalendarNameCollision try: register_calendar('AShare', AShareCalendar()) except CalendarNameCollision: pass #load_extensions(default_extension, extensions, strict_extensions, environ) if benchmark_returns is not None: benchmark_spec = BenchmarkSpec.from_returns(benchmark_returns) else: benchmark_spec = BenchmarkSpec(None, None, None, None, True) return _run( handle_data=handle_data, initialize=initialize, before_trading_start=before_trading_start, analyze=analyze, algofile=None, algotext=None, defines=(), data_frequency=data_frequency, capital_base=capital_base, bundle=bundle, bundle_timestamp=bundle_timestamp, start=start, end=end, output=os.devnull, trading_calendar=trading_calendar, print_algo=False, metrics_set=metrics_set, local_namespace=False, environ=environ, blotter=blotter, benchmark_spec=benchmark_spec, )