Hi Max,
I took a look at your code and here is what I found. One problem is you're nesting your stop-loss loops inside of your ordering loops.
Here's how your algo runs: Handle_data gets called once per minute. After 10AM, if there are no positions, it will place an order to buy the stock according to your MA logic. However the order is filled in the next minute bar and is subject to the slippage model. Since the order is placed in one bar and filled in the next bar, code on line 60 never gets triggered. It will never be true that
if number_of_shares == 0
then if (context.portfolio.positions[stock].amount != 0):
I updated your code and have attached the backtest. The logic now says:
- Enter position at or after 10AM according to the MA logic
- Once we have a position, set a stop-loss at today's low. If triggered, this will exit the entire position
- If have a profit that equals or exceeds $400, sell half of the portfolio
To note, it's more robust to use order_target_percent, which is more flexible with changes in your portfolio cash. Let me know if this makes sense and if its the behavior that you expected.
Cheers,
Alisa
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.