Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Help - stuck with a line for the whole day

So down below is the part I am having problem with.

if cur_price > add_price and add_unit < 4:  

this line returns an error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). There was a runtime error on line 87.

The part looks like this:

        elif sec in context.portfolio.positions: #buy 1 unit if sec price up 0.5N  
            last_price =(recordme[recordme['symbol'] == sec]['last_buy_price']).astype(float)  
            add_price =(last_price + 0.5 * ATR).astype(float)  
            add_unit = (recordme[recordme['symbol'] == sec]['add_time']).astype(float)

            if cur_price > add_price and add_unit < 4: #4 - limit unit  
                unit = account_size*0.01 / ATR  
                order(sec,unit)  

log.info() come back with

2015-01-29 16:30 rebalance:84 INFO Series([], Name: add_time, dtype: int64)  
2015-01-29 16:30 rebalance:85 INFO Series([], Name: last_buy_price, dtype: int64)  

I think the problem is with :
add_price =(last_price + 0.5 * ATR).astype(float)
add_unit = (recordme[recordme['symbol'] == sec]['add_time']).astype(float)
that it didn't return a number but a Series. But isn't float a number already once I am using .astype? but it still a Series from the log.info().
Been scratching my head in this, did all kinds of search but didn't really find a solution.

3 responses
"""
This is a template algorithm on Quantopian for you to adapt and fill in.  
"""
import quantopian.algorithm as algo  
from quantopian.pipeline.data.builtin import USEquityPricing  
from quantopian.pipeline.filters import QTradableStocksUS  
import math  
from quantopian.pipeline import CustomFactor, Pipeline  
import talib  
import pandas as pd  
from quantopian.pipeline.filters.morningstar import Q1500US, Q500US  
from quantopian.algorithm import attach_pipeline, pipeline_output

def initialize(context):  
    context.securities = [  
        sid(24),  
        ]  
    # Rebalance every day, 1 hour after market open.  
    algo.schedule_function(  
        rebalance,  
        algo.date_rules.every_day(),  
        algo.time_rules.market_open(hours=1),  
    )

    context.trade_percent = 0.01  
    context.atrlength = 20  
    context.portfolio_size = context.portfolio.cash + context.portfolio.positions_value  
    my_pipe = make_pipeline()  
    attach_pipeline(my_pipe, 'my_pipeline')


class Cal_unit(CustomFactor):  
    def compute(self, today, assets, out, portfolio_value, trade_percent, ATR):  
        out[:] = math.floor(portfolio_value * trade_percent/ATR)  
def make_pipeline():  
    base_universe = Q500US()  
    return Pipeline(  
              columns={  
              },screen=(base_universe)  
          )  
def before_trading_start(context, data):  
    pipe_results = algo.pipeline_output('my_pipeline')  
    record(leverage=context.account.leverage)  
def rebalance(context, data):  
    global recordme  
    hist = data.history(context.securities, ['high', 'low', 'close'], 200, '1d')  
    account_size = context.portfolio_size  
    recordme = pd.DataFrame({'symbol':[],'add_time':[],'last_buy_price':[]})  
    for sec in context.securities:  
        #close = data.history(sec,'close',200,'1d')  
        #high = data.history(sec,'high',200,'1d')  
        #low = data.history(sec,'low',200,'1d')

        ATR = talib.ATR(hist['high'][sec],  
                        hist['low'][sec],  
                        hist['close'][sec], timeperiod=context.atrlength)[-1]

        cur_price = data.current(sec, 'price')  
        position = context.portfolio.positions[sec].amount  
        #log.info(position)  
        if len(recordme)!=0:  
               recordme= recordme[recordme['symbol']!=sec] 


        unit = account_size*0.01 / ATR  
        #unit = Cal_unit(inputs = [account_size, 0.01, ATR], window_length = 1)  
        if cur_price > hist['high'][sec][-20:-1].max() and position is 0:  
            order(sec, unit)  
            recordme = recordme.append(pd.DataFrame({'symbol':[sec],'add_time':[1],'last_buy_price':[cur_price]}))  
            continue  
        elif sec in context.portfolio.positions: #buy 1 unit if sec price up 0.5N  
            last_price =(recordme[recordme['symbol'] == sec]['last_buy_price']).astype(float)  
            add_price =(last_price + 0.5 * ATR).astype(float)  
            add_unit = (recordme[recordme['symbol'] == sec]['add_time']).astype(float)

            if cur_price > add_price and add_unit < 4: #4 - limit unit  
                unit = account_size*0.01 / ATR  
                order(sec,unit)  
                #update sec info into recordme  
                recordme.loc[recordme['symbol']== sec,'add_time']=recordme[recordme['symbol']== sec]['add_time']+1  
                recordme.loc[recordme['symbol']== sec,'last_buy_price']=cur_price  
            elif cur_price< hist['low'][sec][-int(20/2):-1].min() or cur_price < (last_price - 2*ATR):  
                order_target_percent(sec,0)  
                #After sell the stock, empty recordme  
                recordme = recordme[recordme['symbol']!=sec]  

Its the Turtal Trading strategy that it will add 0.5N when price go up, but add no more than 4 times

The error is on line 76

            if cur_price > add_price and add_unit < 4: #4 - limit unit  

The issue is that add_price is a series. Python doesn't understand how to compare a real value with a series. You should specify which location in the series you want to reference.

I would also suggest not saving prices from day to day. If there is a stock split (which happens quite often) the prices will not be comparable.

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.

Thank you for responding, like you have suggested, I did

if cur_price > add_price[-1] and add_unit[-1] < 4:  

but It came back with error
IndexError: index out of bounds There was a runtime error on line 86. I thinks its because it start with an empty Series that [-1] won't make sense to Python.
So I've added

            if last_price.empty == False or add_price.empty == False or add_unit.empty == False:

but the following code would never execute this way.
Any further advise?