Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Buying Worst Performing positions in my portfolio

I am new to Quantopian and coding/algorithm trading. I am trying to make an algorithm that will recognize and purchase the worst performing stocks in my portfolio (preferably one share at at time) if the uninvested cash balance it enough to buy 1 share of the worst performing stock.

For example, my portfolio has 250 different stocks. If i have 100 shares of AAPL and it is the worst performing stock with -10.1% return followed by VZ at -10.05% return, the algorithm should be able to recognize AAPL as the worst performing position and buy 1 share of AAPL. If, after the purchase, the new AAPL return is now higher than -10.05% (let's say -10.02) and now VZ is the worst performer at -10.05%, then the Algorithm should now buy 1 share of VZ. But if the new AAPL return is still the worst performing in the portfolio( let's say the new return after the purchase of 1 additional share is -10.07% vs the 2nd worst performer VZ at -10.05%), then the algorithm should place another order for 1 additional share of AAPL and repeat this step until AAPL is no longer the worst performer. Then the Algorithm would now keep buying the new worst performer until it is no longer the worst performing.

Note: The algorithm should NEVER sell all stocks. Just buying the worst performer.

The logic is for the algorithm to always focus on buying the worst performing stock in the entire portfolio al long as my portfolio has enough cash to buy one stock of the worst performing position.

Anyone got an idea how to code this?