Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
PIPELINE - Stocks up 4% and greater

Please help me.

I am trying to get this pipeline to filter stocks that are up 4% or more for the day and are priced between $1 - $10.

I am having trouble. Been trying to program this for days! Please does someone have the answer?

Code is below.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import SimpleMovingAverage

def initialize(context):

# Create and attach an empty Pipeline.  
pipe = Pipeline()  
pipe = attach_pipeline(pipe, name='my_pipeline')

# Construct Factors.  
change_4 = returns(inputs=[USEquityPricing.close], window_length=2)

# Construct a Filter.  
prices_under_1 = (price < 1)  
prices_over_10 = (price > 10)

# Register outputs.  
pipe.add(change_4, 'change_4')

# Remove rows for which the Filter returns False.  
pipe.set_screen(prices_under_1)  
pipe.set_screen(prices_over_10)  

def before_trading_start(context, data):
# Access results using the name passed to attach_pipeline.
results = pipeline_output('my_pipeline')
print results.head(5)

# Define a universe with the results of a Pipeline.  
# Take the first 25 assets by gain above 4%.  
update_universe(results.sort('change_4').index[:25])  

def handle_data(cdontext, data):
pass

12 responses

Hi Dante,

It looks like there may be a couple of issues here. first, you'll want to create a custom factor to calculate your recent returns like the one in this sample algo. As well, your filters seem to be looking at stocks with price < 1 and price > 10 when instead they should be looking for price > 1 and < 10. These should then be put together in one set_screen function like this:

pipe.set_screen(prices_over_1 & prices_under_10)  

Finally, it makes it much easier to help if you attach your backtest to your post, instead of just copying and pasting the code in the text box! You can do this by using the "Attach" button in the top right of your post.

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.

I can't backtest because the algo is only 1/4 written. Thank you so much for the help! Though I am not going for returns. I need some more help on this. I want the pipeline to include stocks that are up 4% or more since the previous day. Any suggestions on how to do this?

Again, thank you so much! Nobody else has helped me. Very grateful!

Here is what I changed. I am unsure of how to modify the pct_change to show me stocks that are up by 4%. Any thoughts?

\\\\\\\\\\\\\\\\\\\\\\\\

from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import SimpleMovingAverage

def initialize(context):

# Create and attach an empty Pipeline.  
pipe = Pipeline()  
pipe = attach_pipeline(pipe, name='my_pipeline')

# Construct Factors.  
change_4 = pct_change(periods=1, fill_method='pad', limit=None, freq=None, **kwargs)  

# Construct a Filter.  
prices_under_1 = (price > 1)  
prices_over_10 = (price < 10)

# Register outputs.  
pipe.add(change_4, 'change_4')

# Remove rows for which the Filter returns False.  
pipe.set_screen(prices_over_1 & prices_under_10)  

def before_trading_start(context, data):
# Access results using the name passed to attach_pipeline.
results = pipeline_output('my_pipeline')
print results.head(5)

# Define a universe with the results of a Pipeline.  
# Take the first 25 assets by gain above 4%.  
update_universe(results.sort('change_4').index[:25])  

def handle_data(cdontext, data):
pass

Dante,

If you look at the % returns since yesterday, this will be the same as % change. Take a look at this example and you'll see that it's just comparing a previous price to yesterday's price.

Jamie,

So returns doesn't mean stocks you own or have purchased, but rather the change in % of a stocks price over a period of trading days???

Thanks,
Dante

I have added in what I think is correct. But I am not sure. Coding is tough. I am a professional trader, but a novice coder. :c

import pandas as pd
import math
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import SimpleMovingAverage

Custom factors are defined as a class object, outside of initialize or handle data.

RecentReturns will calculate the returns for a security over the n-most recent days.

class RecentReturns(CustomFactor):

# Set the default list of inputs as well as the default window_length.  
# Default values are used if the optional parameters are not specified.  
inputs = [USEquityPricing.close]  
window_length = 10  

# Computes the returns over the last n days where n = window_length.  
# Any calculation can be performed here and is applied to all stocks  
# in the universe.  
def compute(self, today, assets, out, close):  
    out[:] = (close[-1] - close[0]) / close[0]

def initialize(context):

# Define the other variables  
context.returns_lookback = 1  

# Create and attach an empty Pipeline.  
pipe = Pipeline()  
pipe = attach_pipeline(pipe, name='momo')

# Construct Factors.  
change_4 = RecentReturns(window_length=context.returns_lookback)  

# Construct a Filter.  
prices_under_1 = (price > 1)  
prices_over_10 = (price < 10)

# Register outputs.  
pipe.add(change_4, 'change_4')

# Remove rows for which the Filter returns False.  
pipe.set_screen(prices_over_1 & prices_under_10)  

def before_trading_start(context, data):
# Access results using the name passed to attach_pipeline.
results = pipeline_output('momo')
print results.head(5)

# Define a universe with the results of a Pipeline.  
# Take the first 25 assets by gain above 4%.  
update_universe(results.sort('change_4').index[:50])  

def handle_data(cdontext, data):
pass

also i am getting an error that price isn't defined. I found it in even properties on the API. how do i import it?

I am on my last warning of failed imports before my account is suspended :C

here is the most up to date code.

import pandas as pd
import math
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline import CustomFactor
from quantopian.pipeline.data.builtin import USEquityPricing

Custom factors are defined as a class object, outside of initialize or handle data.

RecentReturns will calculate the returns for a security over the n-most recent days.

class RecentReturns(CustomFactor):

# Set the default list of inputs as well as the default window_length.  
# Default values are used if the optional parameters are not specified.  
inputs = [USEquityPricing.close]  
window_length = 10  

# Computes the returns over the last n days where n = window_length.  
# Any calculation can be performed here and is applied to all stocks  
# in the universe.  
def compute(self, today, assets, out, close):  
    out[:] = (close[-1] - close[0]) / close[0]

def initialize(context):

# Define the other variables  
context.returns_lookback = 1  

# Create and attach an empty Pipeline.  
pipe = Pipeline()  
pipe = attach_pipeline(pipe, name='momo')

# Construct Factors.  
change_4 = RecentReturns(window_length=context.returns_lookback)  

# Construct a Filter.  
prices_over_1 = (price > 1)  
prices_under_10 = (price < 10)

# Register outputs.  
pipe.add(change_4, 'change_4')

# Remove rows for which the Filter returns False.  
pipe.set_screen(prices_over_1 & prices_under_10)  

def before_trading_start(context, data):
# Access results using the name passed to attach_pipeline.
results = pipeline_output('momo')
print results.head(5)

# Define a universe with the results of a Pipeline.  
# Take the first 25 assets by gain above 4%.  
update_universe(results.sort('change_4').index[:50])  

def handle_data(cdontext, data):
pass

Hi Dante,

It's much too difficult to follow this code. Even if a backtest errors out, you should be able to click "Full Backtest", and then share your partial backtest in the forums when it errors out. Please give it a shot!

Jamie,

I cannot backtest. I have tried. It does nothing. There is no handle data

Dante,

Can you just add:

def handle_data(context, data):  
    pass  

to your code?

Regarding the 'price is undefined' error, you need to make sure to set the price variable to something before using it in a filter!

i fixed everything now! thanks for the help!