I wrote this algorithm inspired by Joshua Kennon's excellent blog post on S&P 500 index investing. The results, supported by quite a bit of academic literature, are quite good. I tested versions of this algorithm multiple times over multiple different starting time periods and I have not yet found a run where it doesn't outperform the S&P 500 index and numerous runs where it outperforms the S&P by a good margin.
Notes: Because of limitations of how Quantopian manages dividends (it doesn't tell you where they are coming from, just deposits them in portfolio.cash), I am assuming reinvestments into SPY. In real life, I would plan to just set up all of the stocks on a DRIP dividend reinvestment program, which is free of commissions. In addition, I am ignoring transaction costs because this is a buy-and-hold-forever algorithm and it shouldn't affect the answer very much with a sufficiently large portfolio.