def rebalance(context, data): alpha = context.pipeline_data.sentiment_score if not alpha.empty: objective = opt.MaximizeAlpha(alpha) constrain_pos_size = opt.PositionConcentration.with_equal_bounds( -context.max_pos_size, constrain.max_pos_size ) max_leverage = opt.MaxGrossExposure(context.max_leverage) dollar_neutral = opt.DollarNeutral() max_turnover = opt.MaxTurnover(context.max_turnover) factor_risk_constrains = opt.experimental.RiskModelExposure( context.risk_factor_betas, version = opt.Newest ) algo.order_optimal_portfolio( objective = objective, constrains = [ constrain_pos_size, max_leverage, dollar_neutral, max_turnover, factor_risk_constrains ] )
def rebalance_pairs(context, data): # Calculate how far away the current spread is from its equilibrium zscore = calc_spread_zscore(context, data) # Get target weights to rebalance portfolio target_weights = get_target_weights(context, data, zscore) 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) # 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 if target_weights: # If we have target weights, rebalance portfolio order_optimal_portfolio( opt.TargetWeights(target_weights), constraints=[ dollar_neutral , ] )
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) # 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 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, constrain_pos_size, max_turnover, factor_risk_constraints, ])
def rebalance(context, data): """ Execute orders according to our schedule_function() timing. """ # Attempts to allocate capital to assets based on sentiment score objective = opt.MaximizeAlpha(context.output.sentiment_score) # Constrain positions constrain_pos_size = opt.PositionConcentration.with_equal_bounds( -context.max_pos_size, context.max_pos_size) # Constrain risk exposure factor_risk_constraints = opt.experimental.RiskModelExposure( context.risk_factor_betas, version=opt.Newest) # 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) algo.order_optimal_portfolio(objective=objective, constraints=[ max_leverage, dollar_neutral, max_turnover, constrain_pos_size, 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): # 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. """ weights = compute_weights(context, data) # Optimize API variables objective = opt.TargetWeights(weights) leverage_constraint = opt.MaxGrossExposure(MAX_GROSS_LEVERAGE) max_turnover = opt.MaxTurnover(context.max_turnover) factor_risk_constraints = opt.experimental.RiskModelExposure( context.risk_factor_betas, version=opt.Newest ) position_size = opt.PositionConcentration.with_equal_bounds( -MAX_SHORT_POSITION_SIZE, MAX_LONG_POSITION_SIZE, ) market_neutral = opt.DollarNeutral() algo.order_optimal_portfolio( objective = objective, constraints = [ leverage_constraint, position_size, market_neutral, max_turnover, factor_risk_constraints, ], )
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 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 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 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_clean 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.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.append(opt.MaxTurnover(0.2)) # 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): 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): # Get the alpha factor data from the pipeline output output = pipeline_output('pipeline') alpha_factor = output.alpha_factor log.info(alpha_factor) # Weight securities by their alpha factor # Divide by the abs of total weight to create a leverage of 1 weights = alpha_factor / alpha_factor.abs().sum() # Must use TargetWeights as an objective order_optimal_portfolio( objective=opt.TargetWeights(weights), constraints=[opt.MaxTurnover(0.2)], )
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, ] )