def run_strategy(strategy_name): """ Run an example module from zipline.examples. """ mod = None if strategy_name == "buy_and_hold": mod = BuyAndHold() elif strategy_name == "auto_correlation": mod = AutoCorrelation() register_calendar("YAHOO", get_calendar("NYSE"), force=True) print('mod', type(mod), mod.__class__.__name__) print('mod._test_args()', mod._test_args()) 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='quantopian-quandl', # change from quandl -> quantopian-quandl environ=environ, # Provide a default capital base, but allow the test to override. **merge({'capital_base': 1e7}, mod._test_args()))
def main(): register_calendar('BITMEX', AlwaysOpenCalendar()) # The following is necessary because zipline's developer hard-coded NYSE # everywhere in run_algo._run, *DOH*!!! deregister_calendar('NYSE') register_calendar_alias('NYSE', 'BITMEX', force=False) register( 'bitmex', create_bundle( [ Pairs.symbol_btc, #Pairs.symbol_ada, #Pairs.symbol_bch, #Pairs.symbol_eos, #Pairs.symbol_eth, #Pairs.symbol_ltc, #Pairs.symbol_trx, #Pairs.symbol_xrp, ], pd.Timestamp('2017-11-05 00:00:00', tz='utc'), pd.Timestamp('2018-12-18 23:59:59', tz='utc'), ), calendar_name='BITMEX', minutes_per_day=24*60 )
def make_equity_info(cls): register_calendar("TEST", get_calendar("NYSE"), force=True) return make_simple_equity_info( cls.ASSET_FINDER_EQUITY_SIDS, cls.ASSET_FINDER_EQUITY_START_DATE, cls.ASSET_FINDER_EQUITY_END_DATE, cls.ASSET_FINDER_EQUITY_SYMBOLS, )
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_force_registration(self): dummy_nyse = self.dummy_cal_type('NYSE') # Get the actual NYSE calendar real_nyse = get_calendar('NYSE') # Force a registration of the dummy NYSE register_calendar(dummy_nyse, force=True) # Ensure that the dummy overwrote the real calendar retr_cal = get_calendar('NYSE') self.assertNotEqual(real_nyse, retr_cal)
def run_strategy(strategy_name): mod = None if strategy_name == "buy_and_hold": mod = BuyAndHold() 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='quandl', environ=environ, # Definimos un capital inicial que puede ser sobreescrito por el test **merge({'capital_base': 1e7}, mod._test_args()))
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 main(): register_calendar('CN_FUTURES', CN_FUTURE_CALENDAR(), force=True) deregister_calendar('NYSE') register_calendar_alias('NYSE', 'CN_FUTURES', force=True) register( 'CN_FUTURES', create_bundle( ['IC', 'IH', 'IF', 'RB'], pd.Timestamp('2017-09-20 01:31:00', tz='utc'), pd.Timestamp('2018-10-31 01:31:00', tz='utc'), ), calendar_name='CN_FUTURES', minutes_per_day=4 * 60 + 90 )
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_strategy(strategy_name): mod = None if strategy_name == "buy_and_hold": mod = BuyAndHold() 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='quandl', environ=environ, # Provide a default capital base, but allow the test to override. **merge({'capital_base': 1e7}, mod._test_args()))
def init_class_fixtures(cls): super(WithTradingCalendars, cls).init_class_fixtures() cls.trading_calendars = {} for cal_str in cls.TRADING_CALENDAR_STRS: # Set name to allow aliasing. calendar = get_calendar(cal_str) setattr(cls, '{0}_calendar'.format(cal_str.lower()), calendar) cls.trading_calendars[cal_str] = calendar for asset_type, cal_str in iteritems( cls.TRADING_CALENDAR_FOR_ASSET_TYPE): calendar = get_calendar(cal_str) cls.trading_calendars[asset_type] = calendar for exchange, cal_str in iteritems(cls.TRADING_CALENDAR_FOR_EXCHANGE): register_calendar(exchange, get_calendar(cal_str)) cls.trading_calendars[exchange] = get_calendar(cal_str)
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_strategy(strategy_name): """ Run strategies here """ # instantiate a strategy as a mod, change my strategy here: mod = None if strategy_name == "buy_and_hold": mod = BuyAndHold() # Here I set the trading calendar for a given exchange 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='quantopian-quandl', environ=environ, # allows the default capital base to be overidden by the strategy class **merge({'capital_base': 1e7}, mod._test_args()))
def run_strategy(strategy_name): """ Run an example module from zipline.examples. """ mod = None if strategy_name == 'scalping': mod = ScalpBollingerBands() 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='quandl', environ=environ, # Provide a default capital base, but allow the test to override. **merge({'capital_base': 1e7}, mod._test_args()) )
def should_clean(name): dt = from_bundle_ingest_dirname(name) return ((before is not None and dt < before) or (after is not None and dt > after)) elif keep_last >= 0: last_n_dts = set(take(keep_last, reversed(all_runs))) def should_clean(name): return name not in last_n_dts else: raise BadClean(before, after, keep_last) cleaned = set() for run in all_runs: if should_clean(run): path = pth.data_path([name, run], environ=environ) shutil.rmtree(path) cleaned.add(path) return cleaned return BundleCore(bundles, register, unregister, ingest, load, clean) bundles, register, unregister, ingest, load, clean = _make_bundle_core() register_calendar("YAHOO", get_calendar("NYSE")) register_calendar("QUANDL", get_calendar("NYSE"))
minute_bar_writer: BcolzMinuteBarWriter, daily_bar_writer: BcolzDailyBarWriter, adjustment_writer: SQLiteAdjustmentWriter, calendar: TradingCalendar, start_session: pd.Timestamp, end_session: pd.Timestamp, cache: dataframe_cache, show_progress: bool, output_dir: Text, ) -> NoReturn: sid_map = list(zip(range(len(symbols)), symbols)) asset_db_writer.write( futures=_get_metadata(sid_map), exchanges=pd.DataFrame(data=[['bitmex', 'UTC']], columns=['exchange', 'timezone']), ) minute_bar_writer.write( _get_minute_bars(sid_map, start_session, end_session, cache), show_progress=show_progress, ) daily_bar_writer.write( _get_daily_bars(sid_map, start_session, end_session, cache), show_progress=show_progress, ) # adjustment_writer.write() return ingest register_calendar('bitmex', BitmexCalendar())
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('HSDZ price (USD)') # Show the plot. plt.gcf().set_size_inches(18, 8) plt.show() equities1 = {} register( 'sniper', # name this whatever you like viadb(equities1)) register_calendar("HSDZ", get_calendar("SHSZ"), force=True) run_algorithm(initialize=initialize, handle_data=handle_data, analyze=analyze, bundle='sniper', environ=os.environ, **merge({'capital_base': 1e7}, { 'start': pd.Timestamp('2014-01-01', tz='utc'), 'end': pd.Timestamp('2014-11-01', tz='utc'), }))
def should_clean(name): dt = from_bundle_ingest_dirname(name) return ( (before is not None and dt < before) or (after is not None and dt > after) ) elif keep_last >= 0: last_n_dts = set(take(keep_last, reversed(all_runs))) def should_clean(name): return name not in last_n_dts else: raise BadClean(before, after, keep_last) cleaned = set() for run in all_runs: if should_clean(run): path = pth.data_path([name, run], environ=environ) shutil.rmtree(path) cleaned.add(path) return cleaned return BundleCore(bundles, register, unregister, ingest, load, clean) bundles, register, unregister, ingest, load, clean = _make_bundle_core() register_calendar("YAHOO", get_calendar("NYSE")) register_calendar("QUANDL", get_calendar("NYSE"))
from zipline.utils.calendars import get_calendar, register_calendar from .shsz_calendar import SHSZCalendar register_calendar("SHSZ", SHSZCalendar(), force=True) shsz_calendar = get_calendar("SHSZ")
astype(np.int64) self.market_closes_nanos = self.schedule.market_close.values. \ astype(np.int64) self._trading_minutes_nanos = self.all_minutes.values. \ astype(np.int64) self.first_trading_session = _all_days[0] self.last_trading_session = _all_days[-1] @property def name(self): return _CALENDAR_NAME @property def tz(self): return timezone("UTC") @property def open_time(self): return time(9, 31) @property def close_time(self): return time(15, 00) ASTOCK_TRADING_CALENDAR = RqalphaAStockTradingCalendar() register_calendar(_CALENDAR_NAME, ASTOCK_TRADING_CALENDAR)
@property def close_time(self): return time(23, 59) @lazyval def day(self): # http://pandas.pydata.org/pandas-docs/stable/timeseries.html#custom-business-days-experimental return CustomBusinessDay( holidays=[], calendar=None, weekmask='Sun Mon Tue Wed Thu Fri Sat' ) #aoe =AlwaysOpenExchange() #print('is open',aoe.is_open_on_minute(pd.Timestamp('2013-01-07 15:03:00+0000', tz='UTC'))) register_calendar("AlwaysOpen",AlwaysOpenExchange()) # order validity enum # similar to ORDER_STATUS: https://github.com/quantopian/zipline/blob/3350227f44dcf36b6fe3c509dcc35fe512965183/zipline/finance/order.py#L24 from zipline.utils.enum import enum ORDER_VALIDITY = enum( 'GTC', 'GTD', 'DAY' ) # my own blotter/order class to allow for order validity from zipline.finance.order import Order class MyOrder(Order): def __init__(self, validity, *args, **kwargs): super(MyOrder,self).__init__(*args, **kwargs)
from zipline.utils.calendars import get_calendar, register_calendar from .exchange_calendar_shsz import SHSZExchangeCalendar register_calendar("SHSZ", SHSZExchangeCalendar(), force=True) #singleton in python shsz_calendar = get_calendar("SHSZ")
@property def tz(self): return timezone('UTC') @property def open_time(self): return time(0, 0) @property def close_time(self): return time(23, 59) @lazyval def day(self): return CustomBusinessDay(weekmask='Mon Tue Wed Thu Fri Sat Sun') register_calendar('POLONIEX', PoloniexCalendar()) # The following is necessary because zipline's developer hard-coded NYSE # everywhere in run_algo._run, *DOH*!!! deregister_calendar('NYSE') register_calendar_alias('NYSE', 'POLONIEX', force=False) register('.test_poloniex', create_bundle( [Pairs.usdt_eth], pd.Timestamp('2016-01-01', tz='utc'), pd.Timestamp('2016-01-31', tz='utc'), ), calendar_name='POLONIEX', minutes_per_day=24 * 60)