Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to implement long only optimization?

Hey guys, I would like to change my dollar neutral portfolio to a long only portfolio but struggle with the opt api.

You can see my current implementation below. Do you guys know how I can change the optimization to long only?

thanks for your help

Kind regards

Marcel

UNIVERSE_SIZE = 500
MIN_MARKET_CAP_PERCENTILE = 50
LIQUIDITY_LOOKBACK_LENGTH = 100

MAX_GROSS_LEVERAGE = 1.0
MAX_SHORT_POSITION_SIZE = 0.00
MAX_LONG_POSITION_SIZE = 0.1

MINUTES_AFTER_OPEN_TO_TRADE = 10
BASE_UNIVERSE_RECALCULATE_FREQUENCY = 'week_start'

def before_trading_start(context, data):

context.pipeline_data = algo.pipeline_output('pipe')

def portfolio_construction(context, data):

pipeline_data = context.pipeline_data  
todays_universe = pipeline_data.index

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,  
)

algo.order_optimal_portfolio(  
    objective=objective,  
    constraints=[  
        constrain_gross_leverage,  
        constrain_pos_size,  
        sector_neutral,  
    ]  
)  
1 response

To create a long only portfolio simply add a 'LongOnly' constraint before placing orders. Something like this.

    # Create a LongOnly constraint  
    long_only = opt.LongOnly(todays_universe)

    # Add the LongOnly constraint  
    order_optimal_portfolio(  
          objective=objective,  
          constraints=[  
                constrain_gross_leverage,  
                constrain_pos_size,  
                long_only,  
                ]  
)

One issue with the algo in the original post is that it also included a 'NetGroupExposure' constraint of min/max = -0.0001/0.0001 grouped by sector. If long only, one can only get this small a net group exposure by not buying much (since there are no shorts to net out the long exposure). Therefore, unless this constraint is removed, or the bounds are changed, the algo won't buy much of anything.