strategy

Trading System Optimization

This strategy uses the global optimizer to find the best suitable parameters for technical indicators.

You can clone and edit this example there (tab Examples).


Backesting a trading system amounts to perform a simulation of the trading rules on historical data. All trading rules depend to some extent on a set of parameters. These parameters can be the lookback periods used for defining technical indicators or the hyperparameters of a complex machine learning model.

It is very important to study the parameter dependence of the key statistical indicators, for example the Sharpe ratio. A parameter choice which maximizes the value of the Sharpe ratio when the simulation is performed on the past data is a source of backtest overfitting and leads to poor performance on live data.

In this template we provide a tool for studying the parameter dependence of the statistical indicators used for assessing the quality of a trading system.

We recommend optimizing your strategy in a separate notebook because a parametric scan is a time consuming task.

Alternatively it is possible to mark the cells which perform scans using the #DEBUG# tag. When you submit your notebook, the backtesting engine which performs the evaluation on the Quantiacs server will skip these cells.

You can use the optimizer also in your local environment on your machine. Here you can use more workers and take advantage of parallelization to speed up the grid scan process.

In [1]:
%%javascript
IPython.OutputArea.prototype._should_scroll = function(lines) { return false; }
// disable widget scrolling
In [2]:
import qnt.data as qndata
import qnt.ta as qnta
import qnt.output as qnout
import qnt.stats as qns
import qnt.log as qnlog
import qnt.optimizer as qnop
import qnt.backtester as qnbt

import xarray as xr

For defining the strategy we use a single-pass implementation where all data are accessed at once. This implementation is very fast and will speed up the parametric scan.

You should make sure that your strategy is not implicitly forward looking before submission, see how to prevent forward looking.

The strategy is going long only when the rate of change in the last roc_period trading days (in this case 10) of the linear-weighted moving average over the last wma_period trading days (in this case 20) is positive.

In [3]:
def single_pass_strategy(data, wma_period=20, roc_period=10):
    wma = qnta.lwma(data.sel(field='close'), wma_period)
    sroc = qnta.roc(wma, roc_period)
    weights = xr.where(sroc > 0, 1, 0)
    weights = weights / len(data.asset) # normalize weights so that sum=1, fully invested
    with qnlog.Settings(info=False, err=False): # suppress log messages
        weights = qnout.clean(weights, data) # check for problems
    return weights

Let us first check the performance of the strategy with the chosen parameters:

In [4]:
#DEBUG#
# evaluator will remove all cells with this tag before evaluation

data = qndata.futures.load_data(min_date='2004-01-01') # indicators need warmup, so prepend data
single_pass_output = single_pass_strategy(data)
single_pass_stat = qns.calc_stat(data, single_pass_output.sel(time=slice('2006-01-01', None)))
display(single_pass_stat.to_pandas().tail())
100% (35526272 of 35526272) |############| Elapsed Time: 0:00:00 Time:  0:00:00
field equity relative_return volatility underwater max_drawdown sharpe_ratio mean_return bias instruments avg_turnover avg_holding_time
time
2024-04-10 1.218077 -0.000650 0.040471 -0.056453 -0.166718 0.268101 0.010850 1.0 71.0 0.040734 26.270992
2024-04-11 1.215649 -0.001993 0.040470 -0.058333 -0.166718 0.265329 0.010738 1.0 71.0 0.040739 26.295952
2024-04-12 1.219063 0.002808 0.040471 -0.055689 -0.166718 0.269097 0.010891 1.0 71.0 0.040749 26.301302
2024-04-15 1.219734 0.000550 0.040467 -0.055169 -0.166718 0.269819 0.010919 1.0 71.0 0.040750 26.309063
2024-04-16 1.217032 -0.002215 0.040466 -0.057262 -0.166718 0.266739 0.010794 1.0 71.0 0.040746 26.448483

A parametric scan over pre-defined ranges of wma_period and roc_period can be performed with the Quantiacs optimizer function:

In [5]:
#DEBUG#
# evaluator will remove all cells with this tag before evaluation

data = qndata.futures.load_data(min_date='2004-01-01') # indicators need warmup, so prepend data

result = qnop.optimize_strategy(
    data,
    single_pass_strategy,
    qnop.full_range_args_generator(
        wma_period=range(10, 150, 5), # min, max, step
        roc_period=range(5, 100, 5)   # min, max, step
    ),
    workers=1 # you can set more workers when you run this code on your local PC to speed it up
)

qnop.build_plot(result) # interactive chart in the notebook

print("---")
print("Best iteration:")
display(result['best_iteration']) # as a reference, display the iteration with the highest Sharpe ratio
100% (532 of 532) |######################| Elapsed Time: 0:06:28 Time:  0:06:28
---
Best iteration:
{'args': {'wma_period': 15, 'roc_period': 80},
 'result': {'equity': 1.4667385801324209,
  'relative_return': -0.0035888642875436805,
  'volatility': 0.04018513510997636,
  'underwater': -0.05281389961630856,
  'max_drawdown': -0.11402281047194351,
  'sharpe_ratio': 0.5265039185144236,
  'mean_return': 0.021157631101434093,
  'bias': 1.0,
  'instruments': 71.0,
  'avg_turnover': 0.016887580487030623,
  'avg_holding_time': 75.06047516198815},
 'weight': 0.5265039185144236,
 'exception': None}

The arguments for the iteration with the highest Sharpe ratio can be later defined manually or calling result['best_iteration']['args'] for the final strategy. Note that cells with the tag #DEBUG# are disabled.

The final multi-pass call backtest for the optimized strategy is very simple, and it amounts to calling the last iteration of the single-pass implementation with the desired parameters:

In [6]:
best_args = dict(wma_period=20, roc_period=80) # highest Sharpe ratio iteration (not recommended, overfitting!)

def best_strategy(data):
    return single_pass_strategy(data, **best_args).isel(time=-1)

weights = qnbt.backtest(
    competition_type="futures",
    lookback_period=2 * 365,
    start_date='2006-01-01',
    strategy=best_strategy,
    analyze=True,
    build_plots=True
)
Run last pass...
Load data...
Run strategy...
Load data for cleanup...
Output cleaning...
fix uniq
Normalization...
Output cleaning is complete.
Write result...
Write output: /root/fractions.nc.gz
---
Run first pass...
Load data...
100% (16521772 of 16521772) |############| Elapsed Time: 0:00:00 Time:  0:00:00
Run strategy...
---
Load full data...
---
Run iterations...

100% (4775 of 4775) |####################| Elapsed Time: 0:02:25 Time:  0:02:25
Merge outputs...
Load data for cleanup and analysis...
Output cleaning...
fix uniq
ffill if the current price is None...
Check missed dates...
Ok.
Normalization...
Output cleaning is complete.
Write result...
Write output: /root/fractions.nc.gz
---
Analyze results...
Check...
Check missed dates...
Ok.
Check the sharpe ratio...
Period: 2006-01-01 - 2024-04-16
Sharpe Ratio = 0.5223632193832376
ERROR! The Sharpe Ratio is too low. 0.5223632193832376 < 1
Improve the strategy and make sure that the in-sample Sharpe Ratio more than 1.
Check correlation.
WARNING! Can't calculate correlation.
Correlation check failed.
---
Align...
Calc global stats...
---
Calc stats per asset...
Build plots...
---
Output:
asset F_AD F_AE F_AG F_AH F_AX F_BC F_BG F_BO F_BP F_C
time
2024-04-03 0.0 0.014085 0.014085 0.000000 0.014085 0.014085 0.014085 0.0 0.014085 0.0
2024-04-04 0.0 0.014085 0.014085 0.000000 0.014085 0.014085 0.014085 0.0 0.014085 0.0
2024-04-05 0.0 0.014085 0.014085 0.000000 0.014085 0.014085 0.014085 0.0 0.014085 0.0
2024-04-08 0.0 0.014085 0.014085 0.014085 0.014085 0.014085 0.014085 0.0 0.014085 0.0
2024-04-09 0.0 0.014085 0.014085 0.014085 0.014085 0.014085 0.014085 0.0 0.014085 0.0
2024-04-10 0.0 0.014085 0.014085 0.014085 0.014085 0.014085 0.014085 0.0 0.000000 0.0
2024-04-11 0.0 0.014085 0.014085 0.014085 0.014085 0.014085 0.014085 0.0 0.000000 0.0
2024-04-12 0.0 0.014085 0.014085 0.014085 0.014085 0.014085 0.014085 0.0 0.000000 0.0
2024-04-15 0.0 0.014085 0.014085 0.014085 0.014085 0.014085 0.014085 0.0 0.000000 0.0
2024-04-16 0.0 0.014085 0.014085 0.014085 0.014085 0.014085 0.014085 0.0 0.000000 0.0
Stats:
field equity relative_return volatility underwater max_drawdown sharpe_ratio mean_return bias instruments avg_turnover avg_holding_time
time
2024-04-03 1.473769 0.001505 0.040619 -0.054593 -0.117503 0.528453 0.021465 1.0 71.0 0.015323 85.495964
2024-04-04 1.474606 0.000568 0.040615 -0.054056 -0.117503 0.529177 0.021493 1.0 71.0 0.015321 85.495964
2024-04-05 1.476108 0.001019 0.040612 -0.053092 -0.117503 0.530514 0.021545 1.0 71.0 0.015322 85.496218
2024-04-08 1.476476 0.000250 0.040607 -0.052856 -0.117503 0.530801 0.021554 1.0 71.0 0.015332 85.493703
2024-04-09 1.476576 0.000067 0.040603 -0.052792 -0.117503 0.530836 0.021554 1.0 71.0 0.015338 85.511078
2024-04-10 1.473858 -0.001840 0.040601 -0.054536 -0.117503 0.528212 0.021446 1.0 71.0 0.015339 85.511827
2024-04-11 1.472475 -0.000939 0.040598 -0.055423 -0.117503 0.526854 0.021389 1.0 71.0 0.015351 85.517570
2024-04-12 1.473867 0.000945 0.040594 -0.054530 -0.117503 0.528091 0.021437 1.0 71.0 0.015355 85.543129
2024-04-15 1.473276 -0.000401 0.040590 -0.054909 -0.117503 0.527481 0.021410 1.0 71.0 0.015353 85.543129
2024-04-16 1.467990 -0.003588 0.040595 -0.058300 -0.117503 0.522363 0.021205 1.0 71.0 0.015350 85.349558
---

The full code for the optimized strategy

import qnt.data as qndata
import qnt.ta as qnta
import qnt.log as qnlog
import qnt.backtester as qnbt
import qnt.output as qnout

import xarray as xr


best_args = dict(wma_period=20, roc_period=80) # highest Sharpe ratio iteration (not recommended, overfit!)


def single_pass_strategy(data, wma_period=20, roc_period=10):
    wma = qnta.lwma(data.sel(field='close'), wma_period)
    sroc = qnta.roc(wma, roc_period)
    weights = xr.where(sroc > 0, 1, 0)
    weights = weights / len(data.asset)
    with qnlog.Settings(info=False, err=False): # suppress log messages
        weights = qnout.clean(weights, data) # check for problems
    return weights


def best_strategy(data):
    return single_pass_strategy(data, **best_args).isel(time=-1)


weights = qnbt.backtest(
    competition_type="futures",
    lookback_period=2 * 365,
    start_date='2006-01-01',
    strategy=best_strategy,
    analyze=True,
    build_plots=True
)

Preventing forward-looking

You can use this code snippet for checking forward looking. A large difference in the Sharpe ratios is a sign of forward looking for the single-pass implementation used for the parametric scan.

#DEBUG#
# evaluator will remove all cells with this tag before evaluation

# single pass
data = qndata.futures.load_data(min_date='2004-01-01') # warmup period for indicators, prepend data
single_pass_output = single_pass_strategy(data)
single_pass_stat = qns.calc_stat(data, single_pass_output.sel(time=slice('2006-01-01', None)))

# multi pass
multi_pass_output = qnbt.backtest(
    competition_type="futures",
    lookback_period=2*365,
    start_date='2006-01-01',
    strategy=single_pass_strategy,
    analyze=False,
)
multi_pass_stat = qns.calc_stat(data, multi_pass_output.sel(time=slice('2006-01-01', None)))

print('''
---
Compare multi-pass and single pass performance to be sure that there is no forward looking. Small differences can arise because of numerical accuracy issues and differences in the treatment of missing values.
---
''')

print("Single-pass result:")
display(single_pass_stat.to_pandas().tail())

print("Multi-pass result:")
display(multi_pass_stat.to_pandas().tail())