def initialize(context): # Ethereum contract #context.contract = ContractHandler() # Get blacklist of sectors which returns a list of codes #context.blacklist = context.contract.getBlacklist() # for testing purpose without Ethereum exclude Defense, Beer & Alcohol, Tabacco and Coal context.blacklist = [26.0, 4.0, 5.0, 29.0] # Only run get_fundamentals when necessary based on the rebalance function context.initial = True # Dictionary of stocks and their respective weights context.stock_weights = {} # Count of days before rebalancing context.days = 0 # Number of sectors to go long in context.sect_numb = 2 # Sector mappings context.sector_mappings = get_sectors(key='code') context.ticker_sector_dict = get_sector_code() # TODO: Update this accordingly (weekly?) # Rebalance monthly on the first day of the month at market open schedule_function(rebalance, date_rule=date_rules.month_start(), time_rule=time_rules.market_open())
def initialize(context): # Dictionary of stocks and their respective weights context.stock_weights = {} # Count of days before rebalancing context.days = 0 # Number of sectors to go long in context.sect_numb = 2 # Sector mappings context.sector_mappings = { 101.0: "Basic Materials", 102.0: "Consumer Cyclical", 103.0: "Financial Services", 104.0: "Real Estate", 205.0: "Consumer Defensive", 206.0: "Healthcare", 207.0: "Utilites", 308.0: "Communication Services", 309.0: "Energy", 310.0: "Industrials", 311.0: "Technology", } # Rebalance monthly on the first day of the month at market open schedule_function(rebalance, date_rule=date_rules.month_start(), time_rule=time_rules.market_open())
def initialize(context): set_commission(commission.PerDollar(cost=0.0055)) # context.strategy_name = "FOF_{mdd}" context.mdd = context.namespace["mdd"] context.fof_code = context.namespace["fof_code"] context.save2mysql = context.namespace.get("save_method", 0) context.i = 0 schedule_function(scheduled_rebalance, date_rules.month_start(days_offset=0), time_rules.market_open()) context.init_value = pd.Series() # 记录自最近一次调仓以来,组合内各基金所达到的最大净值 context.adjust_date = 0 # 记录距离最近一次季调的时间 context.stop_date = 0 # 记录距离最近一次止损的时间 # 基金池 stock = [ '000478.OF', '050002.OF', '110006.OF', '161120.OF', '000217.OF', "501018.OF", '000071.OF', '070031.OF', '000342.OF', 'B00.IPE', "HSCI.HI", '037.CS', "em_bond", "reit", "SPTAUUSDOZ.IDC", '096001.OF', 'SPX.GI', '000905.SH' ] context.stocks = [] for sym in stock: context.stocks.append(symbol(sym)) # 指数与基金的对应关系 fixed index = [ "HSCI.HI", '037.CS', "EM_BOND", "REIT", "SPTAUUSDOZ.IDC", "000905.SH", "B00.IPE", "NDX.GI", 'SPX.GI' ] index_etf = ["000071.OF","161120.OF","000342.OF",\ "070031.OF","000217.OF","000478.OF",\ "501018.OF","160213.OF",'096001.OF'] context.df_index = pd.DataFrame( data=index_etf, index=index, )
def initialize(context): """ A function to define things to do at the start of the strategy """ # set the account currency, only valid for backtests set_account_currency("USD") # universe selection context.short_dollar_basket = { symbol('FXCM:AUD/USD'):1, symbol('FXCM:EUR/USD'):1, symbol('FXCM:GBP/USD'):1, symbol('FXCM:NZD/USD'):1, symbol('FXCM:USD/CAD'):-1, symbol('FXCM:USD/CHF'):-1, symbol('FXCM:USD/JPY'):-1, } # Call rebalance function on the first trading day of each month after 2.5 hours from market open schedule_function(rebalance, date_rules.month_start(days_offset=0), time_rules.market_close(hours=2, minutes=30)) # set trading cost and slippage to zero set_commission(fx=commission.PipsCost(cost=0.00)) set_slippage(fx=slippage.FixedSlippage(0.00))
def initialize(context): """ Initialization and trading logic """ # Set comission and slippage if enable_commission: comm_model = PerDollar(cost=commission_pct) else: comm_model = PerDollar(cost=0.0) set_commission(comm_model) if enable_slippage: slippage_model = VolumeShareSlippage( volume_limit=slippage_volume_limit, price_impact=slippage_impact) else: slippage_model = FixedSlippage(spread=0.0) # Used only for progress output context.last_month = initial_portfolio # Store index membership context.index_members = pd.read_csv('./data/sp500_members.csv', index_col=0, parse_dates=[0]) # Schedule rebalance monthly schedule_function(func=rebalance, date_rule=date_rules.month_start(), time_rule=time_rules.market_open())
def initialize(context): print("{}:inside initialize".format(get_datetime())) schedule_function(rebalance, date_rule=date_rules.month_start(), time_rule=time_rules.market_open()) context.frequency = 120 context.loop_count = 0
def initialize(context): """ A function to define things to do at the start of the strategy """ # universe selection context.long_portfolio = [symbol('ASIANPAINT'), symbol('TCS')] # Call rebalance function on the first trading day of each month after 2.5 hours from market open schedule_function(rebalance, date_rules.month_start(days_offset=0), time_rules.market_close(hours=2, minutes=30))
def initialize(context): ''' A function to define things to do at the start of the strategy ''' # The context variables can be accessed by other methods context.params = {'lookback': 12, 'percentile': 0.05, 'min_volume': 1E7} # Call rebalance function on the first trading day of each month schedule_function(strategy, date_rules.month_start(), time_rules.market_close(minutes=1)) # Set up the pipe-lines for strategies attach_pipeline(make_strategy_pipeline(context), name='strategy_pipeline')
def rebalance_scheduler(context): ''' function to schedule a rebalancing trade. The rebalancing is done based on the weights determined in the strategy core for each of the instruments defined in the trading universe. ''' context.use_handle_data = False rebalance_freq = context.params.get('rebalance_freq',None) if rebalance_freq is None: return if context.params['verbose']: print('setting up {} scheduler'.format(rebalance_freq)) if rebalance_freq == 'monthly': schedule_function(rebalance, date_rules.month_start(days_offset=0), time_rules.market_open(hours=5, minutes=30)) elif rebalance_freq == 'weekly': schedule_function(rebalance, date_rules.week_start(days_offset=0), time_rules.market_open(hours=5, minutes=30)) elif rebalance_freq == 'daily': schedule_function(rebalance, date_rules.every_day(), time_rules.market_open(hours=5, minutes=30)) elif rebalance_freq.endswith('m'): try: context.trade_freq = int(rebalance_freq.split('m')[0]) print('trade freq {}'.format(context.trade_freq)) context.bar_count = 0 context.use_handle_data = True except: raise ValueError('Invalid minute frequency') elif rebalance_freq.endswith('h'): try: context.trade_freq = int(rebalance_freq.split('h')[0])*60 print('trade freq {}'.format(context.trade_freq)) context.bar_count = 0 context.use_handle_data = True except: raise ValueError('Invalid hourly frequency') else: raise ValueError('Un-recognized rebalancing frequency') if context.params['no_overnight_position']: schedule_function(square_off, date_rules.every_day(), time_rules.market_close(hours=3, minutes=30))
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): pipe = Pipeline() attach_pipeline(pipe, 'my_pipeline') pb_ratios = PriceBookRatio() pipe.add(pb_ratios, 'pb_ratio') # If Zipline has trouble pulling the default benchmark, try setting the # benchmark to something already in your bundle # set_benchmark(symbol("change this to a symbol in your data")) # Rebalance monthly schedule_function(rebalance, date_rules.month_start()) context.set_commission(commission.PerShare(cost=.0075, min_trade_cost=1.0))
def initialize(context): # ETFs and target weights for a balanced and hedged portfolio context.securities = { 'SPY': 0.25, 'TLT': 0.3, 'IEF': 0.3, 'GLD': 0.075, 'DBC': 0.075 } # Schedule rebalance for once a month schedule_function(rebalance, date_rules.month_start(), time_rules.market_open()) # Set up a benchmark to measure against context.set_benchmark(symbol('SPY'))
def initialize(context): # add_history(LOOKBACK_PERIOD, '1d', 'price') #set_max_leverage(1.25) context.i = 0 set_commission(commission.PerDollar(cost=0.006)) context.fof_code = context.namespace["fof_code"] context.save2mysql = context.namespace.get("save_method", 0) schedule_function(scheduled_rebalance, date_rules.month_start(days_offset=0), time_rules.market_open()) context.weights = pd.Series() stock = [house,oil,Emerging_market_bonds,America_stock,Hongkong_stock,\ gold,"HSCI.HI", "SPX.GI",'B00.IPE',"em_bond","reit", "SPTAUUSDOZ.IDC"] context.stocks = [] for i in stock: context.stocks.append(symbol(i))
def initialize(context): # weights for rebalance context.weights = {} # set up the factor models vol_factor = FactorModel('vol_factor', VolatilityFactor, 0.05, False) skew_factor = FactorModel('skew_factor', SkewFactor, 0.05, True) pca_factor = FactorModel('pca_factor', PCAFactor, 0.05, False) mom_factor = FactorModel('mom_factor', MomentumFactor, 0.05, True) context.agent = Agent([vol_factor, skew_factor, pca_factor, mom_factor], 0.35, method=1) # set up pipeline - for efficient computation attach_pipeline(factor_pipe(context), name='factor_pipe') # our rebalabce function schedule_function(run_strategy, date_rules.month_start(days_offset=0), time_rules.market_open(hours=2, minutes=30))
def initialize(context): # these must ALWAYS be present! context.transforms = [] context.algo_rules = [] context.max_lookback = 63 context.outstanding = {} # orders which span multiple days context.raw_data = {} ############################################################# # set the following parameters as required context.show_positions = True # select records to show in algo.show_records() context.show_records = True # replace cash_proxy with risk_free if cantec.allow_cash_proxY_replacement is True # and cash_proxy price is <= average cash_proxy price over last context.cash_proxy_lookback days context.allow_cash_proxy_replacement = False context.cash_proxy_lookback = 43 # must be <= context.max_lookback context.update_metrics = False # to calculate Sharpe ratio context.calculate_SR = False context.SR_lookback = 63 # must be <= context.max_lookback context.SD_factor = 0 # position only changed if percentage change > threshold context.threshold = 0.01 # the following can be changed context.market_proxy = symbols('VFINX')[0] context.risk_free = symbols('VFISX')[0] # context.market_proxy = symbols('SPY')[0] # context.risk_free = symbols('SHY')[0] set_commission(commission.PerTrade(cost=10.0)) context.leverage = 1.0 ################################################################# # configure strategies context.rebalance_interval = 3 # set interval to n = no of periods (default: months) # if you want to change default period, change schedule reallocate below # Strategy 1 rs0003 = StrategyParameters( context, name='rs0003', portfolios=[symbols('NHMAX', 'FAGIX', 'VFIIX')], # portfolios=[symbols('HYD','HYD','MBB')], portfolio_allocation_modes=['EW'], portfolio_allocation_kwargs=[{}], security_weights=[None], portfolio_allocation_formulas=[None], scoring_methods=['RS'], scoring_factors=[{ '+momentum': 1.0 }], n_tops=[1], protection_modes=['BY_RULE'], protection_rules=['smma_rule'], protection_formulas=[None], cash_proxies=[symbol('VFISX')], # cash_proxies=[symbol('SHY')], strategy_allocation_mode='FIXED', portfolio_weights=[1.0], strategy_allocation_formula=None, strategy_allocation_rule=None) Configurator(context, define_transforms, define_rules, strategies=[rs0003]) ############################ # configure algorithm algo = Algo(context, strategies=[rs0003.strategy], allocation_model=AllocationModel(context, mode='EW', weights=None, formula=None), regime=None) ########################################################################################################### # generate algo data every day at close schedule_function(algo.update_data, date_rules.every_day(), time_rules.market_close()) # daily functions to handle GTC orders schedule_function(algo.check_for_unfilled_orders, date_rules.every_day(), time_rules.market_close()) schedule_function(algo.fill_outstanding_orders, date_rules.every_day(), time_rules.market_open()) if context.update_metrics: # calculate metrics every day schedule_function(algo.update_metrics, date_rules.every_day(), time_rules.market_close()) if context.show_positions: schedule_function(algo.show_positions, date_rules.month_start(days_offset=0), time_rules.market_open()) if context.show_records: # show records every day # edit the show_records function to include records required schedule_function(algo.show_records, date_rules.every_day(), time_rules.market_close()) schedule_function(algo.rebalance, date_rules.month_end(days_offset=2), time_rules.market_open())
Pipeline algorithm that buys recent winners and sells recent losers. Specifically: - rank stocks by their performance over the past MOMENTUM_WINDOW days - ignore very recent performance by excluding the last RANKING_PERIOD_GAP days from the ranking window (as commonly recommended for UMD) - buy the TOP_N_DECILES deciles of highest performing stocks and short the TOP_N_DECILES deciles of lowest performing stocks - rebalance the portfolio according to REBALANCE_INTERVAL """ MOMENTUM_WINDOW = 252 RANKING_PERIOD_GAP = 22 TOP_N_DECILES = 5 REBALANCE_INTERVAL = date_rules.month_start() class Momentum(CustomFactor): """ Calculates the percent change in close price over MOMENTUM_WINDOW, excluding the most recent RANKING_PERIOD_GAP periods. """ inputs = [USEquityPricing.close] window_length = MOMENTUM_WINDOW def compute(self, today, assets, out, close): out[:] = (close[-RANKING_PERIOD_GAP] - close[0]) / close[0] def make_pipeline():
def initialize(context): context.record_rank = {} context.save2mysql = 0 # 模型训练参数 context.horizon = 6 context.percent = 5 context.model_name = 'adaBoost' context.rolling = 1 # 是否为滚动,0为不滚动 context.ishistory = 0 #是否用历史分类。0为不使用 context.train_period = 12 * 1 context.i = 0 set_slippage(slippage.FixedSlippage(spread=0.00)) set_commission(commission.PerDollar(cost=0.00325)) month = 21 week = 5 rf = 0.025 c = 252 if context.namespace["fund_type"] == 'stock': benchmark = '000300.SH' fund_type = 1 elif context.namespace["fund_type"] == 'hybrid': benchmark = '000300.SH' fund_type = 2 elif context.namespace["fund_type"] == 'bond': benchmark = '037.CS' fund_type = 3 # 选择基金池和benchmark ben_sid = symbol(benchmark).sid df_stock = df.query("update_time == update_time.max() and type_code=={"\ "type}".format(type = fund_type)) # 基金900 开头的不需要,专门去掉 df_stock = df_stock[df_stock["fund_code"] < '900000'].fund_code + ".OF" sfilt = SpecificAssets(symbols( benchmark, *tuple(df_stock))) # 使用到的数据,包括基金和对应benchmark指数 sample_filt = SpecificAssets(symbols( *tuple(df_stock))) # 只包含基金,因为评级不应该包含benchmark,故在事后screen去掉benchmark # 只包含基金,因为评级不应该包含benchmark,故在事后screen去掉benchmark ## 16个因子指标 down_sharpe = Down_sharpe(window_length=9 * month, rf=rf, c=c, mask=sfilt) drawdown = Drawdown(window_length=9 * month, mask=sfilt) dvar = Down_variation(window_length=9 * month, rf=rf, c=c, mask=sfilt) mean_r = Average_return(window_length=9 * month, mask=sfilt) lasting = Lasting(window_length=9 * month, mask=sfilt, time=6 * month, percent=20) emr = Emr(window_length=9 * month, mask=sfilt, time=6 * month) rlt_var = Negative_variation(window_length=9 * month, c=c, mask=sfilt) mcv_in = Mcv_in(window_length=9 * month, rf=rf, c=c, mask=sfilt, time=week, index_sid=ben_sid) rank_stable = Rank_stable(window_length=9 * month, mask=sfilt, time=6 * month) select_time, select_stock = CL(window_length=9 * month, rf=rf, mask=sfilt, time=week, index_sid=ben_sid) hit_rate = Hit_rate(window_length=10 * month, mask=sfilt, time=6 * month, time_window=9 * month, index_sid=ben_sid) value_at_risk = Value_at_risk(window_length=9 * month, mask=sfilt, q_value=5, time=6 * month) beta_in = Beta_in(window_length=9 * month, mask=sfilt, rf=rf, time=week, index_sid=ben_sid) bias_in = Bias_in(window_length=9 * month, mask=sfilt, time=126) ir = Information_ratio(window_length=9 * month, mask=sfilt, time=1, index_sid=ben_sid) # 预测因变量Y _ry = Lag_Return(window_length=context.horizon * month, mask=sfilt) _sp = Lag_Sharpe(window_length=context.horizon * month, mask=sfilt) pipe = Pipeline(columns={ "dhsp": down_sharpe, "drwd": drawdown, "dvar": dvar, "mean_r": mean_r, "lasting": lasting, "emr": emr, "rlt_var": rlt_var, "mcv_in": mcv_in, "rank_stable": rank_stable, "select_time": select_time, "select_stock": select_stock, "hit_rate": hit_rate, "value_at_risk": value_at_risk, "beta_in": beta_in, "bias_in": bias_in, "ir": ir, "_ry": _sp }, screen=sample_filt) attach_pipeline(pipe, 'my_pipeline') set_max_leverage(1.1) schedule_function(rebalance, date_rule=date_rules.month_start(), time_rule=time_rules.market_open()) # 初始化记录变量 context.rank_score = pd.Series() context.f = pd.Panel() context.f_dict = {} context.reb_flag = False context.B = {}
def initialize (context) : # Algorithm parameters are defined here if ENVIRONMENT == 'RESEARCH': context.benchmark = symbols('SPY') context.risk_free = symbols('SHY') context.cash_proxy = symbols('SHY') elif ENVIRONMENT == 'ZIPLINE' or ENVIRONMENT == 'IDE': context.benchmark = symbol('SPY') context.risk_free = symbol('SHY') context.cash_proxy = symbol('SHY') context.algo_transforms = [(['price'], ROCP, ['mom_63'], 62), (['price'], ROCP, ['mom_21'], 20), (['price'], average_historic_volatility, ['hvol_20'], 63, 20), (['price'], SMA, ['short_mavg'], 21), (['price'], SMA, ['long_mavg'], 63) ] if ENVIRONMENT == 'ZIPLINE' or ENVIRONMENT == 'IDE': context.strategies = { 'strategy1': { 'strat_wt' : 1.0, 'strat_type' : 'SIGNAL', 'alloc_type' : 'EQWT', 'portfolios' : [ symbols('VHT', 'VGT', 'VCR', 'IBB', 'EDV', 'VB', 'VAW', 'TLT') ], 'weights' : [1.0], 'n_top' : [1], 'zscore_data' : ['+mom_63', '+mom_21', '-hvol_20'], 'zscore_weights' : [0.7, 0.0, 0.3], # 'filter' : [lambda x,y: (x > y) & (x > 0), 'mom_21', ('mom_21', context.risk_free)] # 'filter' : [] 'filter' : [lambda x,y: x > y, 'mom_63', ('mom_63', context.risk_free)], 'buy_trigger' : [lambda x,y: (x > y) and (context.buy_flag==False), 'short_mavg', 'long_mavg'], 'sell_trigger' : [lambda x,y : (x < y) and (context.buy_flag==True), 'short_mavg', 'long_mavg'] } } elif ENVIRONMENT == 'RESEARCH': context.strategies = { 'strategy1': { 'strat_wt' : 1.0, 'strat_type' : 'SIGNAL', 'alloc_type' : 'EQWT', 'portfolios' : [ [symbols('VHT'), symbols('VGT'), symbols('VCR'), symbols('IBB'), symbols('EDV'), symbols('VB'), symbols('VAW'), symbols('TLT')] ], 'weights' : [1.0], 'n_top' : [1], 'zscore_data' : ['+mom_63', '+mom_21', '-hvol_20'], 'zscore_weights' : [0.7, 0.0, 0.3], # 'filter' : [lambda x,y: (x > y) & (x > 0), 'mom_21', # ('mom_21', context.risk_free)] # 'filter' : [] 'filter' : [lambda x,y: x > y, 'mom_63', ('mom_63', context.risk_free)], 'buy_trigger' : [lambda x,y: (x > y) and (context.buy_flag==False), 'short_mavg', 'long_mavg'], 'sell_trigger' : [lambda x,y : (x < y) and (context.buy_flag==True), 'short_mavg', 'long_mavg'] } } # have to set this manually 'til I figure how to generate it programmatically from above parameters context.max_lookback = 120 # need additional data for recursive indicators like EMA, historic_vol etc. # set the appropriate time_rule offsets (hours, minutes) for order processing context.order_time_rule = time_rules.market_close(hours=0, minutes=1) context.threshold = 0.0 # only BUY/SELL if asset QTY changes by threshold% set_commission(commission.PerTrade(cost=0.0)) set_slippage(slippage.FixedSlippage(spread=0)) ####################################################################################### # THE FOLLOWING MUST ALWAYS BE INCLUDED AND MUST PRECEDE ANY SCHEDULED FUNCTIONS! # include this check to make sure that the algo parameters are formatted as required check_algo_parameters (context) # create a set of all the symbols used by the algorithm create_symbol_list(context) initialize_strat_variables(context) if ENVIRONMENT != 'IDE': add_strat_history(context) ####################################################################################### schedule_function(generate_strat_data, # date_rule=date_rules.month_start(days_offset=0), date_rule=date_rules.month_start(days_offset=0), time_rule=time_rules.market_open(hours=0, minutes=1), half_days=True) # schedule_function_by_interval(context, test_signal, # date_rule=date_rules.every_day(), # time_rule=time_rules.market_open(hours=0, minutes=5), # half_days=True, # freq=1) # the 'freq' parameter is added to the norma schedule_function routine # to enable intervals of 'freq' periods - 1,2,3,..... months schedule_function_by_interval(context, rebalance, date_rule=date_rules.month_start(days_offset=0), time_rule=time_rules.market_open(hours=0, minutes=5), half_days=True, freq=1) schedule_function_by_interval(context, handle_orders, date_rule=date_rules.month_start(days_offset=0), time_rule=time_rules.market_close(hours=0, minutes=15), half_days=True, freq=1)