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):
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:
| Item | PFE | KO |
|---|---|---|
| Phi | 0.9977 | 0.9969 |
| Half-Life | 303.5680 | 222.5130 |
| Sigma | 0.0158 | 0.0100 |
| Long-Run Mean | 3.3005 | 4.1336 |
| Forecast | 9.5111 | -9.4572 |
| Profit-Taking | 6.0000 | 0.5000 |
| Stop-Loss | 10.0000 | 0.5000 |
| Mean | 1.3971 | -0.0498 |
| Standard Deviation | 7.0180 | 1.2679 |
| Sharpe Ratio | 0.1991 | -0.0393 |
| Average Holding Period | 55.5542 | 1.5936 |
11 rows
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.
| Parameter | Type | Description | Example |
|---|---|---|---|
period | str | The data frequency (daily, weekly, monthly, quarterly, or yearly). Defaults to “daily”. | "weekly" |
column | str | The price column. Defaults to “Adj Close”. | "Return" |
maximum_threshold | float | The widest profit-taking and stop-loss level, in units of Sigma. Defaults to 10.0. | 10.0 |
grid_size | int | The number of levels on each side of the mesh, so the mesh has grid_size² rules. Defaults to 20. | 20 |
maximum_holding_period | int | The most periods a position is held. Defaults to 100. | 100 |
simulations | int | The number of simulated paths. Defaults to 10000. | 1000 |
seed | int | The seed of the simulation. Defaults to 0. | 42 |
log_prices | bool | Whether 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 |
grid | bool | Whether to return every rule of the mesh instead of the optimal one. Defaults to False. | False |
include_benchmark | bool | Whether to include “Benchmark” among the assets. Defaults to False. | True |
rounding | int | None | The number of decimals to round the results to. Defaults to None. | 2 |
show_columns | str | list[str] | None | The 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