Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to buy a stock at a price lower than the price previously sold at

I'm currently working off of an algorithm that sells a stock at a price higher than what it was purchased at.
The algorithm stops after it has sold the stock.
I'm hoping to extend the code to make it start buying stocks again at a price that was lower than what it was sold at and to repeat the cycle.
Can someone help me with the lines of code after line 40?

3 responses

Thanks a lot! That's basically what I was looking for.
I am still having some trouble with this code.
I changed line 3 to:

stocks, profit_ratio, buy_ratio = symbols('VTI'), 1.05, 0.97

However, the algorithm seems to stop trading after a buy order on 2012-05-21 on a backtest with the time range 01/04/2011 to 12/14/2018. Would you know why it does not submit a sell order since the price of VTI goes above 105% the buy order price?

I really appreciate the help!

Thanks!

The algorithm above sends a sell order when the price rises above the profit target(if relative_prices >= profit_ratio) and sends a buy order when the price falls below the buy target (if relative_buy <= buy_ratio).
So if you specified buy ratio 0.97 or 3% below the last sold price and that may will not happen.

Thank you very much for your response and the new code.
I tried it out and I feel that the initial code is closer to what I intended the algorithm to do.
I shared the backtest result in another post to better display my problem.
https://www.quantopian.com/posts/algorithm-not-selling-stocks-at-target-price

This algorithm seemed to just run 3-4 transactions and stopped.
In the code, I had the profit_ratio set to 1.05
The final purchase was on 2012-05-21 for 160 shares of VTI at $66.71.
When the price of VTI later exceeded 70.0455, a sell order was not executed. Isn't that relative_prices>=profit ratio?