Brenda the reason you are seeing that leverage is because in your code you ask it to buy 100% of you portfolio value for each stock.
Iterate over the list of stocks
for stock in context.stocks:
current_position = context.portfolio.positions[stock].amount
# Close position for the stock when the MACD signal is negative and we own shares.
if signal[stock] < 0.1 and current_position > 0:
# Enter the position for the stock when the MACD signal is positive and
# our portfolio shares are 0.
elif signal[stock] > 0.05 and current_position == 0:
order_target_percent(stock, 1 - current_position)
So you have 3 securities in
context.stocks and you iterate through each of them, your buy logic is what is messing you up. To enter a position you require that the signal is greater than 0.05 and you currently have 0 positions, are as your code says
current_position == 0. Well when you place the order you choose a portfolio weighting of
1 - current_position well that statement will always evaluate to 1, since by definition the only way to get to the order statement is by having a current position of 0. Consequently you will always place an order for 100% of your portfolio value for each stock.
I've attached a backtest where I changed it to just hold an equal weighting of each security, log the leverage, and use
schedule_function which is a more robust way to trade than with custom date logic as you have it now.
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.