Skip to content

Get Rich Bot Problem


You've developed an algorithmic stock trading bot to strike it rich 🤑, but you want to backtest it before putting it into production. You have price data on 10 stocks, each tracked at 8 regular time intervals.

import numpy as np

rng = np.random.default_rng(1234)
prices = [rng.normal(rng.lognormal(3, 1), size=8).round(2) for i in range(10)]
prices = np.vstack(prices)

print(prices) # (1)!
# [[  4.1    4.78   4.19   4.9    6.95   2.56   4.99   2.37]
#  [ 27.81  29.65  27.46  28.84  27.06  26.17  28.76  30.06]
#  [ 32.79  34.06  34.56  34.98  32.63  34.49  34.14  33.76]
#  [ 19.67  19.73  21.68  20.61  19.87  17.86  19.48  19.85]
#  [  4.24   6.39   5.32   3.87   4.23   5.27   6.68   4.06]
#  [ 98.02  96.79  99.02  99.94  98.28  99.15  98.19  98.49]
#  [107.11 105.01 109.01 105.19 107.06 106.71 106.13 106.41]
#  [ 17.89  16.34  15.88  17.53  18.79  16.91  18.75  16.96]
#  [ 96.28  95.84  96.26  94.48  95.42  93.75  93.54  96.24]
#  [ 18.31  17.43  16.53  20.2   18.68  17.48  17.33  18.96]]
  1. Element (i,j) represents the price of stock i at time j.

For each stock, your algorithm suggests the best time to buy the stock and the best time to sell the stock.

trade_idxs = [np.sort(rng.choice(8, size=2, replace=False)) for i in range(10)]
trade_idxs = np.vstack(trade_idxs)

print(trade_idxs) # (1)!
# [[0 1]
#  [3 6]
#  [2 4]
#  [1 5]
#  [0 3]
#  [2 7]
#  [2 3]
#  [1 3]
#  [3 6]
#  [1 4]]
  1. Element (i,0) represents the time to buy stock i. Element (i,1) represents the time to sell stock i.

trade_idxs identifies the index of the buy price and sell price for each stock. So, the holding periods look like this.

| trade_idxs |     0 |     1 |     2 |      3 |     4 |     5 |     6 |     7 |
|:-----------|------:|------:|------:|-------:|------:|------:|------:|------:|
| [0 1]      |  4.1  |  4.78 | ----- |  ----- | ----- | ----- | ----- | ----- |
| [3 6]      | ----- | ----- | ----- |  28.84 | 27.06 | 26.17 | 28.76 | ----- |
| [2 4]      | ----- | ----- | 34.56 |  34.98 | 32.63 | ----- | ----- | ----- |
| [1 5]      | ----- | 19.73 | 21.68 |  20.61 | 19.87 | 17.86 | ----- | ----- |
| [0 3]      |  4.24 |  6.39 |  5.32 |   3.87 | ----- | ----- | ----- | ----- |
| [2 7]      | ----- | ----- | 99.02 |  99.94 | 98.28 | 99.15 | 98.19 | 98.49 |
| [2 3]      | ----- | ----- | 09.01 | 105.19 | ----- | ----- | ----- | ----- |
| [1 3]      | ----- | 16.34 | 15.88 |  17.53 | ----- | ----- | ----- | ----- |
| [3 6]      | ----- | ----- | ----- |  94.48 | 95.42 | 93.75 | 93.54 | ----- |
| [1 4]      | ----- | 17.43 | 16.53 |  20.2  | 18.68 | ----- | ----- | ----- |

Given prices and trade_idxs, calculate the average price of each holding period.


Try with Google Colab