def initialize(context): """ Called once at the start of the algorithm. """ set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1)) set_commission(commission.PerShare(cost=0.01, min_trade_cost=1.00)) set_max_leverage(1.0) # Rebalance every day, 1 hour after market open. schedule_function( context.my_rebalance, date_rules.every_day(), time_rules.market_open(hours=1) ) # Close all positions every day, 30 minutes before market close. schedule_function( context.close_positions, date_rules.every_day(), time_rules.market_close(minutes=30) ) # Create risk manager context.risk_manager = RiskManager(context, daily_risk) # Create our dynamic stock selector. attach_pipeline(context.make_screener(), 'stock_screener')
def initialize(context): context.asset = symbol('AAPL') # Explicitly set the commission/slippage to the "old" value until we can # rebuild example data. # github.com/quantopian/zipline/blob/master/tests/resources/ # rebuild_example_data#L105 context.set_commission(commission.PerShare(cost=.0075, min_trade_cost=1.0)) context.set_slippage(slippage.VolumeShareSlippage())
def initialize(context): context.asset = symbol(asset_symbol) # To keep track of whether we invested in the stock or not context.invested = False # Explicitly set the commission/slippage to the "old" value until we can context.set_commission(commission.PerShare(**commission_cost)) context.set_slippage(slippage.VolumeShareSlippage()) context.params = params_list
def initialize(context): """Setup: register pipeline, schedule rebalancing, and set trading params""" attach_pipeline(compute_factors(), 'factor_pipeline') schedule_function(rebalance, date_rules.week_start(), time_rules.market_open(), calendar=calendars.US_EQUITIES) set_commission(us_equities=commission.PerShare(cost=0.00075, min_trade_cost=.01)) set_slippage(us_equities=slippage.VolumeShareSlippage(volume_limit=0.0025, price_impact=0.01))
def initialize(context): context.asset = symbol("AAPL") # To keep track of whether we invested in the stock or not context.invested = False # Explicitly set the commission/slippage to the "old" value until we can # rebuild example data. # github.com/quantopian/zipline/blob/master/tests/resources/ # rebuild_example_data#L105 context.set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1.0)) context.set_slippage(slippage.VolumeShareSlippage())
def initialize(context): context.i = int(input("Start index?: ")) # Explicitly set the commission/slippage to the "old" value until we can # rebuild example data. # github.com/quantopian/zipline/blob/master/tests/resources/ # rebuild_example_data#L105 context.set_commission(commission.PerShare(cost=.005, min_trade_cost=1.0)) context.set_slippage(slippage.VolumeShareSlippage()) context.schedule_function(func=run, date_rule=date_rules.month_start(), time_rule=time_rules.market_open(), half_days=True, calendar=None)
def initialize(context): # set_benchmark(symbol('SPY')) model.init_model() context.i = 0 context.asset1 = symbol('EBAY') context.asset2 = symbol('KLAC') context.model_fee= 1e-3 context.previous_predict_reward=0 context.previous_action=0 context.set_commission(commission.PerShare(cost=0.005, min_trade_cost=1.0)) context.set_slippage(slippage.VolumeShareSlippage()) context.sequence_length=300 context.tb_log_dir='./log/backtest' context.tensorboard=TensorBoard(log_dir=context.tb_log_dir)
def initialize(context): # 记录股票代码,通过股票代码获取股票对象 context.asset = symbol('AAPL') # 定义是否买入股票的标记 context.invested = False # 设置交易的手续费,股票成交时,手续费按成交金额一定比例收取 # 设置手续费率和最低费用 context.set_commission(commission.PerShare(cost=.0075, min_trade_cost=1.0)) # 设置模拟真实交易的滑价,当实际下单交易时,下单订单将影响市场。买单驱使价格上涨,卖单驱使价格下滑; # 这通常被称为交易的“价格影响”。价格影响的大小取决于订单与当前交易量相比有多大。 context.set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1))
def initialize(algo, eps=1, window_length=5): algo.stocks = ['AMD', 'CERN', 'COST', 'DELL', 'GPS', 'INTC', 'MMM'] algo.sids = [algo.symbol(symbol) for symbol in algo.stocks] algo.m = len(algo.stocks) algo.price = {} algo.b_t = np.ones(algo.m) / algo.m algo.last_desired_port = np.ones(algo.m) / algo.m algo.eps = eps algo.init = True algo.days = 0 algo.window_length = window_length algo.set_commission(commission.PerShare(cost=0, min_trade_cost=1.0)) algo.set_slippage(slippage.VolumeShareSlippage())
def initialize(context): attach_pipeline(make_pipeline(), 'my_pipeline') # Rebalance each day. In daily mode, this is equivalent to putting # `rebalance` in our handle_data, but in minute mode, it's equivalent to # running at the start of the day each day. schedule_function(rebalance, date_rules.every_day()) # Explicitly set the commission/slippage to the "old" value until we can # rebuild example data. # github.com/quantopian/zipline/blob/master/tests/resources/ # rebuild_example_data#L105 context.set_commission(commission.PerShare(cost=.0075, min_trade_cost=1.0)) context.set_slippage(slippage.VolumeShareSlippage())
def initialize(context): context.asset = symbol('000001.SZ') # Explicitly set the commission/slippage to the "old" value until we can # rebuild example data. # github.com/quantopian/zipline/blob/master/tests/resources/ # rebuild_example_data#L105 context.set_commission(commission.PerShare(cost=.0075, min_trade_cost=1.0)) context.set_slippage(slippage.VolumeShareSlippage()) schedule_function( my_func, date_rules.every_day(), time_rules.market_open(minutes=15) )
def initialize(self, context, stock_ids): super().initialize(context, stock_ids) context.portfolio_highest = {} context.price_highest = {} context.stock_shares = {} context.set_commission( commission.PerShare(cost=.0075, min_trade_cost=1.0)) context.set_slippage(slippage.VolumeShareSlippage()) set_benchmark(context.assets[0]) for asset in context.assets: context.price_highest[asset] = 0.0 context.portfolio_highest[asset] = 0.0 context.stock_shares[asset] = 0
def initialize(self, eps=1, window_length=5): self.stocks = STOCKS self.m = len(self.stocks) self.price = {} self.b_t = np.ones(self.m) / self.m self.last_desired_port = np.ones(self.m) / self.m self.eps = eps self.init = True self.days = 0 self.window_length = window_length self.add_transform(MovingAverage, 'mavg', ['price'], window_length=window_length) no_delay = datetime.timedelta(minutes=0) slip = slippage.VolumeShareSlippage(volume_limit=0.25, price_impact=0, delay=no_delay) self.set_slippage(slip) self.set_commission(commission.PerShare(cost=0))
def initialize(context): # http://money.usnews.com/funds/etfs/rankings/small-cap-funds context.stocks = [ symbol('SLY'), symbol('EES'), symbol('SCHA'), symbol('IJR'), symbol('PSCH'), symbol('VB'), symbol('VTWO'), symbol('IWM'), symbol('SCHC'), symbol('JKJ') ] context.m = len(context.stocks) context.price = {} context.b_t = np.ones(context.m) / context.m context.eps = 2.5 #change epsilon here context.init = False set_slippage( slippage.VolumeShareSlippage(volume_limit=0.25, price_impact=0)) set_commission(commission.PerShare(cost=0))
def initialize(context): context.set_benchmark(None) context.i = 1 context.assets = list( map(lambda x: symbol(x), high_cap_company.Symbol.values)) print(context.assets, len(context.assets)) context.model_fee = 5e-3 context.set_commission(commission.PerShare(cost=0.005, min_trade_cost=1.0)) context.set_slippage(slippage.VolumeShareSlippage()) context.bootstrap_sequence_length = 300 context.max_sequence_length = 60 context.tb_log_dir = './log/%s' % back_test_name context.model_update_time = 30 context.target_profit_multiplier = 1.1 context.model_summaries = None bundle = bundles.load('quandl') start_date_str = str(context.get_datetime().date()) initial_history_start_date = bundle.equity_daily_bar_reader.sessions[ bundle.equity_daily_bar_reader.sessions < start_date_str][( -context.bootstrap_sequence_length - 1)] initial_history_end_date = bundle.equity_daily_bar_reader.sessions[ bundle.equity_daily_bar_reader.sessions > start_date_str][0] filterd_assets_index = (np.isnan( np.sum(bundle.equity_daily_bar_reader.load_raw_arrays( columns=['close'], start_date=initial_history_start_date, end_date=initial_history_end_date, assets=context.assets), axis=1)).flatten() == False) context.assets = list(np.array(context.assets)[filterd_assets_index]) print(context.assets, len(context.assets)) remain_symbols = list(map(lambda x: x.symbol, context.assets)) if not os.path.exists('history_data'): print('Start to download good history data') history_data = {} for s in remain_symbols: print('downloading', s) stock = quandl.get_table( 'WIKI/PRICES', date={'gte': str(initial_history_start_date)}, ticker=s) stock.index = stock.date history_data[s] = stock history_data = pd.Panel(history_data) history_data.to_pickle('history_data') context.history_data = generate_stock_features(history_data) print('Done') else: print('history data exist') history_data = pd.read_pickle('history_data') context.history_data = generate_stock_features(history_data) if not os.path.exists('index'): print('downloading index data') spy = quandl.get("CHRIS/CME_SP1", authtoken="CTq2aKvtCkPPgR4L_NFs") gc = quandl.get("CHRIS/CME_GC1", authtoken="CTq2aKvtCkPPgR4L_NFs") si = quandl.get("CHRIS/CME_SI1", authtoken="CTq2aKvtCkPPgR4L_NFs") vix = pd.read_csv( 'http://www.cboe.com/publish/scheduledtask/mktdata/datahouse/vixcurrent.csv' ) vix.columns = vix.iloc[0] vix = vix[1:] vix.index = pd.DatetimeIndex(vix.Date) vix = vix.drop('Date', axis=1) vix = vix.astype(np.float64) vix.columns = ['Open', 'High', 'Low', 'Last'] index_data = pd.Panel({'vix': vix, 'gc': gc, 'si': si, 'spy': spy}) index_data.to_pickle('index') index_data = index_data[:, str(initial_history_start_date):, :] context.index_data = generate_index_features(index_data) else: print('index data exist') index_data = pd.read_pickle('index') index_data = index_data[:, str(initial_history_start_date):, :] context.index_data = generate_index_features( index_data)[:, context.history_data.major_axis[0]:, :] if not os.path.exists('trading_content'): sys.exit(1) else: news_vec = pd.read_csv('trading_content') news_vec.index = news_vec.date news_vec = news_vec.drop('date', axis=1) news_vec = context.history_data[:, :, 'return_rate'].join(news_vec).drop( context.history_data.items, axis=1).fillna(0) context.news_vec = news_vec assert context.history_data.major_axis[0] == context.index_data.major_axis[ 0] feature_network_topology = { 'equity_network': { 'feature_map_number': len(context.assets), 'feature_number': context.history_data.shape[2], 'input_name': 'equity', 'dense': { 'n_units': [128, 64], 'act': [tf.nn.tanh] * 2, }, 'rnn': { 'n_units': [32, 1], 'act': [tf.nn.tanh, None], 'attention_length': 10 }, 'keep_output': True }, 'index_network': { 'feature_map_number': len(context.index_data.items), 'feature_number': context.index_data.shape[2], 'input_name': 'index', 'dense': { 'n_units': [128, 64], 'act': [tf.nn.tanh] * 2, }, 'rnn': { 'n_units': [32, 16], 'act': [tf.nn.tanh, tf.nn.tanh], 'attention_length': 10 }, 'keep_output': False }, 'weight_network': { 'feature_map_number': 1, 'feature_number': len(context.assets) + 1, 'input_name': 'weight', 'dense': { 'n_units': [32, 16], 'act': [tf.nn.tanh] * 2, }, 'rnn': { 'n_units': [16, 8], 'act': [tf.nn.tanh, tf.nn.tanh], 'attention_length': 10 }, 'keep_output': False }, 'return_network': { 'feature_map_number': 1, 'feature_number': 1, 'input_name': 'return', 'dense': { 'n_units': [8, 4], 'act': [tf.nn.tanh] * 2, }, 'rnn': { 'n_units': [4, 2], 'act': [tf.nn.tanh, tf.nn.tanh], 'attention_length': 10 }, 'keep_output': False }, 'news_network': { 'feature_map_number': 1, 'feature_number': 100, 'input_name': 'return', 'dense': { 'n_units': [128, 64], 'act': [tf.nn.tanh] * 2, }, 'rnn': { 'n_units': [32, 16], 'act': [tf.nn.tanh, tf.nn.tanh], 'attention_length': 10 }, 'keep_output': False } } context.model = DRL_Portfolio( asset_number=len(context.assets), feature_network_topology=feature_network_topology, action_network_layers=[32, 16], object_function='reward') context.real_return = [] context.history_weight = [] context.model.init_model() context.tensorboard = TensorBoard(log_dir=context.tb_log_dir, session=context.model.get_session())
def initialize(context): context.i = 0 context.assets = list( map(lambda x: symbol(x), high_cap_company.Symbol.values)) print(context.assets, len(context.assets)) context.model_fee = 1e-3 context.previous_predict_reward = 0 context.previous_action = 0 context.set_commission(commission.PerShare(cost=0.005, min_trade_cost=1.0)) context.set_slippage(slippage.VolumeShareSlippage()) context.sequence_length = 300 context.tb_log_dir = './log/backtest' context.tensorboard = TensorBoard(log_dir=context.tb_log_dir) bundle = bundles.load('quandl') start_date_str = str(context.get_datetime().date()) initial_history_start_date = bundle.equity_daily_bar_reader.sessions[ bundle.equity_daily_bar_reader.sessions < start_date_str][( -context.sequence_length - 1)] initial_history_end_date = bundle.equity_daily_bar_reader.sessions[ bundle.equity_daily_bar_reader.sessions > start_date_str][0] filterd_assets_index = (np.isnan( np.sum(bundle.equity_daily_bar_reader.load_raw_arrays( columns=['close'], start_date=initial_history_start_date, end_date=initial_history_end_date, assets=context.assets), axis=1)).flatten() == False) context.assets = list(np.array(context.assets)[filterd_assets_index]) print(context.assets, len(context.assets)) remain_symbols = list(map(lambda x: x.symbol, context.assets)) if not os.path.exists('history_data'): print('Start to download good history data') history_data = {} for s in remain_symbols: print('downloading', s) stock = quandl.get_table( 'WIKI/PRICES', date={'gte': str(initial_history_start_date)}, ticker=s) stock.index = stock.date history_data[s] = stock history_data = pd.Panel(history_data) history_data = history_data.transpose(2, 1, 0) history_data.to_pickle('history_data') context.history_data = history_data print('Done') else: print('history data exist') history_data = pd.read_pickle('history_data') context.history_data = history_data if not os.path.exists('vix.csv'): print('Start to download VIX index') vix = quandl.get("CHRIS/CBOE_VX1", authtoken="CTq2aKvtCkPPgR4L_NFs") vix = vix[str(initial_history_start_date):] vix.to_csv('vix.csv') if not os.path.exists('si.csv'): print('Start to download silver price') si = quandl.get("CHRIS/CME_SI1", authtoken="CTq2aKvtCkPPgR4L_NFs") si.to_csv('si.csv') if not os.path.exists('gc.csv'): print('Start to download gold price') gc = quandl.get("CHRIS/CME_GC1", authtoken="CTq2aKvtCkPPgR4L_NFs") gc.to_csv('gc.csv') if not os.path.exists('spy.csv'): print('Start to download SP500 Index') spy = quandl.get("CHRIS/CME_SP1", authtoken="CTq2aKvtCkPPgR4L_NFs") spy.to_csv('spy.csv') context.model = DRL_Portfolio(feature_number=len(context.assets) * 8, asset_number=len(context.assets) + 1, object_function='sortino') context.model.init_model()
def initialize(context): context.i = 0 context.assets = list(map(lambda x: symbol(x), high_cap_company.Symbol.values)) print(context.assets, len(context.assets)) context.model_fee = 1e-3 context.previous_predict_reward = 0 context.previous_action = 0 context.set_commission(commission.PerShare(cost=0.005, min_trade_cost=1.0)) context.set_slippage(slippage.VolumeShareSlippage()) context.bootstrap_sequence_length = 300 context.max_sequence_length = 500 context.tb_log_dir = './log/%s' % back_test_name context.tensorboard = TensorBoard(log_dir=context.tb_log_dir) context.target_profit_multiplier = 1.1 bundle = bundles.load('quandl') start_date_str = str(context.get_datetime().date()) initial_history_start_date = bundle.equity_daily_bar_reader.sessions[bundle.equity_daily_bar_reader.sessions < start_date_str][(-context.bootstrap_sequence_length - 1)] initial_history_end_date = bundle.equity_daily_bar_reader.sessions[bundle.equity_daily_bar_reader.sessions > start_date_str][0] filterd_assets_index = (np.isnan(np.sum(bundle.equity_daily_bar_reader.load_raw_arrays(columns=['close'], start_date=initial_history_start_date, end_date=initial_history_end_date, assets=context.assets), axis=1)).flatten() == False) context.assets = list(np.array(context.assets)[filterd_assets_index]) print(context.assets, len(context.assets)) remain_symbols = list(map(lambda x: x.symbol, context.assets)) if not os.path.exists('history_data'): print('Start to download good history data') history_data = {} for s in remain_symbols: print('downloading', s) stock = quandl.get_table('WIKI/PRICES', date={'gte': str(initial_history_start_date)}, ticker=s) stock.index = stock.date history_data[s] = stock history_data = pd.Panel(history_data) history_data = history_data.transpose(2, 1, 0) history_data.to_pickle('history_data') context.history_data = history_data print('Done') else: print('history data exist') history_data = pd.read_pickle('history_data') context.history_data = history_data if not os.path.exists('trading_content'): sys.exit(1) else: news_vec = pd.read_csv('trading_content') news_vec.index = news_vec.date news_vec = news_vec.drop('date', axis=1) context.news_vec = news_vec if not os.path.exists('index'): print('downloading index data') spy = quandl.get("CHRIS/CME_SP1", authtoken="CTq2aKvtCkPPgR4L_NFs") gc = quandl.get("CHRIS/CME_GC1", authtoken="CTq2aKvtCkPPgR4L_NFs") si = quandl.get("CHRIS/CME_SI1", authtoken="CTq2aKvtCkPPgR4L_NFs") vix = pd.read_csv('http://www.cboe.com/publish/scheduledtask/mktdata/datahouse/vixcurrent.csv') vix.columns = vix.iloc[0] vix = vix[1:] vix.index = pd.DatetimeIndex(vix.Date) vix = vix.drop('Date', axis=1) vix = vix.astype(np.float64) vix.columns = ['Open', 'High', 'Low', 'Last'] index_data = pd.Panel({'vix': vix, 'gc': gc, 'si': si, 'spy': spy}) index_data = index_data.transpose(2, 1, 0) index_data.to_pickle('index') context.index_data = index_data['Last', str(initial_history_start_date):] else: print('index data exist') index_data = pd.read_pickle('index') context.index_data = index_data['Last', str(initial_history_start_date):] context.model = DRL_Portfolio(feature_number=len(context.assets) * 8 + 100 + context.index_data.columns.shape[0] * 7, asset_number=len(context.assets) + 1, object_function='reward') context.model.init_model()
def initialize(context): context.asset = symbol('BITMAP') context.invested = False context.set_commission(commission.PerShare(cost=.0075, min_trade_cost=1.0)) context.set_slippage(slippage.VolumeShareSlippage())
def initialize(self): self.set_commission(commission.PerShare(cost=self.transaction_cost, min_trade_cost=1.0)) self.set_slippage(slippage.VolumeShareSlippage())
def initialize( self ): # Adjust slippage self.set_slippage( slippage.VolumeShareSlippage( volume_limit = 1.0, price_impact = 0.01 ) ) # Trade on boundary of first trading day of MONTH or set DAYS # DAYS|MONTH # self.boundaryTrade = 'DAYS' # self.boundaryDays = 21 self.boundaryTrade = 'MONTH' # Set Performance vs. Volatility factors (7.0, 3.0 from Grossman GMRE self.factorPerformance = 0.7 self.factorVolatility = 0.3 # Period Volatility and Performance period in DAYS self.metricPeriod = 63 # 3 months LOOKBACK self.periodVolatility = 21 # Volatility period. Chose a MULTIPLE of metricPeriod # To prevent going 'negative' on cash account set stop, limit and price factor >= stop # self.orderBuyLimits = False # self.orderSellLimits = False # #self.priceBuyStop = None # #self.priceBuyLimit = None # #self.priceSellStop = None # #self.priceSellLimit = None # self.priceBuyFactor = 3.03 # Buffering since buys and sells DON'T occur on the same day. # Re-enact pricing from original Quast code self.orderBuyLimits = False self.orderSellLimits = False self.priceBuyFactor = 0.0 # Factor commission cost # self.set_commission(commission.PerShare(cost=0.03)) # self.set_commission(commission.PerTrade(cost=15.00)) # Set the basket of stocks self.basket = { 12915: 'MDY', # MDY (SPDR S&P MIDCAP 400) 21769: 'IEV', # IEV (ISHARES EUROPE ETF) 24705: 'EEM', # EEM (ISHARES MSCI EMERGING MARKETS) 23134: 'ILF', # ILF (ISHARES LATIN AMERICA 40) 23118: 'EPP', # EPP (ISHARES MSCI PACIFIC EX JAPAN) 22887: 'EDV', # EDV (VANGUARD EXTENDED DURATION TREASURY) 40513: 'ZIV', # ZIV (VelocityShares Inverse VIX Medium-Term) 23911: 'SHY', # SHY (iShares 1-3 Year Treasury Bond ETF) } self.logWarn = True self.logBuy = True self.logSell = True self.logHold = True self.logRank = False self.logDebug = False # SHOULDN'T NEED TO MODIFY REMAINING VARIABLES self.accumulateData = accumulateData( window_length = self.metricPeriod ) # Keep track of the current period self.cashStart = None self.dateStart = None self.currentDayNum = None self.currentMonth = None self.currentStock = None self.nextStock = None self.oidBuy = None self.oidSell = None self.period_start_portfolio_value = None self.buyCount = 0 self.sellCount = 0