Trading Backtesting function


Backtesting is the process of applying a trading strategy or analytical method to historical data to see how accurately the strategy or method would have predicted actual results.

Included now into the T library: https://github.com/al3xandr3/T

Basic Usage

Lets use the S&P500 index as the stock to invest in

>>> sp500 = t.get_quotes_close(['^GSPC'], date_from = '2018-06-14')
>>> sp500 = sp500.reset_index()

Lets say we have 1000 to invest

>>> capital = 1000

What are the gain/losses if we had invested 1000 in S&P in 2018-06-14 ?

>>> bulk1 = pd.DataFrame()
>>> bulk1["date"] = sp500["date"]
>>> bulk1["order_size"] = 0
>>> bulk1.loc[t.where(bulk1, "date", datetime.strptime('2018-06-14', '%Y-%m-%d'), op.eq).index[0], "order_size"] = 1000
>>> out1 = t.backtest_strategy(sp500, bulk1, capital)
>>> out1["transactions"]
date ^GSPC order_size pct_change invested_start_day invested_end_day account_cash_start_day account_cash_end_day net_worth nb
0 2018-06-14 2782.489990 1000 NaN 0.000000 1000.000000 1000 0 1000.000000
1 2018-06-15 2779.659912 0 -0.001017 998.982897 998.982897 0 0 998.982897
2 2018-06-18 2773.750000 0 -0.002126 996.858932 996.858932 0 0 996.858932
3 2018-06-19 2762.590088 0 -0.004023 992.848167 992.848167 0 0 992.848167
4 2018-06-20 2767.320068 0 0.001712 994.548077 994.548077 0 0 994.548077
... ... ... ... ... ... ... ... ... ... ...
495 2020-06-03 3122.870117 0 0.013649 1122.329327 1122.329327 0 0 1122.329327
496 2020-06-04 3112.350098 0 -0.003369 1118.548533 1118.548533 0 0 1118.548533
497 2020-06-05 3193.929932 0 0.026212 1147.867537 1147.867537 0 0 1147.867537
498 2020-06-08 3232.389893 0 0.012042 1161.689675 1161.689675 0 0 1161.689675
499 2020-06-09 3207.179932 0 -0.007799 1152.629459 1152.629459 0 0 1152.629459



And the overall percent gain/loss

>>> out1["lift"]

0.153

about 15% gain, i.e. +152 gain from the original 1000 investment.



Project updates hosted in github: https://github.com/al3xandr3/T


Updated: