def initialize(context): #Schedule a function'rebalance', to run once a month schedule_function(schedule, date_rules.month_start(), time_rules.market_open(hours=0, minutes=3)) attach_pipeline(make_pipeline(), 'my_pipeline') attach_pipeline(risk_loading_pipeline(), 'risk_factors')
def initialize(context): context.day_count = 0 context.daily_message = "Day {}" context.weekly_message = "Time to place some trades" context.max_leverage = 1.0 context.max_position_size = 0.015 context.max_turnover = 0.95 algo.attach_pipeline( make_pipeline(), 'data_pipe' ) algo.attach_pipeline( risk_loading_pipeline(), 'risk_pipe' ) algo.schedule_function( rebalance, date_rule = algo.date_rules.week_start(), time_rule = algo.time_rules.market_open() )
def initialize(context): """ Called once at the start of the algorithm. """ # Rebalance every Monday when the market opens algo.schedule_function( rebalance, algo.date_rules.week_start(), algo.time_rules.market_open(), ) # Record tracking variables at the end of each day. algo.schedule_function( record_vars, algo.date_rules.every_day(), algo.time_rules.market_close(), ) # Set constraints context.max_leverage = 1.0 context.max_pos_size = 0.015 context.max_turnover = 0.95 # Create our dynamic stock selector. algo.attach_pipeline(make_pipeline(), 'pipeline') algo.attach_pipeline(risk_loading_pipeline(), 'risk_pipeline')
def initialize(context): # Here we set our slippage and commisions. Set slippage # and commission to zero to evaulate the signal-generating # ability of the algorithm independent of these additional # costs. set_commission(commission.PerShare(cost=0.0, min_trade_cost=0)) set_slippage(slippage.VolumeShareSlippage(volume_limit=1, price_impact=0)) context.spy = sid(8554) algo.attach_pipeline(make_pipeline(), 'long_short_equity_template') # attach the pipeline for the risk model factors that we # want to neutralize in the optimization step algo.attach_pipeline(risk_loading_pipeline(), 'risk_factors') # Schedule my rebalance function schedule_function(func=rebalance, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(hours=0, minutes=30), 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)
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_portfolio, TRADE_FREQ, time_rules.market_open(minutes=1)) # Record tracking variables at the end of each day. schedule_function(log_metrics, date_rules.every_day(), time_rules.market_close()) # Set up universe # base_universe = AverageDollarVolume(window_length=63, mask=QTradableStocksUS()).percentile_between(80, 100) universe = AverageDollarVolume( window_length=63, mask=QTradableStocksUS()).percentile_between(40, 60) # create alpha factors and machine learning pipline ml_pipeline = make_ml_pipeline(alpha_factors=make_alpha_factors(), universe=universe, lookback=TRAINING_PERIOD, lookahead=HOLDING_PERIOD) attach_pipeline(ml_pipeline, 'alpha_model') attach_pipeline(risk_loading_pipeline(), 'risk_loading_pipeline') context.past_predictions = {} context.realized_rmse = 0 context.realized_ic = 0 context.long_short_spread = 0
def initialize(context): """ バックテスト開始時に呼び出される、アルゴリズムの中心となるメイン関数を、Quantopianでは initialize関数と呼びます。 パラメータ ---------- context : アルゴリズムコンテキスト バックテストの状態を保存するために用いられるオブジェクト。 contextは、initialize, before_trading_start, handle_data, scedule_functionから呼び 出される全ての関数に渡されます。 contextは現在のポジションに関する情報を回収ために用いることのできるポートフォリオ特性を提供します。 """ # パイプラインをアルゴリズムに取り込む(notebookでいうところのrun_pipelineに相当) # run_pipelineと違うのは、start_dateとend_dateが引数に存在しない点! algo.attach_pipeline(make_pipeline(), 'long_short_equity_template') # リスクモデルのファクターを構成するパイプラインをアルゴリズムに取り込む algo.attach_pipeline(risk_loading_pipeline(), 'risk_factors') # アルゴリズムの動作スケジュールを決定(ポートフォリオのリバランスを【週次】実行している) algo.schedule_function(func=rebalance, date_rule=algo.date_rules.week_start(), time_rule=algo.time_rules.market_open(hours=0, minutes=30), half_days=True) # アルゴリズムの動作スケジュールを決定(ポートフォリオの状態を営業日終了時点で評価) algo.schedule_function(func=record_vars, date_rule=algo.date_rules.every_day(), time_rule=algo.time_rules.market_close(), half_days=True)
def initialize(context): # SPY capital, EFA fondos, TIP bonos, GSG indince. context.security_list = symbols('SPY', 'EFA','TIP','GSG') context.classifier = KNeighborsClassifier(n_neighbors=7, weights='uniform', algorithm='kd_tree') # Usar un clasificador KNN #Parametros de restriccion # Attach de pileine datos attach_pipeline( make_pipeline(), 'data_pipe' ) attach_pipeline( risk_loading_pipeline(), 'risk_pipe' ) # Rebalance 2 horas de abrir el mercado algo.schedule_function( rebalance, algo.date_rules.month_end(), algo.time_rules.market_open(hours=2), ) # guardar al cierre todos los dias algo.schedule_function( record_vars, algo.date_rules.every_day(), algo.time_rules.market_close() ) # crea el conjunto seleccionado algo.attach_pipeline(make_pipeline(), 'pipeline')
def initialize(context): """ A core function called automatically once at the beginning of a backtest. Use this function for initializing state or other bookkeeping. Parameters ---------- context : AlgorithmContext An object that can be used to store state that you want to maintain in your algorithm. context is automatically passed to initialize, before_trading_start, handle_data, and any functions run via schedule_function. context provides the portfolio attribute, which can be used to retrieve information about current positions. """ algo.attach_pipeline(make_pipeline(), 'long_short_equity_template') # Attach the pipeline for the risk model factors that we # want to neutralize in the optimization step. The 'risk_factors' string is # used to retrieve the output of the pipeline in before_trading_start below. algo.attach_pipeline(risk_loading_pipeline(), 'risk_factors') # Schedule our rebalance function algo.schedule_function(func=rebalance, date_rule=algo.date_rules.week_start(), time_rule=algo.time_rules.market_open(hours=0, minutes=30), half_days=True) # Record our portfolio variables at the end of day algo.schedule_function(func=record_vars, date_rule=algo.date_rules.every_day(), time_rule=algo.time_rules.market_close(), half_days=True)
def initialize(context): universe = QTradableStocksUS() sector = Sector() momentum = Momentum() pipe = Pipeline() pipe.add(sector, 'sector') # ALPHA asset_turnover = Fundamentals.assets_turnover.latest.winsorize(.05, .95).zscore() ciwc = Fundamentals.change_in_working_capital.latest.winsorize(.05, .95).zscore() alpha = (asset_turnover + ciwc).rank().demean() pipe.add(alpha, 'alpha') # BETA beta = RollingLinearRegressionOfReturns(target=sid(8554), returns_length=5, regression_length=252, mask=alpha.notnull() & Sector().notnull() ).beta pipe.add(beta, 'beta') # REGISTER PIPELINES # ------------------ attach_pipeline(pipe, 'pipe') attach_pipeline(risk_loading_pipeline(), 'risk_loading_pipeline') pipe.set_screen(alpha.notnull() & Sector().notnull() & beta.notnull() & universe & (momentum>0)) # SCHEDULE FUNCTIONS # ------------------ schedule_function(rebalance, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(minutes=10))
def initialize(context): """ Called once at the start of the algorithm. """ set_benchmark(symbol('SPY')) set_commission(commission.PerTrade(cost=0.0)) set_slippage(slippage.VolumeShareSlippage(volume_limit=1, price_impact=0)) set_long_only() # set_max_leverage(1.1) # Rebalance every day, 1 hour after market open. algo.schedule_function( rebalance, algo.date_rules.every_day(), algo.time_rules.market_open(hours=1), ) # Record tracking variables at the end of each day. algo.schedule_function( record_vars, algo.date_rules.every_day(), algo.time_rules.market_close(), ) # Create our dynamic stock selector. algo.attach_pipeline(make_pipeline(), 'piotroski') algo.attach_pipeline(risk_loading_pipeline(), 'risk_factors')
def initialize(context): algo.schedule_function(rebalance, algo.date_rules.week_start(), time_rules.market_open()) algo.schedule_function(recordo, date_rules.every_day(), time_rules.market_close()) algo.attach_pipeline(make_pipeline(), 'my_pipeline') algo.attach_pipeline(risk_loading_pipeline(), 'risk_factors')
def initialize(context): # DEFINE UNIVERSE # ------------------ universe = QTradableStocksUS() # ALPHA GENERATION # ---------------- # COMPUTE Z SCORES: ASSET TURNOVER AND CHANGE IN WORKING CAPITAL # BOTH ARE FUNDAMENTAL VALUE MEASURES asset_turnover = Fundamentals.assets_turnover.latest.winsorize( .05, .95).zscore() ciwc = Fundamentals.change_in_working_capital.latest.winsorize( .05, .95).zscore() # ALPHA COMBINATION # ----------------- # ASSIGN EVERY ASSET AN ALPHA RANK AND CENTER VALUES AT 0 (DEMEAN). alpha = (asset_turnover + 2 * ciwc).rank().demean() # BETA DEFINITION beta = 0.66 * RollingLinearRegressionOfReturns( target=sid(8554), returns_length=5, regression_length=252, mask=alpha.notnull() & Sector().notnull()).beta + 0.33 * 1.0 # CREATE AND REGISTER PIPELINE #------------------------------- # COMPUTES COMBINES ALPHA AND SECTOR CODE FOR UNIVERSE OF STOCKS TO BE USED IN OPTIMIZATION pipe = Pipeline( columns={ 'alpha': alpha, 'sector': Sector(), 'beta': beta, }, # RETURN ONLY "NOT NULL" VALUES IN OUR PIPELINE screen=alpha.notnull() & Sector().notnull() & beta.notnull() & universe, ) # LOAD ALL PIPELINES algo.attach_pipeline(pipe, 'pipe') algo.attach_pipeline(risk_loading_pipeline(), 'risk_loading_pipeline') # SCHEDULE FUNCTIONS #-------------------- algo.schedule_function( do_portfolio_construction, date_rule=algo.date_rules.week_start(), time_rule=algo.time_rules.market_open(minutes=10), half_days=False, )
def initialize(context): algo.attach_pipeline(make_pipeline(), 'long_short_equity_template') algo.attach_pipeline(risk_loading_pipeline(), 'risk_factors') algo.schedule_function(func=rebalance, date_rule=algo.date_rules.week_start(), time_rule=algo.time_rules.market_open(hours=0, minutes=30), half_days=True) algo.schedule_function(func=record_vars, date_rule=algo.date_rules.every_day(), time_rule=algo.time_rules.market_close(), half_days=True)
def initialize(context): # Constraint parameters context.max_leverage = 1.0 context.max_short_pos_size = 0.03 context.max_long_pos_size = 0.03 context.max_turnover = 0.95 # Attach data pipelines attach_pipeline(make_pipeline(), 'data_pipe') attach_pipeline(risk_loading_pipeline(), 'risk_pipe') # Schedule rebalance function schedule_function(rebalance, date_rules.week_start(), time_rules.market_open())
def initialize(context): algo.attach_pipeline(make_pipeline(), 'long_short_equity_template') algo.attach_pipeline(risk_loading_pipeline(), 'risk_factors') algo.schedule_function(func=rebalance, date_rule=algo.date_rules.week_start(), time_rule=algo.time_rules.market_close(), half_days=False) # Record our portfolio variables at the end of day algo.schedule_function(func=record_vars, date_rule=algo.date_rules.every_day(), time_rule=algo.time_rules.market_close(), half_days=True)
def initialize(context): context.max_leverage = 1.0 context.max_pos_size = 0.015 context.max_turnover = 0.95 algo.attach_pipeline( make_pipeline(), 'data_pipe') algo.attach_pipeline( risk_loading_pipeline(), 'risk_pipe' ) algo.schedule_function( rebalance, date_rule = algo.date_rules.week_start(), time_rule = algo.time_rules.market_open() )
def initialize(context): attach_pipeline(make_pipeline(), 'long_short_equity_template') attach_pipeline(risk_loading_pipeline(), 'risk_loading_pipeline') # Schedule my rebalance function schedule_function(func=rebalance, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(minutes=60), 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) set_commission(commission.PerShare(cost=0, min_trade_cost=0)) set_slippage(slippage.FixedSlippage(spread=0))
def initialize(context): # Restricciones && context.max_lever = 1.2 context.max_posTam = 0.025 # Volumen de Negocios context.max_Volum = 0.85 # adjunta la informacion de pipelines attach_pipeline(make_pipeline(),'data_pipe') attach_pipeline(risk_loading_pipeline(),'risk_pipe') # llama la funcion rebalance cada dia, 15 minutos despues que el mercado abre schedule_function( rebalance, date_rules.week_start(), time_rules.market_open(minutes=15), )
def initialize(context): # 制約パラメータ context.max_leverage = 1.0 context.max_pos_size = 0.015 context.max_turnover = 0.95 # data pipelines を取り付ける algo.attach_pipeline(make_pipeline(), 'data_pipe') algo.attach_pipeline(risk_loading_pipeline(), 'risk_pipe') # rebalance 関数をスケジュール algo.schedule_function( rebalance, algo.date_rules.week_start(), algo.time_rules.market_open(), )
def initialize(context): context.spy = sid(8554) attach_pipeline(make_pipeline(), 'long_short_equity_template') # Attach the risk loading pipeline to our algorithm. algo.attach_pipeline(risk_loading_pipeline(), 'risk_loading_pipeline') # Schedule my rebalance function schedule_function(func=rebalance, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(hours=0, minutes=30), 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)
def initialize(context): """ Called once at the start of the algorithm. """ #This is for the trend following filter context.spy = sid(8554) context.TF_filter = False context.TF_lookback = 126 # Attach the risk loading pipeline to our algorithm. algo.attach_pipeline(risk_loading_pipeline(), 'risk_loading_pipeline') algo.attach_pipeline(make_pipeline(), 'pipe') # Schedule a function, 'do_portfolio_construction', to run once a week # ten minutes after market open. algo.schedule_function( do_portfolio_construction, date_rule=algo.date_rules.week_start(), time_rule=algo.time_rules.market_open(minutes=MINUTES_AFTER_OPEN_TO_TRADE), half_days=False, )
def initialize(context): algo.attach_pipeline(make_pipeline(), 'long_short_equity_template') # Attach the pipeline for the risk model factors that we # want to neutralize in the optimization step. The 'risk_factors' string is # used to retrieve the output of the pipeline in before_trading_start below. algo.attach_pipeline(risk_loading_pipeline(), 'risk_factors') # Schedule our rebalance function algo.schedule_function(func=rebalance, date_rule=algo.date_rules.every_day(), time_rule=algo.time_rules.market_open(hours=0, minutes=30), half_days=True) # Record our portfolio variables at the end of day algo.schedule_function(func=record_vars, date_rule=algo.date_rules.every_day(), time_rule=algo.time_rules.market_close(), half_days=True)
def initialize(context): attach_pipeline(risk_loading_pipeline(), 'risk_loading_pipeline') attach_pipeline(beta_pipeline(), 'beta_pipeline') attach_pipeline(factor_pipeline(), 'factor_pipeline') # Schedule my rebalance function schedule_function(func=rebalance, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(minutes=60), 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) context.init = True context.combined_alpha = pd.Series()
def initialize(context): context.max_pos_size = 0.01 context.max_turnover = 0.95 context.holdings = 10 context.profit_taking = 20 context.max_loss = -20 context.max_leverage = 1 set_slippage(slippage.FixedSlippage(spread=0.00)) schedule_function(monthly_rebalance, date_rules.month_end(), time_rules.market_open(hours=5)) #5 is 8% pipe = Pipeline() attach_pipeline(pipe, 'ranked_stocks') attach_pipeline(risk_loading_pipeline(), 'risk_pipe') market_cap_filter = market_cap() stocks = market_cap_filter.top(3000) total_filter = (stocks) pipe.set_screen(total_filter) m_factor1 = momentum_factor_1() pipe.add(m_factor1, 'factor_1') m_factor2 = momentum_factor_2() pipe.add(m_factor2, 'factor_2') m_factor_3 = stddev_factor() pipe.add(m_factor_3, 'factor_3') m_factor1_rank = m_factor1.rank(mask=total_filter, ascending=False) m_factor2_rank = m_factor2.rank(mask=total_filter, ascending=False) m_factor_3_rank = m_factor_3.rank(mask=total_filter, ascending=True) pipe.add(m_factor1_rank, 'f1_rank') pipe.add(m_factor2_rank, 'f2_rank') pipe.add(m_factor_3_rank, 'f3_rank') #should put weighted adding instead combo_raw = (m_factor1_rank + m_factor2_rank + m_factor_3_rank) / 3 pipe.add(combo_raw, 'combo_raw') pipe.add(combo_raw.rank(mask=total_filter), 'combo_rank')
def initialize(context): # Agregar tuberia algo.attach_pipeline(make_pipeline(), 'long_short_equity_template') # Agregar tuberia de riesgo algo.attach_pipeline(risk_loading_pipeline(), 'risk_factors') # Agregar función programada de rebalanceo algo.schedule_function(func=rebalance, date_rule=algo.date_rules.week_start(), time_rule=algo.time_rules.market_open(hours=0, minutes=30), half_days=True) # Agregar función programada de registro de variables algo.schedule_function(func=record_vars, date_rule=algo.date_rules.every_day(), time_rule=algo.time_rules.market_close(), half_days=True)
def initialize(context): set_slippage(slippage.FixedSlippage(spread=0.05)) algo.attach_pipeline(make_pipeline(), 'pipeline') algo.attach_pipeline(risk_loading_pipeline(), 'risk_factors') #Schedule Functions schedule_function(trade, date_rules.week_start(2), time_rules.market_close(minutes=30)) schedule_function(trade_bonds, date_rules.month_end(), time_rules.market_close(minutes=20)) #This is for the trend following filter context.spy = sid(8554) context.TF_filter = False context.TF_lookback = 126 #Set number of securities to buy and bonds fund (when we are out of stocks) context.Target_securities_to_buy = 20.0 context.bonds = sid(23870)
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, time_rules.market_open(minutes=1), ) # Record tracking variables at the end of each day. schedule_function( record_vars, date_rules.every_day(), time_rules.market_close(), ) # Set up universe, alphas and ML pipline context.universe = QTradableStocksUS() # if you are using IsAnnouncedAcqTarget, uncomment the next line # context.universe &= IsAnnouncedAcqTarget() ml_pipeline = make_ml_pipeline( context.universe, n_forward_days=PRED_N_FORWARD_DAYS, window_length=ML_TRAINING_WINDOW, ) # Create our dynamic stock selector. attach_pipeline(ml_pipeline, 'alpha_model') # Add the risk pipeline attach_pipeline(risk_loading_pipeline(), 'risk_factors') context.past_predictions = {} context.hold_out_accuracy = 0 context.hold_out_log_loss = 0 context.hold_out_returns_spread_bps = 0
def initialize(context): # Rebalance every day, after market close algo.schedule_function(rebalance, algo.date_rules.every_day(), algo.time_rules.market_close(hours=1)) if NO_COST: set_commission(commission.PerShare(cost=0, min_trade_cost=0)) set_slippage( slippage.FixedBasisPointsSlippage(basis_points=0, volume_limit=0.1)) # Record tracking variables at the end of each day. algo.schedule_function( record_vars, algo.date_rules.every_day(), algo.time_rules.market_close(), ) # Create our dynamic stock selector. algo.attach_pipeline(make_pipeline(), 'pipeline') algo.attach_pipeline(risk_loading_pipeline(), 'risk_loading_pipeline')
def initialize(context): # Rebalance every day, 1 hour after market open. algo.schedule_function( rebalance, algo.date_rules.every_day(), algo.time_rules.market_open(hours=1), ) # contrains to the contest context.max_posTam = 0.045 context.max_lever = 0.97 # Record tracking variables at the end of each day. algo.schedule_function( record_vars, algo.date_rules.every_day(), algo.time_rules.market_close(), ) # Create our dynamic stock selector. algo.attach_pipeline(risk_loading_pipeline(), 'risk_loading_pipeline') algo.attach_pipeline(make_pipeline(), 'pipeline')
Parameters ---------- context : AlgorithmContext An object that can be used to store state that you want to maintain in your algorithm. context is automatically passed to initialize, before_trading_start, handle_data, and any functions run via schedule_function. context provides the portfolio attribute, which can be used to retrieve information about current positions. """ algo.attach_pipeline(make_pipeline(), 'long_short_equity_template') # Attach the pipeline for the risk model factors that we # want to neutralize in the optimization step. The 'risk_factors' string is # used to retrieve the output of the pipeline in before_trading_start below. algo.attach_pipeline(risk_loading_pipeline(), 'risk_factors') # Schedule our rebalance function algo.schedule_function(func=rebalance, date_rule=algo.date_rules.month_start(days_offset = 3), time_rule=algo.time_rules.market_close(hours=0, minutes=30), half_days=True) # Record our portfolio variables at the end of day algo.schedule_function(func=record_vars, date_rule=algo.date_rules.every_day(), time_rule=algo.time_rules.market_close(), half_days=True) def make_pipeline(): """