Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Why is my algo taking a trade every minute?

Total noob, so be kind.

Why is my algo taking a trade every minute, even when I told it to only take a trade if position == 0?

import talib  
import numpy as np  
import pandas as pd

# Setup our variables  
def initialize(context):  
    context.stock = sid(--masked--)  
    for minute in range(0, 390, 1):  
        schedule_function(trade, date_rules.every_day())  
    #close out positions end of day  
    schedule_function(close_orders, date_rules.every_day(), time_rules.market_close(hours=0, minutes=5))  
def trade(context, data):  
    current_position = context.portfolio.positions[context.stock].amount  
    price = data.current(context.stock, 'price')  
    # Load historical data for the stocks  
    #looking for 4 days worth of data  
    prices = data.history(context.stock, 'price', 1440, '1m')  
    upper, middle, lower = talib.BBANDS(  
        prices,  
        timeperiod=20,  
        # number of non-biased standard deviations from the mean  
        nbdevup=2,  
        nbdevdn=-2,  
        # Moving average type: simple moving average here  
        matype=0)  
    # If price is below the recent lower band and we have  
    # no long positions then go long  
    if price <= lower[-1] and current_position == 0 and data.can_trade(context.stock):  
        order_target(context.stock, 1000)  
        log.info('long trade taken at' + str(price))  

    # If price is above the recent upper band and we have  
    # no short positions then go short  
    elif price >= upper[-1] and current_position == 0 and data.can_trade(context.stock):  
        order_target(context.stock, -1000)  
        log.info('short trade taken at' + str(price))  
3 responses

Probably has something to do with the fact that you scheduled your order function within the for loop on the 2nd line of your initialze() function.

Hope that helps,
Josh

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.

Yeah but it should only take a trade if current_position = 0... thats the problem. Once a trade is taken, it shouldnt take another one unless that is met. Thoughts?

Hi Casey,

Without seeing the backtest + log output, it's a little bit difficult to help debug, but I think the problem is that the algorithm is over-ordering. The for loop around the schedule_function call is essentially calling trade at market open 390 times. I get the sense that you were looking to run the function once per minute, in which case you could specify a minute offset equal to the minute variable in your for loop. Of course, if you're running the function every minute, you're probably better off just running it in handle_data.

To help debug, you might want to log the value of current_position before placing an order. I'd also recommend reading the lesson on order management from the Getting Started Tutorial.

Let me know if this helps.

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.