Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Keeping algorithm from adding in additional cash for purchases?

I'm very new to algorithmic trading, coming from a software dev background, so I apologize in advance if I'm missing something obvious. I want to run a simulation where I don't add any additional cash other than what I started with, as that is more realistic to what I would be doing in real life. For example, I'd like to start with 1,000 and that is it, I use that to buy the initial stock and then can only use what I make from selling that stock to buy more stock. My algorithm below doesn't perform this way, however, as it keeps pumping in additional cash. I am trying to simulate a situation, just for testing, where, if the moving average of stockA goes ahead of the previous moving average of stockB, I sell all of stockB and use the money from that to buy as much of stockA as I can. Thanks for any advice.

3 responses

Dan responded on the other thread, and had a question on it so posting his response here:

For your main question, what you want to do is to add cash management
to your algorithm. You need to test if your order is goign to drive
you into negative cash, and not execute the order if it would!

Looking over the API reference, I don't see much that would help with this, so I'm assuming this is something I need to write the code for (which is fine), or is there a method that can help with this?

Your best bet is to search through forums for good examples that have margin constraints or some some sort of re-balancing going on. This one comes to mind. The back tester will let you borrow as much $ as you want, it's on you to make sure it doesn't. I added a line to record your cash and positions, it should help you see where the money goes.

moving_average = ta.MA(timeperiod=30)

def initialize(context):  
    context.stocks = [sid(40107),sid(12652)]  
    context.voo = sid(40107)  
    context.dltr = sid(12652)  
    context.prev_voo_ma = 0  
    context.prev_dltr_ma = 0  
    context.portfolio.starting_cash = 1000

def handle_data(context, data):  
    record(cash=context.portfolio.cash, positions=context.portfolio.positions_value)  
    moving_average_data = moving_average(data)  
    voo_ma = moving_average_data[context.voo]  
    dltr_ma = moving_average_data[context.dltr]  
    log.info("prev_ma: " + str(context.prev_voo_ma))  
    log.info("cur_ma: " + str(voo_ma))  
    if context.portfolio.cash > 0:  
        if voo_ma  context.prev_voo_dltr:  
            order_percent(context.voo, -1)  
            order_percent(context.dltr, 1)  
        else:  
            order_percent(context.dltr, -1)  
            order_percent(context.voo, 1)  
    context.prev_voo_ma = voo_ma  
    context.prev_dltr_ma = dltr_ma  

Thanks David, I appreciate the helpful example!