def initialize(context): attach_pipeline(make_pipeline(), 'pipeline') #Schedule Functions if not IS_LIVE: schedule_function( trade, #date_rules.every_day(), #date_rules.week_end(days_offset=1),#0=Fri 1= Thurs date_rules.month_end(days_offset=3), time_rules.market_close(minutes=30) ) schedule_function(record_vars, date_rules.every_day(), time_rules.market_close()) schedule_function(cancel_open_orders, date_rules.week_end(days_offset=2), time_rules.market_close()) context.spy = symbol('SPY') #sid(8554) #SPY context.TF_filter = False #context.TF_lookback = 60 #Set number of securities to buy and bonds fund (when we are out of stocks) context.Target_securities_to_buy = 15 #10 #15 #2 #1 #5 #10 #5 context.bonds = symbol('IEF') #sid(23870) #IEF context.relative_momentum_lookback = 44 #66 #22 #4 #22 #22 #22 #126 #Momentum lookback context.momentum_skip_days = 1 context.top_n_relative_momentum_to_buy = 10 #15 #10 #15 #1 #5 #5 #10 #5 #Number to buy context.stock_weights = pd.Series() context.bond_weights = pd.Series() context.auto_close = {} #Initialize portfolio auto_close list. context.TRACK_ORDERS_ON = False
def initialize(context): # Set benchmark to short-term Treasury note ETF (SHY) since strategy is dollar neutral set_benchmark(symbol('AAPL')) # Schedule our rebalance function to run at the end of each day. # Modified the timing to 5 mins earlier than the market close to reduce the fail to book warnings # schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_close(minutes=5)) # Try to change it to open and see what happened -- HY schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open(minutes=5)) # Record variables at the end of each day. # schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close()) # Get intraday prices today before the close if you are not skipping the most recent data # schedule_function(get_prices,date_rules.every_day(), time_rules.market_close(minutes=10)) # Try to get the price data when the market is opening -- HY # schedule_function(get_prices, date_rules.every_day(), time_rules.market_open(minutes=1)) # Set commissions and slippage to 0 to determine pure alpha set_commission(commission.PerShare(cost=0, min_trade_cost=0)) set_slippage(slippage.FixedSlippage(spread=0)) # Number of quantiles for sorting returns for mean reversion context.nq = 5 # Number of quantiles for sorting volatility over five-day mean reversion period context.nq_vol = 3 # Create our pipeline and attach it to our algorithm. my_pipe = make_pipeline() attach_pipeline(my_pipe, 'my_pipeline')
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())
def initialize(context): """ Called once at the start of a backtest, and once per day at the start of live trading. In live trading, the stored context will be loaded *after* this function is called. """ # Rebalance every day, 1 hour after market open. algo.schedule_function( rebalance, algo.date_rules.month_start(), algo.time_rules.market_open(hours=1), ) algo.schedule_function( bonds, algo.date_rules.month_start(days_offset=1), algo.time_rules.market_open(hours=1), ) algo.set_benchmark(algo.sid("FIBBG000BDTBL9")) # Create a pipeline to select stocks each day. algo.attach_pipeline(make_pipeline(), 'pipeline') # algo.set_min_leverage(0, datetime.timedelta(30)) # algo.set_max_leverage(1.2) context.trend_filter = False
def initialize(context): """ Called once at the start of a backtest, and once per day at the start of live trading. """ # Attach the pipeline to the algo algo.attach_pipeline(make_pipeline(), 'pipeline') # Set SPY as benchmark algo.set_benchmark(algo.sid("FIBBG000BDTBL9")) # identify down gaps immediately after the opening algo.schedule_function( find_down_gaps, algo.date_rules.every_day(), algo.time_rules.market_open(minutes=1), ) # at 9:40, short stocks that gapped down algo.schedule_function( short_down_gaps, algo.date_rules.every_day(), algo.time_rules.market_open(minutes=10), ) # close positions 5 minutes before the close algo.schedule_function( close_positions, algo.date_rules.every_day(), algo.time_rules.market_close(minutes=5), ) # Set commissions and slippage algo.set_commission(commission.PerShare(cost=0.0)) algo.set_slippage(slippage.FixedBasisPointsSlippage(basis_points=3.0))
def initialize(context): model = g_models[g_idx] print("hello world --- :",g_idx,model) attach_pipeline(make_pipeline(asset_finder=None,algo_mode=model), 'my_pipeline') schedule_function(rebalance, date_rules.week_start(days_offset=0), half_days=True) context.posset = {} context.rbcnt = 0
def initialize(context): ''' Initialize global vars''' context.long_leverage = 0.1 context.short_leverage = -0.9 context.returns_lookback = 16 context.pct_per_stock = 0.5 context.fastperiod = 12 context.slowperiod = 26 context.signalperiod = 9 context.bar_count = 90 set_commission(commission.PerShare(cost=0.0014, min_trade_cost=1)) # Rebalance on the first trading day of each week at 12AM. schedule_function(rebalance, date_rules.week_start(days_offset=0),time_rules.market_open(hours=0.5)) # Rebalance mid-week schedule_function(cut_losses, date_rules.week_start(days_offset=2),time_rules.market_open(hours=0.5)) # Record tracking variables at the end of each day. schedule_function(record, date_rules.every_day(),time_rules.market_open(minutes=1)) # Create and attach our pipeline (dynamic stock selector), defined below. attach_pipeline(make_pipeline(context), 'mean_reversion_macd_learning')
def initialize(context): pipe = Pipeline() attach_pipeline(pipe, 'example') # Note that we don't call add_factor on these Factors. # We don't need to store intermediate values if we're not going to use them sma_short = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30) sma_long = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=100) sma_val = sma_short/sma_long # Construct the custom factor mkt_cap = MarketCap() # Create and apply a filter representing the top 500 equities by MarketCap # every day. mkt_cap_top_500 = mkt_cap.top(500) remove_penny_stocks = sma_short > 1.0 pipe.add(sma_val, 'sma_val') pipe.add(mkt_cap, 'mkt_cap') # Use mkt_cap_top_500 as a mask on rank pipe.add(sma_val.rank(mask=mkt_cap_top_500), 'sma_rank') # Use multiple screens to narrow the universe pipe.set_screen(mkt_cap.top(500) & remove_penny_stocks)
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): """ Called once at the start of the algorithm. """ c = context c.etf_universe = StaticAssets( symbols('XLY', 'XLP', 'XLE', 'XLF', 'XLV', 'XLI', 'XLB', 'XLK', 'XLU')) c.alphas = pd.DataFrame() # Rebalance every day, 1 hour after market open. schedule_function( rebalance, date_rules.every_day(), time_rules.market_open(hours=1), ) # Record tracking variables at the end of each day. schedule_function( record_vars, date_rules.every_day(), time_rules.market_close(), ) # Create our dynamic stock selector. attach_pipeline(make_pipeline(context), 'pipeline') attach_pipeline(make_pipeinit(context), 'pipeinit') c.first_trading_day = True c.factor_name_list = make_factor().keys()
def initialize(context): """ Called once at the start of the algorithm. """ set_slippage(slippage.FixedSlippage(spread=0.00)) set_commission(commission.PerShare(cost=0, min_trade_cost=0)) schedule_function(rebalance, TRADE_FREQ, date_rules.every_day(), time_rules.market_open(hours=1, minutes=30), ) schedule_function(record_vars, date_rules.every_day(), time_rules.market_close()) ml_pipeline = make_ml_pipeline(universe, n_forward_days=N_FORWARD_DAYS, window_length=TRAINING_PERIOD) # Create our dynamic stock selector. attach_pipeline(ml_pipeline, 'ml_model') context.past_predictions = {} context.ic = 0 context.rmse = 0 context.mae = 0 context.returns_spread_bps = 0
def initialize(context): """ use our factors to add our pipes and screens. """ pipe = Pipeline() attach_pipeline(pipe, 'ff_example') mkt_cap = MarketEquity() pipe.add(mkt_cap, 'market_cap') book_equity = BookEquity() # book equity over market equity bm = book_equity/mkt_cap pipe.add(bm, 'bm') # 营运能力 op = OP() pipe.add(op, 'op') # 投资因子 inv = INV() pipe.add(inv, 'inv') returns = Returns(window_length=2) pipe.add(returns, 'returns') dt = get_datetime().normalize() start_ = dt if dt > START_DATE else START_DATE context.result = result.loc[start_: , :]
def initialize(context): context.params = {'lookback':12, 'min_volume':1E7 } schedule_function(strategy, date_rules.every_day(), time_rules.market_open(minutes=30)) attach_pipeline(make_strategy_pipeline(context), name='strategy_pipeline')
def initialize(context): attach_pipeline(make_pipeline(), 'my_pipeline') context.stop_loss_list = pd.Series() context.sector_wise_exposure = dict() context.sector_stocks = {} context.turnover_count = 0 if context.live_trading is False: schedule_function(rebalance, date_rule=date_rules.month_start())
def initialize(context): __build_deeplearn_strategy(context) attach_pipeline(make_pipeline(context), 'my_pipeline') schedule_function(rebalance, date_rules.every_day(), time_rules.every_minute()) # record my portfolio variables at the end of day print("initialize over") pass
def initialize(context): algo.set_long_only() algo.attach_pipeline(make_pipeline(), 'pipeline') algo.schedule_function( rebalance, algo.date_rules.every_day(), algo.time_rules.market_close(minutes=30), )
def initialize(context): ws.send(msg_placeholder % "Simulation Start") context.lookback = 252 # Period to calculate slope and drawdown context.max_leverage = 1.0 # Leverage context.profit_take = 1.96 # 95% of bollinger band context.minimum_return = 0.1 # Enter if and only if annualized slope exceeds this level context.max_drawdown = 0.10 # Avoid if too much drawdown context.market_impact = 0.2 # Max order is 10% of market trading volume context.weights = {} # Slope at time of entry context.drawdown = {} # Drawdown at time of entry context.shares = {} # Daily target share schedule_function(func=stop_loss, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(minutes=30)) ws.send( msg_placeholder % "Execution of stop loss scheduled at 30 minutes after market open") schedule_function(func=regression, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(minutes=50)) ws.send( msg_placeholder % "Execution of regression computation scheduled at 50 minutes after market open" ) schedule_function(func=trade, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(minutes=100)) ws.send( msg_placeholder % "Execution of transaction planner scheduled at 100 minutes after market open" ) for thirty_minute_interval in range(30, 391, 30): schedule_function( execute_transactions, date_rules.every_day(), time_rules.market_open(minutes=thirty_minute_interval )) # execute every 30 minutes ws.send(msg_placeholder % "Execution of transactions scheduled at every 30 minutes") attach_pipeline(create_high_dollar_volume_pipeline(), 'top_dollar_volume') ws.send(msg_placeholder % "High Dollar Volume pipeline filter attached")
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): attach_pipeline(make_pipeline(), 'my_pipeline') # 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 periodically schedule_function(rebalance, REBALANCE_INTERVAL) context.set_commission(commission.PerShare(cost=.005, min_trade_cost=0))
def initialize(context): attach_pipeline(make_pipeline(), 'my_pipeline') # 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(VolumeShareSlippage()) schedule_function(rebalance2, date_rules.every_day())
def initialize(context): """ Function runs once, at the start of the backtest. You must attach_pipeline() here. :param context: A common namespace to keep variables in :return: """ context.longs_portfolio = {} context.shorts_portfolio = {} attach_pipeline(make_pipeline(), 'data_pipe')
def initialize(self, context): # Schedule our rebalance function to run every day, after a 1 hour, when the market opens. schedule_function(self.rebalance, date_rules.every_day(), time_rules.market_open(hours=1, minutes=0)) # max_minute = 6 * 60 + 30 # # for minute in range(30, max_minute, 60): # schedule_function(self.rebalance, date_rules.every_day(), time_rules.market_open(minutes=minute)) my_pipe = self.make_pipeline() attach_pipeline(my_pipe, "my_pipeline")
def initialize(context): # Create, register and name a pipeline in initialize. pipe = Pipeline() attach_pipeline(pipe, 'example') # Construct a simple moving average factor and add it to the pipeline. sma_short = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10) pipe.add(sma_short, 'sma_short') # Set a screen on the pipelines to filter out securities. pipe.set_screen(sma_short > 1.0)
def initialize(context): """ Called once at the start of the algorithm. """ # Rebalance every day, 1 hour after market open. schedule_function( rebalance, date_rules.every_day(), time_rules.market_open(hours=1), ) # Create our dynamic stock selector. attach_pipeline(make_pipeline(), 'pipeline')
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 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 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))
def initialize(context): __build_factor_basic_strategy(context) attach_pipeline(make_pipeline(context), 'my_pipeline') schedule_function(rebalance, date_rules.week_end(days_offset=0), half_days=True) # record my portfolio variables at the end of day schedule_function(func=recording_statements, date_rule=date_rules.every_day(), time_rule=time_rules.market_close(), half_days=True) print("initialize over") pass
def initialize(context): """ Called once at the start of a backtest, and once per day at the start of live trading. """ # Attach the pipeline to the algo algo.attach_pipeline(make_pipeline(), 'pipeline') # Rebalance every day, 30 minutes before market close. algo.schedule_function( rebalance, algo.date_rules.every_day(), algo.time_rules.market_close(minutes=30), )
def initialize(context): pipeline = Pipeline() context.vwaps = [] for length in vwaps: name = vwap_key(length) factor = VWAP(window_length=length) context.vwaps.append(factor) pipeline.add(factor, name=name) filter_ = (USEquityPricing.close.latest > 300) pipeline.add(filter_, 'filter') if set_screen: pipeline.set_screen(filter_) attach_pipeline(pipeline, 'test')
def initialize(context): pipeline = Pipeline() context.vwaps = [] for length in vwaps: name = vwap_key(length) factor = VWAP(window_length=length) context.vwaps.append(factor) pipeline.add(factor, name=name) filter_ = USEquityPricing.close.latest > 300 pipeline.add(filter_, "filter") if set_screen: pipeline.set_screen(filter_) attach_pipeline(pipeline, "test")
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): pipe = Pipeline() attach_pipeline(pipe, 'pipeline_tutorial') _50ma = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=50) _200ma = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=200) vwap_10 = VWAP(window_length=10) my_volatility_from_daily = Volatility_Daily_Annual() pipe.add(_50ma, '_50ma') pipe.add(_200ma, '_200ma') pipe.add(_50ma / _200ma, 'ma_ratio') pipe.add(vwap_10, 'vwap_10') pipe.add(my_volatility_from_daily, 'my_volatility_from_daily') pipe.set_screen(_50ma / _200ma > 1.0)
def initialize(context): pipeline = attach_pipeline(Pipeline(), "test") vwap = VWAP(window_length=10) pipeline.add(vwap, "vwap") # Nothing should have prices less than 0. pipeline.set_screen(vwap < 0)
def initialize(context): pipeline = attach_pipeline(Pipeline(), 'test') vwap = VWAP(window_length=10) pipeline.add(vwap, 'vwap') # Nothing should have prices less than 0. pipeline.set_screen(vwap < 0)
def initialize(context): pipe = Pipeline() attach_pipeline(pipe, "example") sma_short = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30) sma_long = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=100) # Combined factors to create new factors sma_val = sma_short / sma_long # Create and apply a screen to remove penny stocks remove_penny_stocks = sma_short > 1.0 pipe.set_screen(remove_penny_stocks) pipe.add(sma_short, "sma_short") pipe.add(sma_long, "sma_long") pipe.add(sma_val, "sma_val") # Rank a factor using a mask to ignore the values we're # filtering out by passing mask=remove_penny_stocks to rank. pipe.add(sma_val.rank(mask=remove_penny_stocks), "sma_rank")
def initialize(context): p = Pipeline('test') p.add(USEquityPricing.close.latest, 'close') attach_pipeline(p)
def initialize(context): p = attach_pipeline(Pipeline(), 'test', chunks=chunks) p.add(USEquityPricing.close.latest, 'close')
def initialize(context): p = attach_pipeline(Pipeline(), "test", chunksize=chunksize) p.add(USEquityPricing.close.latest, "close")
def initialize(context): attach_pipeline(Pipeline(), "test")
def initialize(context): attach_pipeline(Pipeline(), "test") pipeline_output("test") raise AssertionError("Shouldn't make it past pipeline_output()")
def late_attach(context, data): attach_pipeline(Pipeline(), "test") raise AssertionError("Shouldn't make it past attach_pipeline!")
def initialize(context): pipeline_close = attach_pipeline(Pipeline(), 'test_close') pipeline_volume = attach_pipeline(Pipeline(), 'test_volume') pipeline_close.add(USEquityPricing.close.latest, 'close') pipeline_volume.add(USEquityPricing.volume.latest, 'volume')
def initialize(context): pipeline = attach_pipeline(Pipeline(), 'my_pipeline') test_factor = TestFactor() pipeline.add(test_factor, 'test_factor')
def initialize(context): attach_pipeline(Pipeline('test'))