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(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): pipeline_output_df = pipeline_output('pipeline').dropna(how='any') # part of constrains max_lever = opt.MaxGrossExposure(context.max_lever) dollar_net = opt.DollarNeutral() constrain_sector_style_risk = opt.experimental.RiskModelExposure( risk_model_loadings=context.risk_loading_pipeline, version=0, ) todays_predictions = pipeline_output_df.Model target_weight_series = todays_predictions.sub(todays_predictions.mean()) target_weight_series = target_weight_series/target_weight_series.abs().sum() order_optimal_portfolio( objective=TargetWeights(target_weight_series), constraints=[ #constrain_posTam, max_lever, constrain_sector_style_risk, dollar_net ] ) pass
def rebalance(context, data): # Obtener dataframes pipeline_data = context.pipeline_data risk_loadings = context.risk_loadings # Objetivo: Maximizar retornos para el factor combinado objective = opt.MaximizeAlpha(pipeline_data.combined_factor) # Definir la lista de restricciones constraints = [] # Restricción: Limitar la exposición maxima de la inversión (Donde 1 es el 100%) constraints.append(opt.MaxGrossExposure(MAX_GROSS_LEVERAGE)) # Restricción: Realizar Long y short en la misma proporción constraints.append(opt.DollarNeutral()) # Crear restricción del modelo de riesgo neutralize_risk_factors = opt.experimental.RiskModelExposure( risk_model_loadings=risk_loadings, version=0) constraints.append(neutralize_risk_factors) # Restricción: Limitar la cantidad de dinero que se invierte en una sola acción (Donde 1 es el 100%) constraints.append( opt.PositionConcentration.with_equal_bounds( min=-MAX_SHORT_POSITION_SIZE, max=MAX_LONG_POSITION_SIZE)) # Calcular pesos de una cartera óptima y haga pedidos hacia esa cartera segun el objetivo y las restricciones especificadas 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): # 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): # 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_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 balance(context, data): history_stock = data.history(context.stock, 'price', 20, '1d') history_guide = data.history(context.guide, 'price', 20, '1d') price_stock = data.current(context.stock, 'price') price_guide = data.current(context.guide, 'price') mean_stock = np.mean(history_stock) mean_guide = np.mean(history_guide) stddev_stock = np.std(history_stock) stddev_guide = np.std(history_guide) zscore_stock = (price_stock - mean_stock) / stddev_stock zscore_guide = (price_guide - mean_guide) / stddev_guide context.weight_stock = 0.5 context.weight_guide = -0.5 if (abs(zscore_guide) > abs(zscore_stock)) & (zscore_stock > 0) & (zscore_guide > 0): context.weight_stock = .9 if (abs(zscore_stock) > abs(zscore_guide)) & (zscore_stock < 0) & (zscore_guide < 0): context.weight_guide = -.9 #record(leverage = context.account.leverage) objective = opt.TargetWeights({ context.stock: context.weight_stock, context.guide: context.weight_guide }) constraints = [opt.MaxGrossExposure(1.0)] algo.order_optimal_portfolio(objective, 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): # 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): pipeline_data = context.pipeline_data risk_loadings = context.risk_loadings objective = opt.MaximizeAlpha(pipeline_data.combined_factor) constraints = [] # Constrain our maximum gross leverage constraints.append(opt.MaxGrossExposure(MAX_GROSS_LEVERAGE)) # Require our algorithm to remain dollar neutral 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): """ 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): #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(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): pipeline_data = context.pipeline_data # demean and normalize combined_alpha = pipeline_data.combined_alpha - pipeline_data.combined_alpha.mean( ) combined_alpha = combined_alpha / combined_alpha.abs().sum() objective = opt.MaximizeAlpha(combined_alpha) constraints = [] constraints.append(opt.MaxGrossExposure(MAX_GROSS_EXPOSURE)) 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_loading_pipeline, # version=opt.Newest, # ) # constraints.append(risk_model_exposure) order_optimal_portfolio( objective=objective, constraints=constraints, )
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): # 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 my_rebalance(context, data): fx_contract = data.current(context.fx, 'contract') fy_contract = data.current(context.fy, 'contract') target_weights = {} sign_f1_f2, sign_fx_fy, entry_flag = get_entry_flag(context, data) if entry_flag: # 符号が同じなのでトレードしない. context.x_short_y_long = False context.x_long_y_short = False target_weights[fx_contract] = 0.0 target_weights[fy_contract] = 0.0 c_pair = opt.Pair(fx_contract, fy_contract) else: if sign_fx_fy > 0: context.x_long_y_short = True target_weights[fx_contract] = 0.5 * context.levarage target_weights[fy_contract] = -0.5 * context.levarage c_pair = opt.Pair(fx_contract, fy_contract) else: # sign_fx_fy < 0 context.x_short_y_long = True target_weights[fx_contract] = -0.5 * context.levarage target_weights[fy_contract] = 0.5 * context.levarage c_pair = opt.Pair(fy_contract, fx_contract) order_optimal_portfolio( objective=opt.TargetWeights(target_weights), constraints=[opt.MaxGrossExposure(context.levarage), c_pair])
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): # 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): """ 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 trade(context, data): # Create a TargetWeights objective target_weights = opt.TargetWeights(context.stock_weights) # Execute the order_optimal_portfolio method with above objective and any constraint # Add opt.MaxGrossExposure(1.0) as a constraint to insure not leverage is used constraints = [] constraints.append(opt.MaxGrossExposure(1.0)) order_optimal_portfolio(objective=target_weights, constraints=constraints)
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 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): # 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, ])