Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How To Get Round Optimize API

Hi,

I've recently run into a problem where the Optimizer occasionally can't find a portfolio which meets all the requirements I've set out. Can someone share some code which will change the requirements of the Optimizer if a proper portfolio can't be found?

i.e.

If I've set the requirements to be dollar neutral, sector neutral and risk neutral and a portfolio can't be found, remove the risk neutral requirement etc...

2 responses
try:  
    order_optimal_portfolio(  
        objective=opt.TargetWeights(weights),  
        constraints=[  
            opt.DollarNeutral(),  
            opt.PositionConcentration.with_equal_bounds(-0.01, 0.01),  
            opt.NetGroupExposure.with_equal_bounds(  
                labels=context.output.sector,  
                min=-0.01,  
                max=0.01),  
            opt.FactorExposure(context.output[['beta']],  
                min_exposures={'beta': -0.05},  
                max_exposures={'beta': 0.05}),  
            opt.MaxGrossExposure(1.0),  
        ],  
    )  
except:  
    order_optimal_portfolio(  
        objective=opt.TargetWeights(weights),  
        constraints=[  
            opt.DollarNeutral(),  
            opt.PositionConcentration.with_equal_bounds(-0.01, 0.01),  
            opt.FactorExposure(context.output[['beta']],  
                min_exposures={'beta': -0.05},  
                max_exposures={'beta': 0.05}),  
            opt.MaxGrossExposure(1.0),  
        ],  
    )  

Hi Jamie,

I've never run into this problem. Just saw your code from another post, maybe because you were not using the latest recommended way. Try below if you havn't.

from quantopian.pipeline.experimental import risk_loading_pipeline

MAX_GROSS_EXPOSURE = 1.0  
MAX_LONG_POSITION_SIZE = 0.005   #0.5%  
MAX_SHORT_POSITION_SIZE = 0.005

def rebalance(context, data):  
    alpha = context.todays_pipeline.alpha  
    objective = opt.MaximizeAlpha(alpha)  
    constrain_gross_exposure = opt.MaxGrossExposure(MAX_GROSS_EXPOSURE)  
    market_neutral = opt.DollarNeutral()  
    #constrain_net_exposure = opt.NetExposure(min=MAX_NET_EXPOSURE*0.95, max=MAX_NET_EXPOSURE*1.05)  
    constrain_pos_size = opt.PositionConcentration.with_equal_bounds(-MAX_SHORT_POSITION_SIZE, MAX_LONG_POSITION_SIZE,)  
    factor_risk_constraints = opt.experimental.RiskModelExposure( context.todays_pipeline_risk.dropna(), version=opt.Newest )  
    algo.order_optimal_portfolio(  
        objective=objective,  
        constraints=[  
            #constrain_net_exposure,  
            constrain_gross_exposure,  
            market_neutral,  
            constrain_pos_size,  
            factor_risk_constraints,  
        ],  )