def rebalance(context, data): pipeline_data = context.pipeline_data risk_loadings = context.risk_loadings objective = opt.MaximizeAlpha(pipeline_data.combined_factor) constraints = [] constraints.append(opt.MaxGrossExposure(MAX_GROSS_LEVERAGE)) constraints.append(opt.DollarNeutral()) neutralize_risk_factors = opt.experimental.RiskModelExposure( risk_model_loadings=risk_loadings, version=0 ) constraints.append(neutralize_risk_factors) constraints.append( opt.PositionConcentration.with_equal_bounds( min=-MAX_SHORT_POSITION_SIZE, max=MAX_LONG_POSITION_SIZE )) algo.order_optimal_portfolio( objective=objective, constraints=constraints )
def rebalance(context, data): ### Optimize API pipeline_data = context.pipeline_data todays_universe = pipeline_data.index ### Extract from pipeline any specific risk factors you want # to neutralize that you have already calculated risk_factor_exposures = pd.DataFrame( {'market_beta': pipeline_data.market_beta.fillna(1.0)}) # We fill in any missing factor values with a market beta of 1.0. # We do this rather than simply dropping the values because we have # want to err on the side of caution. We don't want to exclude # a security just because it's missing a calculated market beta, # so we assume any missing values have full exposure to the market. ### Here we define our objective for the Optimize API. We have # selected MaximizeAlpha because we believe our combined factor # ranking to be proportional to expected returns. This routine # will optimize the expected return of our algorithm, going # long on the highest expected return and short on the lowest. objective = opt.MaximizeAlpha(pipeline_data.combined_rank) ### Define the list of constraints constraints = [] # Constrain our maximum gross leverage constraints.append(opt.MaxGrossLeverage(MAX_GROSS_LEVERAGE)) # Require our algorithm to remain dollar neutral constraints.append(opt.DollarNeutral()) # Add a sector neutrality constraint using the sector # classifier that we included in pipeline constraints.append( opt.NetGroupExposure.with_equal_bounds( labels=pipeline_data.sector, min=-MAX_SECTOR_EXPOSURE, max=MAX_SECTOR_EXPOSURE, )) # Take the risk factors that you extracted above and # list your desired max/min exposures to them - # Here we selection +/- 0.01 to remain near 0. neutralize_risk_factors = opt.FactorExposure( loadings=risk_factor_exposures, min_exposures={'market_beta': -MAX_BETA_EXPOSURE}, max_exposures={'market_beta': MAX_BETA_EXPOSURE}) constraints.append(neutralize_risk_factors) # With this constraint we enforce that no position can make up # greater than MAX_SHORT_POSITION_SIZE on the short side and # no greater than MAX_LONG_POSITION_SIZE on the long side. This # ensures that we do not overly concentrate our portfolio in # one security or a small subset of securities. constraints.append( opt.PositionConcentration.with_equal_bounds( min=-MAX_SHORT_POSITION_SIZE, max=MAX_LONG_POSITION_SIZE)) ### Put together all the pieces we defined above by passing # them into the order_optimal_portfolio function. This handles # all of our ordering logic, assigning appropriate weights # to the securities in our universe to maximize our alpha with # respect to the given constraints. order_optimal_portfolio(objective=objective, constraints=constraints)
def rebalance(context, data): # Each day, we will enter and exit positions by defining a portfolio optimization problem. # To do that, we need to set an objective for our portfolio as well as a series of constraints. # Our objective is to maximize alpha, where 'alpha' is defined by the negative of total_score factor. objective = opt.MaximizeAlpha(-context.total_score) # We want to constrain our portfolio to invest a maximum total amount of money (defined by MAX_GROSS_EXPOSURE). max_gross_exposure = opt.MaxGrossExposure(MAX_GROSS_EXPOSURE) # We want to constrain our portfolio to invest a limited amount in any one position. #To do this, we constrain the position to be between +/- # MAX_POSITION_CONCENTRATION (on Quantopian, a negative weight corresponds to a short position). max_position_concentration = opt.PositionConcentration.with_equal_bounds( -MAX_POSITION_CONCENTRATION, MAX_POSITION_CONCENTRATION) # We want to constraint our portfolio to be dollar neutral (equal amount invested in long and short positions). dollar_neutral = opt.DollarNeutral() # Stores all of our constraints in a list. constraints = [ max_gross_exposure, max_position_concentration, dollar_neutral, ] algo.order_optimal_portfolio(objective, constraints)
def rebalance(context, data): pipeline_data = context.pipeline_data todays_universe = pipeline_data.index risk_factor_exposures = pd.DataFrame( {'market_beta': pipeline_data.market_beta.fillna(1.0)}) objective = opt.MaximizeAlpha(pipeline_data.combined_alpha) constraints = [] constraints.append(opt.MaxGrossExposure(MAX_GROSS_EXPOSURE)) constraints.append(opt.DollarNeutral()) constraints.append( opt.NetGroupExposure.with_equal_bounds( labels=pipeline_data.sector, min=-MAX_SECTOR_EXPOSURE, max=MAX_SECTOR_EXPOSURE, )) neutralize_risk_factors = opt.FactorExposure( loadings=risk_factor_exposures, min_exposures={'market_beta': -MAX_BETA_EXPOSURE}, max_exposures={'market_beta': MAX_BETA_EXPOSURE}) constraints.append(neutralize_risk_factors) constraints.append( opt.PositionConcentration.with_equal_bounds( min=-MAX_SHORT_POSITION_SIZE, max=MAX_LONG_POSITION_SIZE)) try: order_optimal_portfolio(objective=objective, constraints=constraints, universe=todays_universe) except: return
def rebalance(context, data): # Create MaximizeAlpha objective using objective = opt.MaximizeAlpha(context.output.sentiment_score) # Create position size constraint constrain_pos_size = opt.PositionConcentration.with_equal_bounds( -context.max_short_pos_size, context.max_long_pos_size) # Ensure long and short books are reoughly equal dollar_neutral = opt.DollarNeutral() # Constrain target portfolio's leverage max_leverage = opt.MaxGrossExposure(context.max_leverage) # Constrain portfolio turnover max_turnover = opt.MaxTurnover(context.max_turnover) # Constrain target portfolio's risk exposure | sector = 0.2 style = 0.4 factor_risk_constraints = opt.experimental.RiskModelExposure( context.risk_factor_betas, version=opt.Newest) # Rebalance portfolio using objective and constraints order_optimal_portfolio(objective=objective, constraints=[ max_leverage, dollar_neutral, constrain_pos_size, max_turnover, factor_risk_constraints, ])
def rebalance(context, data): """ A function scheduled to run once every Monday at 10AM ET in order to rebalance the longs and shorts lists. Parameters ---------- context : AlgorithmContext See description above. data : BarData See description above. """ pipeline_data = context.pipeline_data risk_loadings = context.risk_loadings objective = opt.MaximizeAlpha(pipeline_data.combined_factor) constraints = [] constraints.append(opt.MaxGrossExposure(MAX_GROSS_LEVERAGE)) constraints.append(opt.DollarNeutral()) neutralize_risk_factors = opt.experimental.RiskModelExposure( risk_model_loadings=risk_loadings, version=0) constraints.append(neutralize_risk_factors) constraints.append( opt.PositionConcentration.with_equal_bounds( min=-MAX_SHORT_POSITION_SIZE, max=MAX_LONG_POSITION_SIZE)) algo.order_optimal_portfolio(objective=objective, constraints=constraints)
def rebalance(context, data): """ A function scheduled to run once every Monday at 10AM ET in order to rebalance the longs and shorts lists. Parameters ---------- context : AlgorithmContext See description above. data : BarData See description above. """ # Retrieve pipeline output pipeline_data = context.pipeline_data risk_loadings = context.risk_loadings # Here we define our objective for the Optimize API. We have # selected MaximizeAlpha because we believe our combined factor # ranking to be proportional to expected returns. This routine # will optimize the expected return of our algorithm, going # long on the highest expected return and short on the lowest. objective = opt.MaximizeAlpha(pipeline_data.combined_factor) # Define the list of constraints constraints = [] # Constrain our maximum gross leverage constraints.append(opt.MaxGrossExposure(MAX_GROSS_LEVERAGE)) # Require our algorithm to remain dollar neutral constraints.append(opt.DollarNeutral()) # Add the RiskModelExposure constraint to make use of the # default risk model constraints neutralize_risk_factors = opt.experimental.RiskModelExposure( risk_model_loadings=risk_loadings, version=0 ) constraints.append(neutralize_risk_factors) # With this constraint we enforce that no position can make up # greater than MAX_SHORT_POSITION_SIZE on the short side and # no greater than MAX_LONG_POSITION_SIZE on the long side. This # ensures that we do not overly concentrate our portfolio in # one security or a small subset of securities. constraints.append( opt.PositionConcentration.with_equal_bounds( min=-MAX_SHORT_POSITION_SIZE, max=MAX_LONG_POSITION_SIZE )) # Put together all the pieces we defined above by passing # them into the algo.order_optimal_portfolio function. This handles # all of our ordering logic, assigning appropriate weights # to the securities in our universe to maximize our alpha with # respect to the given constraints. algo.order_optimal_portfolio( objective=objective, constraints=constraints )
def rebalance(context, data): # Retrieve pipeline output pipeline_data = context.pipeline_data risk_loadings = context.risk_loadings objective = opt.MaximizeAlpha(pipeline_data.combined_factor) # Define the list of constraints constraints = [] # Constrain our maximum gross leverage constraints.append(opt.MaxGrossExposure(MAX_GROSS_LEVERAGE)) # Require our algorithm to remain dollar neutral constraints.append(opt.DollarNeutral()) # Add the RiskModelExposure constraint to make use of the # default risk model constraints neutralize_risk_factors = opt.experimental.RiskModelExposure( risk_model_loadings=risk_loadings, version=0) constraints.append(neutralize_risk_factors) #constraints para las posiciones de las securities constraints.append( opt.PositionConcentration.with_equal_bounds( min=-MAX_SHORT_POSITION_SIZE, max=MAX_LONG_POSITION_SIZE)) algo.order_optimal_portfolio(objective=objective, constraints=constraints)
def rebalance(context, data): #my_positions = context.portfolio.positions # Optimize API pipeline_data = context.pipeline_data # Extract from pipeline any specific risk factors to neutralize that have already been calculated risk_factor_exposures = pd.DataFrame( {'market_beta': pipeline_data.market_beta.fillna(1.0)}) # Fill in any missing factor values with a market beta of 1.0. # Do this rather than simply dropping the values because want to err on the side of caution. Don't want to exclude a security just because it is missing a calculated market beta data value, so assume any missing values have full exposure to the market. # Define objective for the Optimize API. # Here we use MaximizeAlpha because we believe our combined factor ranking to be proportional to expected returns. This routine will optimize the expected return of the algorithm, going long on the highest expected return and short on the lowest. objective = opt.MaximizeAlpha(pipeline_data.combined_rank) # Define the list of constraints constraints = [] # Constrain maximum gross leverage constraints.append(opt.MaxGrossExposure(MAX_GROSS_EXPOSURE)) # Require algorithm to remain dollar-neutral constraints.append(opt.DollarNeutral()) # default tolerance = 0.0001 # Add sector neutrality constraint using the sector classifier included in the pipeline constraints.append( opt.NetGroupExposure.with_equal_bounds( labels=pipeline_data.sector, min=-MAX_SECTOR_EXPOSURE, max=MAX_SECTOR_EXPOSURE, )) # Take the risk factors extracted above and list desired max/min exposures to them. neutralize_risk_factors = opt.FactorExposure( loadings=risk_factor_exposures, min_exposures={'market_beta': -MAX_BETA_EXPOSURE}, max_exposures={'market_beta': MAX_BETA_EXPOSURE}) constraints.append(neutralize_risk_factors) # With this constraint, we enforce that no position can make up greater than MAX_SHORT_POSITION_SIZE on the short side and no greater than MAX_LONG_POSITION_SIZE on the long side. This ensures we don't overly concentrate the portfolio in one security or a small subset of securities. constraints.append( opt.PositionConcentration.with_equal_bounds( min=-MAX_SHORT_POSITION_SIZE, max=MAX_LONG_POSITION_SIZE)) # Put together all the pieces defined above by passing them into the order_optimal_portfolio function. This handles all ordering logic, assigning appropriate weights to the securities in our universe to maximize alpha with respect to the given constraints. order_optimal_portfolio( objective=objective, constraints=constraints, ) #================================================================= # Python "time test", if required. Acknowledgement & thanks to Ernesto Perez, Quantopian support. #start = time.time() # Block of code you want to test here #end = time.time() #log.info(end - start) #=================================================================
def rebalance_portfolio(context, data): """ Execute orders according to our schedule_function() timing. """ predictions = context.predictions predictions = predictions.loc[data.can_trade(predictions.index)] # Select long/short positions n_positions = int(min(N_POSITIONS, len(predictions)) / 2) to_trade = (predictions[predictions > 0].nlargest(n_positions).append( predictions[predictions < 0].nsmallest(n_positions))) # Model may produce duplicate predictions to_trade = to_trade[~to_trade.index.duplicated()] # Setup Optimization Objective objective = opt.MaximizeAlpha(to_trade) # Setup Optimization Constraints constrain_gross_leverage = opt.MaxGrossExposure(1.0) constrain_pos_size = opt.PositionConcentration.with_equal_bounds(-.02, .02) market_neutral = opt.DollarNeutral() constrain_risk = RiskModelExposure( risk_model_loadings=context.risk_loading_pipeline, version=opt.Newest) # Optimizer calculates portfolio weights and # moves portfolio toward the target. order_optimal_portfolio( objective=objective, constraints=[ constrain_gross_leverage, constrain_pos_size, market_neutral, constrain_risk ], )
def rebalance(context, data): # Timeit! start_time = time.time() objective = opt.MaximizeAlpha(context.predictions) max_gross_exposure = opt.MaxGrossExposure(MAX_GROSS_EXPOSURE) max_position_concentration = opt.PositionConcentration.with_equal_bounds( -MAX_POSITION_CONCENTRATION, MAX_POSITION_CONCENTRATION) dollar_neutral = opt.DollarNeutral() constraints = [ max_gross_exposure, max_position_concentration, dollar_neutral, ] algo.order_optimal_portfolio(objective, constraints) # Print useful things. You could also track these with the "record" function. print 'Full Rebalance Computed Seconds: ' + '{0:.2f}'.format(time.time() - start_time) print "Leverage: " + str(context.account.leverage)
def rebalance(context, data): # Create MaximizeAlpha objective using # sentiment_score data from pipeline output objective = opt.MaximizeAlpha(context.output.sentiment_score) # Create position size constraint constrain_pos_size = opt.PositionConcentration.with_equal_bounds( -context.max_pos_size, context.max_pos_size) # Ensure long and short books # are roughly the same size dollar_neutral = opt.DollarNeutral() # Constrain target portfolio's leverage max_leverage = opt.MaxGrossExposure(context.max_leverage) # Constrain portfolio turnover max_turnover = opt.MaxTurnover(context.max_turnover) # Constrain target portfolio's risk exposure # By default, max sector exposure is set at # 0.2, and max style exposure is set at 0.4 factor_risk_constraints = opt.experimental.RiskModelExposure( context.risk_factor_betas, version=opt.Newest) # Rebalance portfolio using objective # and list of constraints order_optimal_portfolio(objective=objective, constraints=[ max_leverage, dollar_neutral, constrain_pos_size, max_turnover, factor_risk_constraints, ])
def rebalance(context, data): """ Execute orders according to our schedule_function() timing. """ alpha = context.output.score.dropna() if not alpha.empty: # Create MaximizeAlpha objective objective = opt.MaximizeAlpha(alpha) # Create position size constraint constrain_pos_size = opt.PositionConcentration.with_equal_bounds( -context.max_pos_size, context.max_pos_size) # Constrain target portfolio's leverage max_leverage = opt.MaxGrossExposure(context.max_leverage) # Ensure long and short books # are roughly the same size dollar_neutral = opt.DollarNeutral() # Constrain portfolio turnover max_turnover = opt.MaxTurnover(context.max_turnover) # Rebalance portfolio using objective # and list of constraints algo.order_optimal_portfolio(objective=objective, constraints=[ constrain_pos_size, max_leverage, dollar_neutral, max_turnover, ])
def rebalance(context, data): """ initialize関数内部で定義した、schedule_functionによって毎週月曜日に実行される関数。 before_trading_start()関数によって、'long_short_equity_template'がcontextに 予めセットされている。 Parameters ---------- context : AlgorithmContext See description above. data : BarData See description above. """ # contextからパイプラインデータを取り出す(ロングショート) pipeline_data = context.pipeline_data # contextからパイプラインデータを取り出す(リスクモデルデータ) risk_loadings = context.risk_loadings # 最適化APIの目的関数を定義する。 # ここではMaximizeAlpha(アルファ最大化)という組み込みの目的関数を利用する。 # combined_factorはmake_pipeline()の中でzscoreの合成値として定義されているので # その値は、正または負の値をとる。 # 正負両方の値を取り得るアルファを使って、アルファを最大化するためには、 # アルファ>0 の銘柄ならば買い(正のアルファスコア x 正のポジション = 正) # アルファ<0 の銘柄ならば売り(負のアルファスコア x 負のポジション = 正) # となることがアルファ最大化に繋がるはずである。この目的関数を指定することで、自動的に # 売り判断と買い判断を行っていることと等しくなる。 objective = opt.MaximizeAlpha(pipeline_data.combined_factor) # 目的関数最大化(アルファ最大化)をしつつ、守るべき制約条件をセットするリストの初期化 constraints = [] # 最大グロスレバレッジ制約をセット constraints.append(opt.MaxGrossExposure(MAX_GROSS_LEVERAGE)) # ドルニュートラル制約(ロングポジションの額と、ショートポジションの額が一致) constraints.append(opt.DollarNeutral()) # リスクモデルエクスポージャ制約 # アルファ以外のファクターを取らないようにすることで、純粋に自分が意図するファクターにのみ # 投資を行っていることを保証するため、リスクモデルエクスポージャ制約を入れる # 【Excesice】リスクモデルエクスポージャ制約がない場合のパフォーマンスはどうなるか? # また、そのときのriskエクスポージャが、制約アリのときと比べてどのように変化しているか? neutralize_risk_factors = opt.experimental.RiskModelExposure( risk_model_loadings=risk_loadings, version=0) constraints.append(neutralize_risk_factors) # 投資比率制約をセット。 # 今回のアルゴリズムの場合、 # 'long_short_equity_template'パイプラインにデータが含まれる時点で、必ず売買を行う # ようにしたい(らしい)。全ての銘柄は、一定の範囲内でポジションを持つように制約をセット # このようにすることで、アルファの絶対値が小さい(ゼロ近辺)の銘柄についても、必ずポジション # を持つことが保証される。言い換えればアルファの絶対値が大きい銘柄に投資を集中させない仕組み constraints.append( opt.PositionConcentration.with_equal_bounds( min=-MAX_SHORT_POSITION_SIZE, max=MAX_LONG_POSITION_SIZE)) # レッツ発注!(制約を満たしつつ、目的関数を最大化するように注文を自動作成するなんて素敵やん) algo.order_optimal_portfolio(objective=objective, constraints=constraints)
def run(context, data): objective = opt.MaximizeAlpha(context[pipe]['returns']) constraints = [ opt.MaxGrossExposure(max_invert), opt.DollarNeutral() ] algo.order_optimal_portfolio(objective, constraints)
def allocate(context, data): port = context.stocks + list( set(context.portfolio.positions.keys()) - set(context.stocks)) w = np.zeros(len(port)) for i, stock in enumerate(port): w[i] = context.portfolio.positions[stock].amount * data.current( stock, 'price') denom = np.sum(np.absolute(w)) if denom > 0: w = w / denom current_portfolio = pd.Series(w, index=port) pipeline_data = pd.DataFrame({'alpha': context.weight}, index=context.stocks) df_pipeline = context.output.ix[context.stocks] pipeline_data = pipeline_data.join(df_pipeline, how='inner') pipeline_data = pipeline_data.loc[data.can_trade(context.stocks)] objective = opt.MaximizeAlpha(pipeline_data.alpha) constrain_gross_leverage = opt.MaxGrossExposure(MAX_GROSS_LEVERAGE) constrain_pos_size = opt.PositionConcentration.with_equal_bounds( -MAX_SHORT_POSITION_SIZE, MAX_LONG_POSITION_SIZE, ) market_neutral = opt.DollarNeutral() sector_neutral = opt.NetGroupExposure.with_equal_bounds( labels=pipeline_data.sector, min=-0.0001, max=0.0001, ) constrain_turnover = opt.MaxTurnover(MAX_TURNOVER) constraints = [ constrain_gross_leverage, constrain_pos_size, market_neutral, sector_neutral, constrain_turnover ] try: weights = opt.calculate_optimal_portfolio(objective, constraints, current_portfolio) except: print "oops" return for (stock, weight) in weights.iteritems(): if data.can_trade(stock): order_target_percent(stock, weight * 3.0)
def do_portfolio_construction(context, data): pipeline_data = context.pipeline_data todays_universe = pipeline_data.index # Objective # --------- # For our objective, we simply use our naive ranks as an alpha coefficient # and try to maximize that alpha. # # This is a **very** naive model. Since our alphas are so widely spread out, # we should expect to always allocate the maximum amount of long/short # capital to assets with high/low ranks. # # A more sophisticated model would apply some re-scaling here to try to generate # more meaningful predictions of future returns. objective = opt.MaximizeAlpha(pipeline_data.alpha) # Constraints # ----------- # Constrain our gross leverage to 1.0 or less. This means that the absolute # value of our long and short positions should not exceed the value of our # portfolio. constrain_gross_leverage = opt.MaxGrossExposure(MAX_GROSS_LEVERAGE) # Constrain individual position size to no more than a fixed percentage # of our portfolio. Because our alphas are so widely distributed, we # should expect to end up hitting this max for every stock in our universe. constrain_pos_size = opt.PositionConcentration.with_equal_bounds( -MAX_SHORT_POSITION_SIZE, MAX_LONG_POSITION_SIZE, ) # Constrain ourselves to allocate the same amount of capital to # long and short positions. market_neutral = opt.DollarNeutral() # Constrain ourselve to have a net leverage of 0.0 in each sector. sector_neutral = opt.NetGroupExposure.with_equal_bounds( labels=pipeline_data.sector, min=-0.0001, max=0.0001, ) # Run the optimization. This will calculate new portfolio weights and # manage moving our portfolio toward the target. algo.order_optimal_portfolio( objective=objective, constraints=[ constrain_gross_leverage, constrain_pos_size, market_neutral, sector_neutral, ], #universe=todays_universe, )
def do_portfolio_construction(context, data): pipeline_data = context.pipeline_data # OBJECTIVE #----------- # OBJECTIVE: MAXIMIZE ALPHA BASED ON NAIVE RANKINGS # RANK ALPHA COEFFICIENT AND TRADE TO MAXIMIZE THAT ALPHA # # **NAIVE** OBJECTIVE MODEL # WITH VERY SPREAD OUT ALPHA DATA, WE SHOULD EXPECT TO ALLOCATE # MAXIMUM AMOUNT OF CONSTRAINED CAPITAL TO HIGH/LOW RANKS # # A MORE SOPHISTICATED MODEL WOULD APPLY SOME SORT OF RE-SCALING objective = opt.MaximizeAlpha(pipeline_data.alpha) # CONTRAINT SETTINGS (CONTEST DEFAULT) # ========================================================================================= # CONSTRAIN MAX GROSS LEVERAGE # IMPLICATIONS: ABSOLUTE VALUE OF OF LONG AND SHORT POSITIONS < OVERALL PORTFOLIO VALUE (1.0) MAX_GROSS_LEVERAGE = 1.0 max_leverage = opt.MaxGrossExposure(MAX_GROSS_LEVERAGE) # CONSTRAIN MAX POSITION SIZE (LONG AND SHORT) # MAX POSITION <= 1% OF OVERALL PORTFOLIO MAX_SHORT_POSITION_SIZE = 0.01 MAX_LONG_POSITION_SIZE = 0.01 max_position_weight = opt.PositionConcentration.with_equal_bounds( -MAX_SHORT_POSITION_SIZE, MAX_LONG_POSITION_SIZE) # CONSTRAIN CAPTIAL ALLOCATIONS FOR LONG AND SHORT EQUILLIBRIUM dollar_neutral = opt.DollarNeutral() # CONSTRAIN BETA-TO-SPY ***CONTEST CRITERIA*** beta_neutral = opt.FactorExposure(pipeline_data[['beta']], min_exposures={'beta': -0.05}, max_exposures={'beta': 0.05}) # CONSTRAIN COMMON SECTOR AND STYLE RISK FACTORS (NEWEST DEFAULT VALUES) # SECTOR DEFAULT: +-0.18 # STYLE DEFAULT: +-0.36 constrain_sector_style_risk = opt.experimental.RiskModelExposure( context.risk_loading_pipeline, version=opt.Newest) # EXECUTE OPTIMIZATION # ========================================================================================= # CALCULATE NEW WEIGHTS AND MANAGE MOVING PORTFOLIO TOWARD TARGET CAPITAL AND ASSET ALLOCATION algo.order_optimal_portfolio(objective=objective, constraints=[ max_leverage, max_position_weight, dollar_neutral, constrain_sector_style_risk, beta_neutral, ])
def rebalance(context, data): """ Execute orders according to our schedule_function() timing. """ predictions = context.predicted_probs # Filter out stocks that can not be traded predictions = predictions.loc[data.can_trade(predictions.index)] # Select top and bottom N stocks n_long_short = min(N_STOCKS_TO_TRADE // 2, len(predictions) // 2) predictions_top_bottom = pd.concat([ predictions.nlargest(n_long_short), predictions.nsmallest(n_long_short), ]) # If classifier predicts many identical values, the top might contain # duplicate stocks predictions_top_bottom = predictions_top_bottom.iloc[ ~predictions_top_bottom.index.duplicated() ] # predictions are probabilities ranging from 0 to 1 predictions_top_bottom = (predictions_top_bottom - 0.5) * 2 # Setup Optimization Objective objective = opt.MaximizeAlpha(predictions_top_bottom) # Setup Optimization Constraints constrain_gross_leverage = opt.MaxGrossExposure(1.0) constrain_pos_size = opt.PositionConcentration.with_equal_bounds( -0.02, +0.02, ) market_neutral = opt.DollarNeutral() if predictions_top_bottom.index.duplicated().any(): log.debug(predictions_top_bottom.head()) sector_neutral = opt.NetGroupExposure.with_equal_bounds( labels=context.risk_factors.Sector.dropna(), min=-0.0001, max=0.0001, ) # Run the optimization. This will calculate new portfolio weights and # manage moving our portfolio toward the target. order_optimal_portfolio( objective=objective, constraints=[ constrain_gross_leverage, constrain_pos_size, market_neutral, sector_neutral, ], )
def rebalance(context, data): # pipeline 出力から alpha を取り出す alpha = context.pipeline_data.sentiment_score if not alpha.empty: # MaximizeAlpha objective 作成 # alpha(つまりsentiment_score)でウェイトをつける objective = opt.MaximizeAlpha(alpha) # ポジションサイズ制約 # with_equal_bounds を使うと、どんなに小さなalphaであってもポートフォリオに組み込む # という設定。つまり大きなalphaの銘柄に大きく偏ったポートフォリオにならない。 constrain_pos_size = opt.PositionConcentration.with_equal_bounds( -context.max_pos_size, # min context.max_pos_size # max ) # ターゲットポートフォリオレバレッジ制約 # ポートフォリオのウェイトが、max_leverage 以下になるように制約 max_leverage = opt.MaxGrossExposure(context.max_leverage) # ロング(買い持ち)とショート(売り持ち)のサイズをだいたい同じに合わせる dollar_neutral = opt.DollarNeutral() # ポートフォリオの出来高の制約 # MaxTurnoverに関するドキュメントがないのでなんだか良くわからない # どうしてDocがないの?という質問がForumにあった。 # https://www.quantopian.com/posts/optimize-api-maxturnover-constraint-is-it-supported#5a3be89765ca177fe452db6d # 答えも不明瞭 max_turnover = opt.MaxTurnover(context.max_turnover) # ターゲットポートフォリオのリスクエクスポージャーを制限する。 # 2casa さんのありがたい教えによると(https://github.com/tokyoquantopian/TQUG6_20181215/blob/master/TQUG6_04-01.%E3%82%A2%E3%83%AB%E3%82%B4%E3%83%AA%E3%82%BA%E3%83%A0%E3%81%AB%E3%82%88%E3%82%8B%E3%83%90%E3%83%83%E3%82%AF%E3%83%86%E3%82%B9%E3%83%88.ipynb) # アルファ以外のファクターを取らないようにすることで、純粋に自分が意図するファクターにのみ # 投資を行っていることを保証するため、リスクモデルエクスポージャ制約を入れる # ということ。 # デフォルト値は、セクターエクスポージャーの最大値は0.2 # スタイルエクスポージャーの最大値は0.4 factor_risk_constraints = opt.experimental.RiskModelExposure( context.risk_factor_betas, # 将来のリリースで RiskModelExposure のデフォルトが変更された場合にも対応。デフォルト設定もopt.Newest version=opt.Newest) # 目的関数と制約リストを使ってポートフォリオをリバランスする algo.order_optimal_portfolio(objective=objective, constraints=[ constrain_pos_size, max_leverage, dollar_neutral, max_turnover, factor_risk_constraints, ])
def trade_sectors(context, data): context.stocks = None context.alphas = None context.betas = None context.sectors = {} for sector_id in context.sector_ids: if sector_id not in context.sectorStocks or len(context.sectorStocks[sector_id]) < 30: continue stocks, alphas, betas = find_weights(context, data, context.sectorStocks[sector_id]) if stocks is None: continue if context.stocks is None: context.stocks = stocks context.alphas = alphas context.betas = betas else: context.stocks = np.hstack((context.stocks, stocks)) context.alphas = np.hstack((context.alphas, alphas)) zero1 = np.zeros((context.betas.shape[0], betas.shape[1])) zero2 = np.zeros((betas.shape[0], context.betas.shape[1])) context.betas = np.hstack((context.betas, zero1)) betas = np.hstack((zero2, betas)) context.betas = np.vstack((context.betas, betas)) for sid in context.stocks: context.sectors[sid] = sector_id if context.stocks is None: return todays_universe = context.stocks N = context.betas.shape[1] M = context.betas.shape[0] names = [str(i) for i in range(0, N)] risk_factor_exposures = pd.DataFrame(context.betas, index=todays_universe, columns=names) objective = opt.MaximizeAlpha(pd.Series(-context.alphas, index=todays_universe)) constraints = [] constraints.append(opt.MaxGrossLeverage(1.0)) constraints.append(opt.DollarNeutral(0.0001)) neutralize_risk_factors = opt.WeightedExposure( loadings=risk_factor_exposures, min_exposures=pd.Series([-0.01] * N, index=names), max_exposures=pd.Series([0.01] * N, index=names)) constraints.append(neutralize_risk_factors) sector_neutral = opt.NetPartitionExposure.with_equal_bounds(labels=context.sectors, min=-0.0001, max=0.0001) constraints.append(sector_neutral) constraints.append(opt.PositionConcentration.with_equal_bounds(min=-10./M, max=10./M)) order_optimal_portfolio(objective=objective, constraints=constraints)
def rebalance(context, data): objective = opt.MaximizeAlpha(context.combined_alpha) constraints = [] constraints.append(opt.MaxGrossExposure(1.0)) constraints.append(opt.DollarNeutral()) constraints.append( opt.PositionConcentration.with_equal_bounds(min=-MAX_POSITION_SIZE, max=MAX_POSITION_SIZE)) risk_model_exposure = opt.experimental.RiskModelExposure( context.risk_loadings, version=opt.Newest, ) constraints.append(risk_model_exposure) beta_neutral = opt.FactorExposure(loadings=context.beta_pipeline[['beta']], min_exposures={'beta': 0}, max_exposures={'beta': 0}) constraints.append(beta_neutral) if context.init: order_optimal_portfolio( objective=objective, constraints=constraints, ) if USE_MaxTurnover: context.init = False return turnover = np.linspace(MIN_TURN, 0.65, num=100) for max_turnover in turnover: constraints.append(opt.MaxTurnover(max_turnover)) try: order_optimal_portfolio( objective=objective, constraints=constraints, ) constraints = constraints[:-1] record(max_turnover=max_turnover) return except: constraints = constraints[:-1]
def rebalance(context, data): # Define the objective objective = opt.MaximizeAlpha(-context.recent_returns_z_score) max_gross_exposure = opt.MaxGrossExposure(max_leverage) max_position_concentration = opt.PositionConcentration.with_equal_bounds( -max_exposure, max_exposure) dollar_neutral = opt.DollarNeutral() constraints = [ max_gross_exposure, max_position_concentration, dollar_neutral ] algo.order_optimal_portfolio(objective, constraints)
def rebalance(context, data): """ A function scheduled to run once at the start of the week an hour and half after market open to order an optimal portfolio of assets. Parameters ---------- context : AlgorithmContext See description above. data : BarData See description above. """ # Each day, we will enter and exit positions by defining a portfolio optimization # problem. To do that, we need to set an objective for our portfolio as well # as a series of constraints. You can learn more about portfolio optimization here: # https://www.quantopian.com/help#optimize-title # Our objective is to maximize alpha, where 'alpha' is defined by the negative of # recent_returns_zscore factor. objective = opt.MaximizeAlpha(-context.recent_returns_zscore) # We want to constrain our portfolio to invest a maximum total amount of money # (defined by MAX_GROSS_EXPOSURE). max_gross_exposure = opt.MaxGrossExposure(MAX_GROSS_EXPOSURE) # We want to constrain our portfolio to invest a limited amount in any one # position. To do this, we constrain the position to be between +/- # MAX_POSITION_CONCENTRATION (on Quantopian, a negative weight corresponds to # a short position). max_position_concentration = opt.PositionConcentration.with_equal_bounds( -MAX_POSITION_CONCENTRATION, MAX_POSITION_CONCENTRATION) # We want to constraint our portfolio to be dollar neutral (equal amount invested in # long and short positions). dollar_neutral = opt.DollarNeutral() # Stores all of our constraints in a list. constraints = [ max_gross_exposure, max_position_concentration, dollar_neutral, ] algo.order_optimal_portfolio(objective, constraints)
def rebalance(context, data): pipeline_data = context.pipeline_data risk_loadings = context.risk_loadings objective = opt.MaximizeAlpha(pipeline_data.combined_factor) # Define the list of constraints constraints = [] # Constrain our maximum gross leverage constraints.append(opt.MaxGrossExposure(MAX_GROSS_LEVERAGE)) # Require our algorithm to remain dollar neutral constraints.append(opt.DollarNeutral()) # Add the RiskModelExposure constraint to make use of the # default risk model constraints neutralize_risk_factors = opt.experimental.RiskModelExposure( risk_model_loadings=risk_loadings, version=0 ) constraints.append(neutralize_risk_factors) # With this constraint we enforce that no position can make up # greater than MAX_SHORT_POSITION_SIZE on the short side and # no greater than MAX_LONG_POSITION_SIZE on the long side. This # ensures that we do not overly concentrate our portfolio in # one security or a small subset of securities. constraints.append( opt.PositionConcentration.with_equal_bounds( min=-MAX_SHORT_POSITION_SIZE, max=MAX_LONG_POSITION_SIZE )) # Put together all the pieces we defined above by passing # them into the algo.order_optimal_portfolio function. This handles # all of our ordering logic, assigning appropriate weights # to the securities in our universe to maximize our alpha with # respect to the given constraints. algo.order_optimal_portfolio( objective=objective, constraints=constraints )
def rebalance(context, data): pipeline_data = context.pipeline_data todays_universe = pipeline_data.index risk_factor_exposures = pd.DataFrame( {'market_beta': pipeline_data.market_beta.fillna(1.0)}) objective = opt.MaximizeAlpha(pipeline_data.combined_alpha) # Setup Optimization Constraints constrain_gross_leverage = opt.MaxGrossExposure(1.0) constrain_pos_size = opt.PositionConcentration.with_equal_bounds( -0.02, +0.02, ) market_neutral = opt.DollarNeutral() neutralize_risk_factors = opt.FactorExposure( loadings=risk_factor_exposures, min_exposures={'market_beta': -MAX_BETA_EXPOSURE}, max_exposures={'market_beta': MAX_BETA_EXPOSURE}) # Constrain our risk exposures. We're using version 0 of the default bounds # which constrain our portfolio to 18% exposure to each sector and 36% to # each style factor. constrain_sector_style_risk = opt.experimental.RiskModelExposure( risk_model_loadings=context.risk_loading_pipeline, version=0, ) # Run the optimization. This will calculate new portfolio weights and # manage moving our portfolio toward the target. algo.order_optimal_portfolio( objective=objective, constraints=[ constrain_gross_leverage, constrain_pos_size, market_neutral, neutralize_risk_factors, constrain_sector_style_risk, ], ) """
def my_rebalance(context, data): """ Execute orders according to our schedule_function() timing. """ context.iDays += 1 if (context.iDays % context.NDays) != 1: return predictions = context.predicted_probs predictions = predictions.loc[data.can_trade(predictions.index)] n_long_short = min(N_STOCKS_TO_TRADE // 2, len(predictions) // 2) predictions_top_bottom = pd.concat([ predictions.nlargest(n_long_short), predictions.nsmallest(n_long_short) ]) predictions_top_bottom = predictions_top_bottom.iloc[ ~predictions_top_bottom.index.duplicated()] todays_universe = predictions_top_bottom.index predictions_top_bottom = (predictions_top_bottom - 0.5) * 2 objective = opt.MaximizeAlpha(predictions_top_bottom) constrain_gross_leverage = opt.MaxGrossExposure(.90) constrain_pos_size = opt.PositionConcentration.with_equal_bounds(-.02, .02) market_neutral = opt.DollarNeutral() if predictions_top_bottom.index.duplicated().any(): log.debug(predictions_top_bottom.head()) order_optimal_portfolio( objective=objective, constraints=[ constrain_gross_leverage, constrain_pos_size, market_neutral, ], )
def rebalance(context, data): objective = opt.MaximizeAlpha(context.output.sentiment_score) constrain_posTam = opt.PositionConcentration.with_equal_bounds( -1.5 * context.max_posTam, context.max_posTam) dollar_net = opt.DollarNeutral() max_lever = opt.MaxGrossExposure(context.max_lever) max_Volum = opt.MaxTurnover(context.max_Volum) factor_risk_constraints = opt.experimental.RiskModelExposure( context.risk_factor_betas, version=opt.Newest) order_optimal_portfolio(objective=objective, constraints=[ max_lever, dollar_net, constrain_posTam, max_Volum, factor_risk_constraints, ])
def rebalance(context, data): alpha = context.pipeline_data.sentiment_score if not alpha.empty: objective = opt.MaximizeAlpha(alpha) #Constrain position size constrain_position_size = opt.PositionConcentration.with_equal_bounds( -context.max_position_size, context.max_position_size ) #Constrain portfolio exposure max_leverage = opt.MaxGrossExposure(context.max_position_size) #Ensure long and short books are roughly the same size dollar_neutral = opt.DollarNeutral() max_turnover = opt.MaxTurnover(context.max_turnover) factor_risk_constraints = opt.experimental.RiskModelExposure( context.risk_factor_betas, version=opt.Newest ) algo.order_optimal_portfolio( objective = objective, constraints = [ constrain_position_size, max_leverage, dollar_neutral, max_turnover, factor_risk_constraints, ]) log.debug(context.pipeline_data.head())
def rebalance(context, data): objective = opt.MaximizeAlpha( context.output.sentiment_score ) # Create position size constraint constrain_posTam = opt.PositionConcentration.with_equal_bounds(-1.5*context.max_posTam,context.max_posTam) # Ensure long and short books # are roughly the same size dollar_neutral = opt.DollarNeutral() # Constrain target portfolio's lever max_lever = opt.MaxGrossExposure(context.max_lever) # Constrain portfolio Volum max_Volum = opt.MaxTurnover(context.max_Volum) factor_risk_constraints = opt.experimental.RiskModelExposure( context.risk_factor_betas, version=opt.Newest ) # Rebalance portfolio using objective # and list of constraints order_optimal_portfolio( objective=objective, constraints=[ max_lever, dollar_neutral, constrain_posTam, max_Volum, factor_risk_constraints, ] )