Back to Community
Can someone check my logic? Trying to calculate top gainers and losers by percentage each day

I have an algo and I am trying to calculate the top gainers and losers throughout a day where yesterdays_data is the closing price from the day before for all the stocks in the universe, and todays_data is the current price of all of the stocks in the universe.

  # Calculate the percentage gained since closing yesterday for all the stocks  
            todays_gain_since_open = (todays_data['price'] / context.yesterdays_data['close']) * 100.0  
            # Get the top 5 gainers and losers for the day  
            top_gainers = todays_gain_since_open.nlargest(5)  
            top_losers = todays_gain_since_open.nsmallest(5)  
            # Here we log the data but could also do more logic  
            log.info('top gainers {} top losers {}'.format(top_gainers, top_losers))  

I think the logic makes sense, but the numbers don't look right. My losers aren't negative as I would expect. Quick checking against other resources like Yahoo finance the numbers don't look right either.
Any ideas what I am doing wrong here?

Clone Algorithm
2
Loading...
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
"""
Algorithm to log the top gainers and losers each minute

"""

# import pipeline methods 
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline, CustomFactor

# import the built in filters and factors
from quantopian.pipeline.filters import QTradableStocksUS, Q1500US, Q500US, StaticAssets

# import any datasets we need
pass

# import numpy and pandas just because they rock
import numpy as np
import pandas as pd

def get_end_of_day_prices(context, data):
    context.yesterdays_data = (data.
                   history(assets=context.stocks,
                           fields=['close', 'price', 'volume'],
                           bar_count=1,
                           frequency='1d')
                   .to_frame()
                   .xs(context.today, level=0)
                   )
    

def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    # Make our pipeline and attach to the algo
    # Used only to get our universe of stocks to check
    attach_pipeline(make_stock_pipeline(context), 'my_stocks')
    context.yesterdays_data = None
    schedule_function(  
        func=get_end_of_day_prices,  
        date_rule=date_rules.every_day(),  
        time_rule=time_rules.market_close(minutes=2)  
    )
    context.minuteCounter = 0 
    

def make_stock_pipeline(context):
    """
    Used to get a list of stocks.
    This will be the universe to check for gainers and losers
    """

    # Set universe 
    stock_universe = QTradableStocksUS()
    
    pipe = Pipeline(
        columns={},
        screen=stock_universe
    )
    return pipe
            
def before_trading_start(context, data):
    # Fetch our universe of stocks as a list
    context.stocks = pipeline_output('my_stocks').index.tolist()
    # Fetch the current day
    context.today = get_datetime().date()

def handle_data(context, data):
    # Fetch the current data. 
    # 'open' is the days open
    # 'price' is the last current price
    # turn the returned panel into a dataframe and drop the date level with 'xs'
    context.minuteCounter += 1
 
    # counter
    if context.minuteCounter >= 10:
        context.minuteCounter = 0
    
        todays_data = (data.
                   history(assets=context.stocks,
                           fields=['open', 'price', 'volume'],
                           bar_count=1,
                           frequency='1d')
                   .to_frame()
                   .xs(context.today, level=0)
                   )
        
        if context.yesterdays_data is not None:
            
            # Calculate the percentage gained since closing yesterday for all the stocks
            todays_gain_since_open = (todays_data['price'] / context.yesterdays_data['close']) * 100.0
    
            # Get the top 5 gainers and losers for the day
            top_gainers = todays_gain_since_open.nlargest(5)
            top_losers = todays_gain_since_open.nsmallest(5)
    
            # Here we log the data but could also do more logic
            log.info('top gainers {} top losers {}'.format(top_gainers, top_losers))
There was a runtime error.
2 responses

The main reason why gainers aren't positive and losers aren't negative (as you expected) is your 'gain' calculation. The algo above uses

    todays_gain_since_open = (todays_data['price'] / context.yesterdays_data['close']) * 100.0

If one want's positive and negative values, then subtract 1. Like this.

    todays_gain_since_open = ((todays_data['price'] / context.yesterdays_data['close']) -1 )* 100.0

However, there is one other issue. Don't ever store price or volume data to use in subsequent days. The values won't be adjusted for splits or dividends and therefore may give incorrect results. In the algo this is being done with 'context.yesterdays_data'. Since you are using pipeline to get a list of stocks, the simplest way to get the closing price is to add a column in your pipeline. These values will be adjusted as of the current day.

Attached is a revised algo which I believe does what you want.

Good luck.

Clone Algorithm
5
Loading...
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
"""
Algorithm to log the top gainers and losers each minute

"""

# import pipeline methods 
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline, CustomFactor

# import the built in filters and factors
from quantopian.pipeline.filters import QTradableStocksUS, Q1500US, Q500US, StaticAssets

# import any datasets we need
from quantopian.pipeline.data import USEquityPricing

# import numpy and pandas just because they rock
import numpy as np
import pandas as pd

def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    # Make our pipeline and attach to the algo
    # Used to get our universe of stocks and close prices
    attach_pipeline(make_stock_pipeline(context), 'my_stocks')
    
    context.yesterdays_data = None
    context.minuteCounter = 0 
    

def make_stock_pipeline(context):
    """
    Get a list of stocks.
    This will be the universe to check for gainers and losers
    """

    # Set universe 
    stock_universe = QTradableStocksUS()
    
    pipe = Pipeline(
        columns={'yesterdays_close': USEquityPricing.close.latest},
        screen=stock_universe
    )
    return pipe
            
def before_trading_start(context, data):
    # Fetch the pipeline data
    pipe_data = pipeline_output('my_stocks')
    
    # Get the universe of stocks as a list
    context.stocks = pipe_data.index.tolist()
    
    # Get yesterdays close prices as a series
    context.yesterdays_close = pipe_data.yesterdays_close
    

def handle_data(context, data):
    context.minuteCounter += 1
 
    # counter
    if context.minuteCounter >= 10:
        context.minuteCounter = 0
    
        current_price = (data.current(assets=context.stocks, fields='price'))
        
        # Calculate the percent gain since close yesterday for all the stocks
        todays_gain_since_yesterday_close = ((current_price / context.yesterdays_close) - 1) * 100.0
    
        # Get the top 5 gainers and losers for the day
        top_gainers = todays_gain_since_yesterday_close.nlargest(5)
        top_losers = todays_gain_since_yesterday_close.nsmallest(5)
    
        # Here we log the data but could also do more logic
        log.info('top gainers {} top losers {}'.format(top_gainers, top_losers))
There was a runtime error.
Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Thank you Dan! Your numbers look much closer to what I was hoping for. The advice about "Don't ever store price or volume data to use in subsequent days" is good. I will remember that.

The pipeline column you set up

 pipe = Pipeline(  
        columns={'yesterdays_close': USEquityPricing.close.latest},  
        screen=stock_universe  
    )  

Makes a lot of sense. Seems obvious now that you point it out, but was counter intuitive looking at it yesterday. I was over thinking what the "latest" closing price of an equity meant in context.