Optimal Trading Rule

Find the optimal trading rule of every asset: the profit-taking and stop-loss levels with the highest Sharpe ratio for a long position.

The log price follows the mean-reverting Ornstein-Uhlenbeck process fitted to it, with the Monte Carlo method of López de Prado (2018, chapter 13).

The process is fitted to the log prices by a regression of each on the one before it, which gives how persistent the price is (Phi), the level it reverts to (the Long-Run Mean) and the size of its shocks (Sigma). Thousands of paths of that process are then simulated from the last price, and every pair of a profit-taking and a stop-loss level on a mesh, in units of Sigma, is tried on the same paths: a position is closed once the price rises above the profit-taking level, falls below the stop-loss level or has been held for the maximum holding period. The rule with the highest Sharpe ratio of the gains is the optimal one. A price far below its long-run mean (a positive Forecast) favours a wide profit-taking level, one above it a tight stop-loss; for a price that hardly reverts (Phi close to 1, a long Half-Life) the Sharpe ratios are close to zero and the rule matters little.

The formula is as follows, with \(p_{t}\) the log of the column (Adj Close by default):

\[p_{t} = c + \phi \cdot p_{t-1} + \sigma \cdot \epsilon_{t} \;\text{by OLS},\;\; \text{with}\; \sigma \;\text{the standard deviation of the residuals} \;(n - 2 \;\text{degrees of freedom}),\;\; \text{Long-Run Mean} = \frac{c}{1 - \phi},\;\; \text{Half-Life} = - \frac{\ln(2)}{\ln(\phi)}\;\;\text{and}\;\; \text{Forecast} = \frac{\text{Long-Run Mean} - p_{0}}{\sigma},\;\; \text{with } p_{0} \text{ the last log price}\] \[y_{t} = \frac{p_{t} - p_{0}}{\sigma} = (1 - \phi) \cdot \text{Forecast} + \phi \cdot y_{t-1} + \epsilon_{t},\;\; y_{0} = 0,\;\; \epsilon_{t} \sim N(0,\; 1),\;\; \text{for simulations paths (10,000 by default) of at most maximum\_holding\_period steps (100 by default)}\] \[\text{For every profit-taking } \bar{\pi} \text{ and stop-loss } \pi \text{̲} \text{ in \{} h \text{, 2h, ..., maximum\_threshold\}},\;\; h = \frac{\text{maximum\_threshold}}{\text{grid\_size}} \;(0.5 \;\text{to 10 by default}) \;\text{:} \;\text{the gain of a path is}\; y_{t} \;\text{at the first}\; t \;\text{with}\; y_{t} > \bar{\pi} \;\text{or}\; y_{t} < - \text{pi̲},\;\; \text{or at the maximum holding period}\] \[\text{Sharpe Ratio} = \frac{\text{mean}}{\text{standard deviation} \;(\text{ddof} = 1) \;\text{of the gains}};\;\; \text{the rule with the highest is reported with its Mean and Standard Deviation (in } \sigma \text{) and Average Holding Period}\]

Also known as: optimal trading rule, OTR, profit-taking and stop-loss, Ornstein-Uhlenbeck trading rule, mean reversion trading rule, synthetic backtest.

Example · PFE, KO · 2021 to 2025

Install the Finance Toolkit with pip install financetoolkit -U, then call get_optimal_trading_rule:

from financetoolkit import Toolkit

toolkit = Toolkit(
    ["PFE", "KO"],
    api_key="FINANCIAL_MODELING_PREP_KEY",
    start_date="2021-01-01",
    end_date="2025-12-31",
)

toolkit.econometrics.get_optimal_trading_rule()

Or, with the Finance Toolkit MCP set up, ask an AI assistant such as Claude or ChatGPT:

Which profit-taking and stop-loss levels gave the highest Sharpe ratio for a long position in Pfizer and Coca-Cola, with their prices from 2021 to 2025 modelled as mean-reverting?

Which returns:

Using Your Own Data

get_optimal_trading_rule runs on any data, not only prices: ratios, economic indicators, yield curves or your own dataset. Pass a DataFrame, a Series or a dictionary of them to Econometrics as data, with the dates in the rows or the columns, and set changes to how its changes are calculated: "percentage", "log", "difference" for rates and ratios, or None when the data are changes already. For example, for the monthly unemployment rates of the United States and Germany:

from financetoolkit import Economics, Econometrics

economics = Economics(start_date="2000-01-01")

unemployment = economics.get_unemployment_rate(
    countries=["United States", "Germany"], period="monthly"
)

econometrics = Econometrics(data=unemployment, changes="difference")

econometrics.get_optimal_trading_rule()

Parameters

get_optimal_trading_rule accepts the following parameters.

ParameterTypeDescriptionExample
periodstrThe data frequency (daily, weekly, monthly, quarterly, or yearly). Defaults to “daily”."weekly"
columnstrThe price column. Defaults to “Adj Close”."Return"
maximum_thresholdfloatThe widest profit-taking and stop-loss level, in units of Sigma. Defaults to 10.0.10.0
grid_sizeintThe number of levels on each side of the mesh, so the mesh has grid_size² rules. Defaults to 20.20
maximum_holding_periodintThe most periods a position is held. Defaults to 100.100
simulationsintThe number of simulated paths. Defaults to 10000.1000
seedintThe seed of the simulation. Defaults to 0.42
log_pricesboolWhether to fit the process to the log prices. Pass False for a series that can be zero or negative, such as a spread. Defaults to True.True
gridboolWhether to return every rule of the mesh instead of the optimal one. Defaults to False.False
include_benchmarkboolWhether to include “Benchmark” among the assets. Defaults to False.True
roundingint | NoneThe number of decimals to round the results to. Defaults to None.2
show_columnsstr | list[str] | NoneThe columns to keep, a name or a list of names, matched on every column level, or the rows when no column has those names (such as the line items of a financial statement). Names that do not exist are logged, and when none exist the result is returned in full. Defaults to None, which keeps every column.None, which keeps every column

References

  • Paper López de Prado, M. (2018). “Advances in Financial Machine Learning.” Wiley, chapter 13, “Backtesting on Synthetic Data”.
  • Library Referenced against RiskLabAI’s ou_rule_metrics
  • Library Shares similar logic as RiskLabAI’s fit_ornstein_uhlenbeck
  • Library Shares similar logic as RiskLabAI’s optimal_ou_trading_rule
Share