Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Cash added during backtest

Hi,

I am trying to make an algorithm that buys 1 share of apple each day until I run out of cash. When I backtest my algorithm, it seems that cash is being added to my position allowing me to continue to trade. Is there anyway to stop trading when cash available is less than the price of the stock?

Thanks,

Steve

4 responses

This list of stocks can have just one element if you prefer ...

def initialize(context):  
    context.stocks = [ sid(24), sid(39840) ]  
    schedule_function(opens, date_rules.every_day(), time_rules.market_open())

def opens(context, data):  
    cash = context.portfolio.cash

    for s in context.stocks:  
        prc = data.current(s, 'price')  
        log.info('{}  {}  vs  {} cash   shares {}'.format( s.symbol,  
             prc, int(cash), context.portfolio.positions[s].amount ))  
        if cash > prc:  
            order(s, 1)  
            cash -= prc  
2010-06-30 06:31 opens:11 INFO AAPL  256.87  vs  10400 cash   shares 0  
2010-06-30 06:31 opens:11 INFO TSLA  25.58  vs  10143 cash   shares 0  
2010-07-01 06:31 opens:11 INFO AAPL  254.02  vs  10115 cash   shares 1  
2010-07-01 06:31 opens:11 INFO TSLA  24.97  vs  9861 cash   shares 1  
2010-07-02 06:31 opens:11 INFO AAPL  249.61  vs  9835 cash   shares 2  
2010-07-02 06:31 opens:11 INFO TSLA  22.19  vs  9585 cash   shares 2  
2010-07-06 06:31 opens:11 INFO AAPL  251.2  vs  9562 cash   shares 3  
2010-07-06 06:31 opens:11 INFO TSLA  19.9  vs  9311 cash   shares 3  
2010-07-07 06:31 opens:11 INFO AAPL  249.84  vs  9289 cash   shares 4  
2010-07-07 06:31 opens:11 INFO TSLA  16.3  vs  9039 cash   shares 4  
etc  

Hi,

Thanks so much for your answer. However, when I run the full backtest, I still see that cash is being added which starts the trading up again. You can see here that cash jumps from $119 on 2017-5-17 to $160 on 2017-5-18 (using the code provided), allowing trading to start again. I am new to this, so please excuse me if this is an easy answer.
Thanks,

Steve

The Q backtester is smart enough to add dividends to your account as cash. In this case, AAPL paid a $.63/share on 5/18/2017. Your algorithm quickly used that cash then to buy more AAPL.

Dan,

Thank you so much!!!!!!!!!

Steve