Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Find Daily Gainers or Losers
API

Is there a simple way get top gainers or top losers in a given day at a particular time, like what google finance gives on its homepage. I have looked at the code here, but I am having difficulty understanding it and getting it to work. What I am imagining is that schedule_function() could be used to then get top gainers or losers at a particular time in a trading day.

2 responses

The best would be to use Pipeline API and use screening functionality to select from all available securities the gainers/losers. Unfortunately you have some limitations:
- you can use pipiline only on daily data, it means you'll end up having the previous day gainers and losers, not current day and not intra-day
- even though the above limitation wouldn't affect you, a current issue ("It is a known issue that access to USEquityPricing.open is broken on Quantopian due to conflicts with our security sandbox. This will be fixed in an upcoming release") doesn't allow the calculation of the previous day returns as close/open price difference

Because you cannot use the Pipeline API you can calculate the daily top loser/gainers manually in handle_data. This means you are restricted to access a subset of securities, only the ones present in your daily universe, that means you can have the "top of MY universe" not the "top of THE universe" losers/gainers :)

I didn't debug the code but you can do something like this:

def handle_data(context, data):

    # get today open and current price  
    open_history = history(bar_count=1, frequency='1d', field='open_price')  
    close_history = history(bar_count=1, frequency='1d', field='close_price')

    # calculate daily returns up to this minute  
    returns_pct = {sid : ((close_history[sid][-1] - open_history[sid][-1]) / open_history[sid][-1]) for sid in data if (sid in close_history and sid in open_history) }

    returns_pct = pd.Series(returns_pct)

    # get top gainers / losers  
    top_gainers = returns_pct.order(ascending=False).iloc[:10]  
    top_losers = returns_pct.order(ascending=True).iloc[:10]

    # and print them  
    print 'Top gainers'  
    for sid in top_gainers.index:  
        print '{sid} gain={gain} % open price {open} close price {close}'.format(sid=sid, gain=top_gainers[sid]*100, open=open_history[sid][-1], close=close_history[sid][-1])


    print 'Top losers'  
    for sid in top_losers.index:  
        print '{sid} gain={gain} % open price {open} close price {close}'.format(sid=sid, gain=top_losers[sid]*100, open=open_history[sid][-1], close=close_history[sid][-1])  

Edit: updated with a meaningful algorithm