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): # Get today's alphas as a MultiIndex DataFrame mdf = (pipeline_output('pipeline')).astype('float64') # Combine the alpha factors combined_alpha = get_alpha(mdf) # Define the objective objective = opt.TargetWeights(combined_alpha) # --------------------------------------------------- # Risk Constraints # --------------------------------------------------- # Uncomment the code below to add constraints # # # Define the position concentration constraint. # constrain_pos_size = opt.PositionConcentration.with_equal_bounds( # -MAX_SHORT_POSITION_SIZE, # MAX_LONG_POSITION_SIZE, # ) # # 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, # ) # # Define the max leverage constraint. # constrain_gross_leverage = opt.MaxGrossExposure(MAX_GROSS_LEVERAGE) # # Define the dollar neutral constraint. # dollar_neutral = opt.DollarNeutral() # # Add our constraints, comment or uncomment as necessary. constraints = [ # constrain_sector_style_risk, # constrain_gross_leverage, # dollar_neutral, # constrain_pos_size ] # --------------------------------------------------- # END - Risk Constraints # --------------------------------------------------- # Calculate the optimal portfolio try: combined_alpha = opt.calculate_optimal_portfolio(objective=objective, constraints=constraints) except: pass # Drop expired securites (i.e. that aren't in the tradeable universe on that date) combined_alpha = combined_alpha[combined_alpha.index.isin(pipeline_output('pipeline').index)] # Do a final null filter and normalization combined_alpha = combined_alpha[pd.notnull(combined_alpha)] combined_alpha = normalize(combined_alpha) # Define the objective objective = opt.TargetWeights(combined_alpha) # Order the optimal portfolio try: order_optimal_portfolio(objective=objective, constraints=constraints) except: pass
def rebalance(context, data): objective = opt.MaximizeAlpha(context.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) combined_alpha = opt.calculate_optimal_portfolio( objective=objective, constraints=constraints, ) context.combined_alpha = (1-ALPHA_SMOOTH)*context.combined_alpha context.combined_alpha = context.combined_alpha.add(ALPHA_SMOOTH*combined_alpha,fill_value=0).dropna() context.combined_alpha = normalize(context.combined_alpha) objective = opt.TargetWeights(context.combined_alpha) constraints = [] 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]
# Optimizar: Proporciona herramientas para definir y resolver problemas de optimización de cartera directamente # Importar libreria de optimización import quantopian.optimize as opt # Calcular pesos de una cartera óptima segun el objetivo y las restricciones especificadas pesos = opt.calculate_optimal_portfolio(objective, constraints) # Calcular pesos de una cartera óptima segun el objetivo y las restricciones especificadas devolviendo un OptimizationResultcon información adicional, pesos = opt.run_optimization(objective, constraints) # Calcular pesos de una cartera óptima y haga pedidos hacia esa cartera segun el objetivo y las restricciones especificadas pesos = algo.order_optimal_portfolio(objective, constraints)