Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Variable weights issue

Hi,
I was trying to implement an algo that would go long(short) overnight if the "last 30 minutes of trading" returns are positive(negative).
However when I tried to implement variable weights instead of fixed ones it started acting weird and stopped trading completely.
Can anyone help me understand what I am doing wrong?
Thanks in advance!

7 responses

You can click a line number in the margin, run it, and examine the outputs by running those things manually from the console prompt that appears.
returns are nans. You might want something more like this although I've combined two lines, not necessary.

returns = data.history(context.base_universe, 'close', 60, '1m').pct_change()

Then the ordering will need to be changed like this:

for stock in longs.index:  
    order_target_percent(stock, longs[stock])  
for stock in shorts.index:  
    order_target_percent(stock, shorts[stock])  

Some of your earlier algos also had that problem in one of the functions while the other was ok, you'll want to revisit those. Once you get used to the debugger, it's indispensable.

Notice since overnight_returns are then positives and negatives, you could try feeding that directly to order_optimal_portfolio's MaximizeAlpha() and skip all the rest. If it doesn't go well, add a minus sign.

Full disclosure almost, I was messing around with your prior code ... didn't intend to post this and lazily using o twice, standing for order and overnight.

from quantopian.pipeline.filters import QTradableStocksUS  
import quantopian.optimize  as op

def initialize(context):  
    c = context  
    c.nullzone = .2  
    ...

def mrkt_open(context, data):  
    '''  short if the 'overnight returns' are positive and long otherwise,  only for the best, worst n%  
    '''  
    c = context  
    if not c.portfolio.positions: return  
    cancel_orders(context, data)  
    # open today and the close of yesterday assumes run at 1 minute after open.  
    prices  = data.history(c.portfolio.positions.keys(), 'price', 2, '1m')  
    onr     = prices.pct_change().iloc[-1].dropna()    # overnight_returns  
    if not len(onr): return  
    o = onr   # for logging the difference  
    o = o[ (o > (o.max() * (c.nullzone * .5))) | (o < (o.min() * (c.nullzone * .5))) ]  
    log.info('{} {}'.format(len(onr), len(o)))  
    order_optimal_portfolio(  
        #objective   = op.TargetWeights(    o    ),  
        objective   = op.MaximizeAlpha(    -o    ),  
        constraints = [  
            op.PositionConcentration.with_equal_bounds(-.03, .03),  
            op.MaxGrossExposure(1.0),  
            op.Frozen( set(c.portfolio.positions.keys()) - set(o.index) ),  
        ],)

def cancel_orders(context, data):  
    c = context  
    oos = get_open_orders()  
    for s in c.portfolio.positions:  
        if s in oos:  
            for o in oos[s]:  
                cancel_order(o.id)  


Thanks Blue Seahawk!
Now my code seems to work. And thanks for the suggestions with the debugger too!
I just have a couple of questions concerning this last comment's code you shared with me:
1) What is the null zone you define and why it is important?
2) I tried to implement you "order_optimal_portfolio" strategy instead of the one I'm using now. However, I am trying to built a strategy where I have variable weights, but the "TargetWeights" seems to use a fixed weight approach instead; am I right?

Weights are positive and negative so nullzone at .2 is saying to exclude those with weights around zero in effect, at 10% above and below the middle. If they have weaker signals (those around 0 in this case) it could be good to try exclusions. If set to 0.0, no exclusion. If .8 then keeping just to top above 90% and the lowest 10%. That's the idea. I'd like to know of any other ways to do that not requiring an additional import.

Someone asked about the possibility of a bug in TargetWeights yesterday.
I haven't read the docs on order_optimal_portfolio carefully so I think you'll be better served from official sources and discussions out there.
Glad that helped and thanks for mentioning it.

https://www.google.com/search?q="TargetWeights"+site:quantopian.com
https://www.google.com/search?q="order_optimal_portfolio"+site:quantopian.com

Besides the debugger, also that type of search above is among the list of best of useful means for making progress efficiently. Then after a search, the 'Tools' button allows for sorting by date, sometimes useful too.

So I tried to implement the code using the order_optimal_portfolio function as you suggested, but my algo doesn't seem to be trading anymore. Do you have any idea what I am doing wrong this time?

In that order_optimize_portfolio (opt or optimize for a shorter nickname) code I posted it was from when I was messing around with your prior, earlier code from https://www.quantopian.com/posts/p-slash-e-pipeline-filter-implementation where positions were also being held overnight but there were two scheduled functions for opening positions. Above, there's only one so the line if not c.portfolio.positions: return is keeping it from getting started because I had set history to operate on c.portfolio.positions.keys().

Couple of versions ...

All optimize