Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Runtime Exception of TypeError due to assignment order?

I have the following test code:

def handle_data(context, data):  
    for stock in context.stocks:  
        h = history(bar_count=1,frequency="1d",field="high")  
        l = history(bar_count=1,frequency="1d",field="low")  
        # Check if we are already in a position.  
        pos = context.portfolio.positions[stock]  
        # Handle open positions  
        if pos.amount != 0:  
            # Check stop-loss value and close if breached.  
            if data[stock].price/pos.cost_basis-1 > context.max_loss:  
                order_target(stock,0)  
                context.open_trade_dt[stock.sid] = None  
            # Check if we have passed the max duration to take profit/loss.  
            if data[stock].datetime - context.open_trade_dt[stock.sid] > dt.timedelta(hours=context.max_duration):  
                order_target(stock,0)  
                context.open_trade_dt[stock.sid] = None  
        # Or see if we meet Long trade criteria  
        elif data[stock].price > h[stock][0]:  
            order(stock,int(context.max_pos_value/data[stock].price))  
            context.open_trade_dt[stock.sid] = dt.datetime.now()  
        elif data[stock].price < l[stock][0]:  
            order(stock,-int(context.max_pos_value/data[stock].price))  
            context.open_trade_dt[stock.sid] = dt.datetime.now()  

The Build is failing with:

2   Error   Runtime exception: TypeError: unsupported operand type(s) for -: 'Timestamp' and 'NoneType'  

But the assignment is clearly made when the code actually opens a trade. Any reason for this?

3 responses

Hi Makoto,

It looks like you've figured out that this error is telling you that you're attempting to subtract a Timestamp from None, which is causing a TypeError. It's hard to say without seeing the rest of your algo, but one thing I notice is that you have:

if data[stock].price/pos.cost_basis-1 > context.max_loss:  
    order_target(stock,0)  
    context.open_trade_dt[stock.sid] = None  
# Check if we have passed the max duration to take profit/loss.  
if data[stock].datetime - context.open_trade_dt[stock.sid] > dt.timedelta(hours=context.max_duration):  
    order_target(stock,0)  
    context.open_trade_dt[stock.sid] = None  

If your first condition is true, then you're setting context.open_trade_dt[stock.sid] to None. Then in the next if-statement, you're doing data[stock].datetime - context.open_trade_dt[stock.sid]. The right hand side of that subtraction is the value you've just set to None, which means you'll be subtracting a Timestamp from None, resulting in the error you're seeing. My guess is that you want your second if-statement to be an elif instead.

Hope that helps,
-Scott

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.

Yes, this should have been an elif, which fixed the issue!

Hooray!