Back to Community
Historical Data Help


I'm new to using the Quantopian libraries, but I wanted to thank the development team and the users that has created such a rich experience. There are some great resources available, and I hope to be able to eventually contribute to the community as well. ^_^

I'm trying to make a simple strategy that looks at yesterday's price and compares it to the day before. If yesterday's close is 8% less than the day before it, place a market order to buy the security and sell it at either a 8% profit or 4% loss - whichever comes first.

So, if Tuesday the stock declines 8% from it's Monday close, place a market buy order to create a position. If the stock falls 4% afterwards, or rises 8%, close the position

I think that I've managed to get the buy condition correct, but I was wondering how I should create the exit strategy.

Thanks in advance for your help and understanding!

def initialize(context):  
    context.etf = symbol('TVIX')

def handle_data(context, data):  
    price_history = history(bar_count=2, frequency='1d', field='price')  
    for s in data:  
        yesterday_close = price_history[s][-2]  
        current_price = price_history[s][-1]  
        if current_price >= yesterday_close * 1.08:  
            order_target(s, 1)  
        if context.portfolio.pnl >= 1.08 or context.portfolio.pnl <= .92:  
            order_target(context.etf, 0)  
4 responses

Hi Andrew,

Welcome to Quantopian! It's great to start like a simple strategy like this to help you grow more comfortable with the platform. With the code you posted, it looks like you're on the right track implementing the strategy you described. A couple of comments/suggestions:

  • It looks like your logic for entering position is backwards, your condition checks if the current price is greater than or equal to 8% of yesterday's close price. To follow the logic you described, you will need to get history(bar_count=3, frequency='1d', field='price') and then you will want to look at price_history[s][-3] and price_history[s][-2] in your for loop.

  • For your exit strategy, since you have two exit conditions, you will want to store your entry price in a variable in context. For example, you can set context.enter_prices = {} in the initialize(context) function, and then when you enter a position in the for loop, you can store your enter price by doing something like context.enter_price[s] = current_price. Then, every day, you can compare the current price to the entry price for each stock in data and exit when one of your conditions is met.

Does this help?


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.

Thanks Jamie!

That was very helpful.

I was able to correct the oversight on the buy condition, and I've included my code below. The only issue is that I would like to place a market buy order to execute at market open the next day, and I would like the sell order to use minute data instead of daily close prices. I cleaned up and commented my current algorithm, if you would be so kind as to take a look!

Here's what I'm trying to model:

  • TVIX closes at $10.00 on Monday.
  • TVIX drops to $9.20 on Tuesday - an 8% drop.
  • A market buy order is placed to execute Wednesday morning at market open.
  • On the next Monday, the stock goes up 8% at any point during the day and a sell order is sent to the market.

Thanks again in advance!

def initialize(context):  
    context.etf = symbol('TVIX')        # Select security.  
    context.entry_price = 0             # Initialize variable.  
def handle_data(context, data):  
    # Create objects to contain open and close prices.  
    close_history = history(bar_count=3, frequency='1d', field='close_price')  
    open_history = history(bar_count=3, frequency='1d', field='open_price')  
    for s in data:  
        # Checks to see if yesterday's close is 8% less than the close of  
        # the previous day.  
        twodaysago = close_history[s][-3]  
        yesterday = close_history[s][-2]  
        # Place a buy order if the condition is met.  
        if yesterday <= (twodaysago * .92):  
            context.entry_price = open_history[s][-1]  
            print context.entry_price  
            order_target(s, 1)  
    # Create a variable to see the current price.  
    current_price = data[context.etf].price  
    if current_price >= context.entry_price * 1.08:  
        # Take profit of 8%.  
        order_target(context.etf, 0)  
    if current_price <= context.entry_price * .92:  
        # Stop loss of 4%.  
        order_target(context.etf, 0)  

In order to implement the logic you explained to me, you will need to run your backtest in minute mode (a better simulation anyway) and you will want to use the schedule_function() method to call a function every day that you define to check for buy orders. You will then have to handle your checks for selling separately in handle_data(), which will get called every minute in minute mode.

In the end, you will have 3 functions:

  • initialize(context)
  • handle_data(context, data) -- where sell orders will be handled
  • check_buy(context, data) -- called by schedule function, the name is arbitrary!

There are some good examples of schedule function in the help docs (follow the link above) and if that's not enough, there are more throughout the forums.

Thanks Jamie!

I was hesitant to use minute mode unnecessarily, because I imagine the server load for backtesting is much greater, but I will work on recreating this strategy with the schedule function!

Thanks for pointing me in the right direction!

  • Andrew