Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Why does the system make an order with a negative cash balance?

I am new here and trying to learn from people in this community. I found a problem about order_target_percent(stock, 1.0), which I can't fix myself. So I ask it here.

When you use this method for the order, say you set total cash amount $1,000,000, it will generate a negative cash balance sometimes for the buy orders. The problem is that I only want to buy the maximum shares with the cash available instead of using margin to buy more shares. Since the method means you can buy shares with 100% of your available cash, it should not use 110% or other percentages over 100%.

There is an example from Quanopian help document under "API Documentation -- TA-Lib methods -- MACD".
https://www.quantopian.com/help#macd

You can see negative balances of -$4479, -$2726.6, and so on if you clone the algorithm and add the following line:
record(Cash = context.portfolio.cash)

Here is the full algorithm (I deleted all comments as the post can't display them correctly):

==========================================================================================

import talib
import numpy as np
import pandas as pd

def initialize(context):
context.stocks = symbols('MMM', 'SPY', 'GOOG_L', 'PG', 'DIA')
context.pct_per_stock = 1.0 / len(context.stocks)

schedule_function(rebalance, date_rules.every_day(), time_rules.market_open())

def rebalance(context, data):

prices = data.history(context.stocks, 'price', 40, '1d')  

macds = {}  

for stock in context.stocks:  
    macd_raw, signal, hist = talib.MACD(prices[stock], fastperiod=12,  
                                    slowperiod=26, signalperiod=9)  
    macd = macd_raw[-1] - signal[-1]  
    macds[stock] = macd  

    current_position = context.portfolio.positions[stock].amount  

    if macd < 0 and current_position > 0 and data.can_trade(stock):  
        order_target(stock, 0)  

    elif macd > 0 and current_position == 0 and data.can_trade(stock):  
        order_target_percent(stock, context.pct_per_stock)  



record(Cash = context.portfolio.cash) 

==========================================================================================

Thank you very much!