Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How can I get the average daily return of worst 20% performance stocks?

If I have 100 stocks, I sort them based on their daily return, and I want to compute the average return of the lowest ranked stocks' average return, what can I do?

2 responses

He,

If I understand what you are asking, you are just looking for:

Daily and Ranked Return Factors

# If you want to look at returns over a longer period, lengthen the window  
daily_return = Returns(window_length=2)  
daily_rank = daily_return.rank(mask=universe)  
pipe.add(daily_rank, 'daily_rank')  

...

def before_trading_start(context, data):

# Later you can pick the 100 worst returning stocks to then short (presumably)  
context.output = pipeline_output('my pipe')  
context.short_list = context.output.sort_values(['daily_rank'], ascending=False).iloc[-100:]  

...

def rebalance(context,data):

# Equally weight the short list  
short_weight = context.short_leverage / float(len(context.short_list))  
for short_stock in context.short_list.index:  
    order_target_percent(short_stock, short_weight)  

# Exit any positions that are no longer in the short list  
for stock in context.portfolio.positions.iterkeys():  
    if stock not in context.short_list.index:  
        order_target(stock, 0)  

This also may help:

from quantopian.pipeline import Pipeline, factors, filters, classifiers  
from quantopian.algorithm import attach_pipeline, pipeline_output  
# ---------------------------------------------------------  
STK_SET, LB, UB, LEV = filters.Q500US(), 0, 20, 1.0  
# ---------------------------------------------------------  
def initialize(context):  
    daily_return = factors.DailyReturns(mask = STK_SET)  
    low_pct = daily_return.percentile_between(LB, UB)  
    attach_pipeline(Pipeline(columns={'daily_return': daily_return}, screen = low_pct), 'pipe')

def before_trading_start(context, data):  
    output = pipeline_output('pipe')  
    average_daily_return_low_pct = output.daily_return.mean()

    record(average_daily_return_low_pct = average_daily_return_low_pct, zero = 0.0)