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): """ Called once at the start of the algorithm. """ #constraints context.max_leverage = 1.0 context.max_pos_size = 0.015 context.max_turnover = 0.65 # 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(), 'pipeline')
def initialize(context): """ Called once at the start of the algorithm. """ # Set Benchmark same as the Stock (Netflix). set_benchmark(sid(23709)) # 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(), '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): """ Called once at the start of the algorithm. """ # Rebalance every day, 1 hour after market open. algo.schedule_function(rebalance, algo.date_rules.month_start(), algo.time_rules.market_open())
def initialize(context): """ Called once at the start of the algorithm. """ # AAPL, MSFT, and SPY context.assets = [sid(24), sid(5061), sid(8554)] context.sym = symbol('AAPL') context.i = 0 # 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(), 'pipeline')
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): # Define stocks to buy context.stocks_to_buy = set([ sid(44543), sid(44542), sid(44546), sid(45104), sid(26807), sid(8554), sid(19920), sid(2174), sid(23921), sid(39035), sid(22445) ]) # Make pipeline algo.attach_pipeline(make_pipeline(), 'pipeline') # Dictionary of desired stock numbers context.stock_numbers = {} # Record tracking variables at the end of each day. algo.schedule_function( record_vars, algo.date_rules.every_day(), algo.time_rules.market_close(), )
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): algo.schedule_function(rebalance, algo.date_rules.week_start(days_offset=0), algo.time_rules.market_open(hours=1, minutes=30)) algo.attach_pipeline(make_pipeline(context), 'mean_reversion')
def initialize(context): """ Called once at the start of the algorithm. """ # Rebalance on the first trading day of each week at 11AM. algo.schedule_function(rebalance, date_rules.month_start(days_offset=0), time_rules.market_open(hours=1, minutes=30)) # # 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. context.stocks_by_sector = { 101.0: set(), 102.0: set(), 103.0: set(), 205.0: set(), 206.0: set(), 207.0: set(), 308.0: set(), 309.0: set(), 310.0: set(), 311.0: set() } algo.attach_pipeline(make_pipeline(), 'value_pipeline')
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. """ # Save the futures contracts we'll be trading and the corresponding proxies for the underlying's spot price. context.security = continuous_future('ES', offset=0, roll='volume', adjustment='mul') context.proxy = sid(8554) # Create empty keys that will later contain our window of cost of carry data. context.cost_of_carry_data = [] context.cost_of_carry_quantiles = [] context.price = 0 context.current_position = 0 context.period = 14 context.rsi = 50 context.small = 30 context.large = 70 context.upper = 0.8 context.lower = 0.2 # Rebalance every day, 1 hour after market open. algo.schedule_function(daily_rebalance, date_rules.every_day(), time_rules.market_open(), calendar=calendars.US_EQUITIES)
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): """ 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() 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') context.past_predictions = {} context.hold_out_accuracy = 0 context.hold_out_log_loss = 0 context.hold_out_returns_spread_bps = 0
def initialize(context): algo.schedule_function( trade, algo.date_rules.every_day(), algo.time_rules.market_open(), )
def initialize(context): """ Called once at the start of the algorithm. """ context.alphas = pd.DataFrame() # 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. attach_pipeline(make_pipeline(), 'pipeline') attach_pipeline(make_pipeinit(), 'pipeinit') context.first_trading_day = True context.factor_name_list = make_factor().keys()
def initialize(context): # Reference to the AAPL security. context.aapl = sid(24) # Rebalance every day, one hour and a half after market open. algo.schedule_function(rebalance, algo.date_rules.every_day(), algo.time_rules.market_open(hours=1, minutes=30))
def initialize(context): # Rebalance on the first trading day of each week at 11AM. algo.schedule_function(rebalance, algo.date_rules.week_start(days_offset=0), algo.time_rules.market_open(hours=1, minutes=30)) # Create and attach our pipeline (dynamic stock selector), defined below. algo.attach_pipeline(make_pipeline(context), 'mean_reversion_example')
def initialize(context): algo.schedule_function( rebalance, algo.date_rules.month_start(), algo.time_rules.market_open(), ) algo.attach_pipeline(make_pipeline(), 'pipeline')
def initialize(context): # Attach pipeline to algorithm algo.attach_pipeline(make_pipeline(), 'data_pipe') # Schedule rebalance function algo.schedule_function(rebalance, date_rule=algo.date_rules.week_start(), time_rule=algo.time_rules.market_open())
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=3), ) algo.attach_pipeline(make_pipeline(), 'pipeline') context.df=None
def initialize(context): # Initialize algorithm parameters context.day_count = 0 context.daily_message = "Day {}." context.weekly_message = "Time to place some trades!" # Schedule rebalance function algo.schedule_function(rebalance, date_rule=algo.date_rules.week_start(), time_rule=algo.time_rules.market_open())
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): """ Called once at the start of the algorithm. """ # Call rebalance() every month, 1 hour after market open. algo.schedule_function( rebalance, algo.date_rules.month_start(days_offset=0), algo.time_rules.market_open(minutes=60), )
def initialize(context): context.stock = symbol('SPY') context.inpos = 0 # Rebalance every day, 1 min before close. algo.schedule_function( rebalance, algo.date_rules.every_day(), algo.time_rules.market_close(minutes=3), )
def initialize(context): context.stocks = [sid(8229), sid(4707), sid(12652), sid(16841)] context.max_leverage=1.0 # Rebalance every day, 1 hour after market open. algo.schedule_function( main, algo.time_rules.market_open(), ) # Create our dynamic stock selector. algo.attach_pipeline(make_pipeline(), 'portfolio') algo.attach_pipeline(make_pipeline(), 'universe')
def initialize(context): """ Called once at the start of the algorithm. """ # Create our dynamic stock selector. algo.attach_pipeline(make_pipeline(), 'pipeline') # Dictionary of max weights for each asset. # Weight by mean annual return % of flags. context.max_weights = { sid(8554): 0.15, # SPY sid(19920): 0.20, # QQQ sid(26444): 0.17, # JKE sid(26445): 0.13, # JKF sid(26447): 0.12, # JKH sid(26448): 0.13, # JKI sid(26454): 0.10, # JKK sid(26451): 0.0 # JKL } # Dictionary of target weights for each asset. context.target_weights = {} # Dictionary of target number of shares for each asset. context.target_shares = {} # Dictionary of flags for each month for each asset. # Each entry for each asset is {'UP': x, 'DOWN': y} context.flags = {} # Dictionary of latest prices for each asset. context.price = {} # Dictionary of latest UP ratios for each asset. context.up_ratios = {} # Set of assets that have recevied first multiple down flag sequence. context.first_down_sequence = set() # First iteration: initialize weightings etc. context.first_iteration = True # Overweighting: True in 2020 context.overweighting = False # Record tracking variables at the end of each day. algo.schedule_function( record_vars, algo.date_rules.every_day(), algo.time_rules.market_close(), ) # Place orders at the end of each month. algo.schedule_function(place_orders, algo.date_rules.month_end())
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): """ Called once at the start of the algorithm. """ context.security = sid(24) # Rebalance every day, 1 hour after market open. algo.schedule_function( rebalance, algo.date_rules.every_day(), algo.time_rules.market_open(hours=1), )