Fast and Reliable Stockmarket Backtesting. Pandas Tips #1

Any backtest of stockmarket trading or investment strategy isn`t complete without calculating stock`s momentums. So the task is to do such calculations quickly and, of course, correctly.

Usually, the shorter programming code — the higher speed of its execution and much better precision of its results. So, we will use:

  • 4 lines of code to calculate =>
  • Monthly (21 trade days) momentums =>
  • For more than 6500 stocks =>
  • For each trading day =>
  • Of the last 20 years.

For these calculations I’m using historical stock prices, which are concatenated in one pandas DataFrame:

The dataset contains ~18M of rows and 3 columns (the choice of the price type to calculate moments depends on your preferences). To get calculated monthly momentums for each of 5183 trading days and 6655 stocks, instead of using “for” loops, I suggest to use pandas pivot_table() function:

which produces to us such resulting table:

The time of code execution is about 25 seconds (depends on your hardware), which is not bad for creating ~18M moments. Finally, let’s check the exactness of these calculations. For example, the adjusted close of Apple stock on 2/2/2000 was $3.049 and the same close on 1/3/2020 (21 trading day before) was $3.454, and so the monthly moment for 2/2/2000 was 3.049/3.454=0.8827, this value we see in the above table. Checking some additional rows can confirm the correctness of code calculations.

If you know the faster way to get the same calculated output, please, write your comments.

--

--