A Practical Guide to Building and Simulating Quantitative Trading Models for Stocks
This article provides a comprehensive guide to developing, simulating, and deploying quantitative stock trading models. It covers setting research boundaries, defining unambiguous mathematical rules, ensuring data reliability, separating strategy logic from execution, modeling transaction costs, evaluating performance with multi-dimensional metrics, and conducting out-of-sample testing to mitigate overfitting risks.
- Clarify the Objective: What Problems Should a Quant Model Solve?
A quantitative stock trading model translates investment hypotheses into computable rules and generates trading orders combined with capital management and trading constraints. It can use simple technical indicators or include statistical predictions and multi-factor scoring. Regardless of its complexity, it must answer three questions: why to trade, when to trade, and how much to trade.
Building a model generally involves three phases: rule definition, program implementation, and historical backtesting. However, engineering practice requires adding data validation, risk control, paper trading, and execution monitoring. Otherwise, a model might perform well on historical charts but fail in a real trading environment.
Three validation methods should be distinguished:
- Historical Backtesting: Reconstructs the trading process using past data according to predefined rules.
- Paper Trading: Generates signals on continuously arriving market data to validate system behavior using a simulated account or virtual ledger.
- Live Trading: Submits real orders through an authorized account, bearing execution and capital risks.
Backtesting is for researching strategies, paper trading validates the engineering pipeline, and live trading exposes full execution risks. These three cannot substitute for one another.
- Define Trading Boundaries to Prevent Endless Scope Expansion
Before writing a strategy, form a “research boundary statement.” It should at least include trading instruments, stock universe, data frequency, holding period, capital size, operating method, and evaluation benchmark.
For developers building a system for the first time, it is suitable to start with a single market, daily-frequency data, and fewer strategy rules. Minute-level or higher-frequency models need to handle more complex issues like time synchronization, missing market data, execution sequencing, and system latency, making them unsuitable as a default starting point.
The stock universe must also be clear. For example, are you researching a set of stocks that met certain conditions at a specific historical point in time, or a fixed group of securities? If you directly use currently traded stocks to backtest years of history, you might omit delisted or removed securities, creating survivorship bias.
Additionally, capital size affects the model’s executability. The same set of signals might be easy to execute with small capital but limited by market liquidity and market impact costs with larger capital. Therefore, the strategy should not only output buy/sell directions but also target positions and execution capacity constraints.
- Translate Trading Ideas into Unambiguous Mathematical Rules
Take a short-term moving average crossing above a long-term moving average as an example. You should not just write “buy on crossover, sell on crossunder,” but also specify the price field, signal confirmation time, order time, and position rules.
Let the closing price used for signal calculation on the t-th trading day be Pₜ, and the n-day simple moving average be:
MAₙ(t) = Sum of prices over the last n valid trading days / n
A short-term moving average crossing above a long-term moving average is determined when the following conditions are met simultaneously:
MA₅(t) > MA₂₀(t)
MA₅(t−1) ≤ MA₂₀(t−1)
If the signal is generated after the daily closing data is confirmed, you cannot assume immediate execution at the same closing price. A clearer daily-frequency research setup is: calculate signals after the close, and attempt execution on the next trading day according to predefined execution rules.
Complete rules should also include:
- Buy conditions: Whether the position is empty, whether the security is tradable, and whether capital constraints are met.
- Sell conditions: Reversal signal, risk-based exit, or preset holding period.
- Position rules: Target weight for each instrument, maximum total portfolio position limit.
- Repeated signal handling: Whether to ignore additional buy signals when a position already exists.
- Insufficient data handling: No trading signals generated during the indicator warm-up period.
- Execution failure handling: Cancel, postpone, or retain the trading intention.
These rules should be determined before observing backtest results and saved as traceable configurations to avoid constantly modifying the interpretation to improve results.
- Build a Reliable Data Foundation
Backtest quality depends primarily on data quality, not the length of the strategy code. Basic data usually includes security identifiers, trading dates, open, high, low, close prices, volume, and turnover. Depending on strategy needs, you might also require trading calendars, trading halt status, price limits, corporate actions, and historical sample membership information.
Data governance should focus on the following issues:
Time Consistency
Financial data should enter the model according to its actual public release time, not be used in advance based on the reporting period. Other information with a release date must also record “when it was knowable,” otherwise, look-ahead bias will occur.Price Basis Consistency
Corporate actions like dividends and stock splits can cause changes in price series. Indicator calculation can use appropriately adjusted price series, but execution simulation must retain the actual trading price at the corresponding time and handle cash and position quantity changes. Adjusted historical prices cannot be directly used as actual execution prices.Missing Values and Trading Halt Handling
A trading halt does not mean a zero price, nor should the previous day’s price simply be used as the executable price. Position valuation can use explicit valuation rules, but order execution must follow the fact of whether the stock was actually tradable that day.Data Version Management
The same historical data might be backfilled or revised. Research records should save the data version, processing rules, strategy parameters, and program version so that results can be reproduced.Separate Strategy Logic from Trade Execution
A maintainable quantitative system can be divided into six modules:
Data Layer -> Indicator & Feature Layer -> Signal Layer -> Portfolio & Risk Control Layer -> Execution Layer -> Performance & Audit Layer
The data layer reads and validates data; the indicator layer calculates features like moving averages; the signal layer expresses trading intentions; the portfolio layer translates intentions into target positions; the execution layer handles orders and fills; the audit layer saves states, results, and exceptions.
The key to this layered design is letting the strategy express “how much it wishes to hold” rather than directly assuming “how much has been executed.” There may be discrepancies between target positions and actual holdings, and the execution module needs to continuously correct them based on capital, trading rules, and execution results.
Below is conceptual pseudocode illustrating the event sequence for a daily-frequency model, not corresponding to any actual trading API:
Initialize capital, positions, pending execution targets, and risk configurationsFor each trading day:Read daily trading status and corporate actionsUpdate position quantities and cash according to rulesCheck pending execution targets generated on the previous trading dayAttempt execution based on available cash, sellable quantity, and liquidityDeduct fees and update positionsRecord unexecuted quantities and reasonsUpdate daily market data after closeCalculate portfolio net valueIf historical data meets indicator warm-up requirements:Calculate trading signals using data up to the current dayConvert signals into target positionsGenerate pending execution targets for the next trading day after risk checksSave records of signals, orders, executions, positions, and net value
In actual implementation, partial fills, order cancellations, exception recovery, and state persistence must also be added. In particular, the same trading intention should not be repeatedly sent due to a program restart.
- Construct Execution and Transaction Cost Models
The aspect where returns are most easily overestimated in backtesting is often the execution assumptions.
If a model defaults to execution whenever a buy signal appears, it might ignore trading halts, price limits, insufficient volume, and insufficient capital. Daily-frequency data only reflects aggregated daily results and cannot accurately reconstruct all intraday order sequences, so the boundaries of execution simulation must be acknowledged.
The cost model should at least consider trading commissions, applicable taxes, and slippage. Specific rates should be set based on the applicable market, account conditions, and historical period, rather than treating a fixed number as a universal rule.
Slippage describes the difference between the assumed execution price and the actually obtainable price. A fixed percentage can be used for preliminary research, or a more detailed model can be built based on volume, volatility, and order size. Regardless of the method, you should test whether the strategy remains viable when costs increase.
The following execution constraints should also be added:
- Buying quantities meet the market’s order unit requirements.
- Selling quantities do not exceed currently sellable positions.
- Handle selling restrictions applicable to shares bought on the same day.
- Do not generate fictitious executions during trading halts.
- Do not assume execution when hitting price limits.
- Single order size is constrained by available liquidity.
- Reduce or reject orders when cash is insufficient according to preset rules.
Commissions and price changes may prevent the target position from being reached precisely, so position calculations should leave a reasonable margin and reconcile the ledger after execution.
- Evaluate Strategy with Multi-Dimensional Metrics, Not Just Returns
Cumulative returns can describe the outcome but cannot explain whether the result is stable or the risk is acceptable. It is recommended to observe the following metrics simultaneously:
Annualized Return
Converts returns over a specific time interval into an annualized scale. However, annualizing a short sample easily amplifies randomness and must be understood in conjunction with the sample length.Maximum Drawdown
Measures the largest decline in net value from a historical peak to a subsequent trough. It reflects the pressure on capital but cannot guarantee that larger losses won’t occur in the future.Volatility and Risk-Adjusted Returns
Used to analyze the volatility of returns and the return obtained per unit of risk taken. Data frequency should be unified during calculation, and related assumptions should be clear.Turnover Rate and Transaction Cost Ratio
High-turnover strategies are more sensitive to transaction fees and execution quality. High gross returns but weak net returns after fees usually mean the strategy lacks sufficient implementation capacity.Relative Benchmark Performance
Compare the strategy with a benchmark matching its investment scope and observe differences across various market phases. A profitable strategy does not necessarily imply excess capability; it might just be taking on market upside risk.
You should also analyze the longest drawdown duration, position concentration, return sources, and trade distribution. The win rate can be a supplement, but a high win rate does not equal high returns: a few large losses can offset many small gains.
- Reduce Overfitting Risk Through Out-of-Sample Testing
Constantly tuning parameters until the historical return curve is beautiful enough is a common trap in quantitative research. The more parameters and attempts, the easier it is to find a combination that only fits historical noise.
Divide the research period chronologically. Build the strategy using earlier data, then test it with subsequent data that did not participate in parameter tuning. Time series are usually not suitable for random shuffling because it may break the sequential relationship of information.
Furthermore, rolling testing can be applied: use only the data from a past period to determine parameters, apply them to the subsequent test window, and then gradually move forward.
Robustness checks can also include:
- Slightly varying the moving average periods to see if performance suddenly fails.
- Increasing commissions and slippage to test cost sensitivity.
- Delaying execution to see if the advantage relies on extremely ideal execution timing.
- Checking performance separately in uptrend, downtrend, and sideways markets.
- Checking whether returns are concentrated in a few securities or a few trades.
The final test interval should not be repeatedly viewed and used to modify the strategy; otherwise, it will gradually become training data.
- Prioritize Engineering Constraints When Choosing Deployment Methods
A quantitative system can be deployed on local devices or remote computing environments. The choice should be based on strategy requirements, not the deployment location itself.
Local running facilitates accessing proprietary data, debugging programs, and managing dependencies, but requires maintaining power, network, processes, and system updates. Remote running facilitates continuous operation and centralized monitoring but requires confirming operating permissions, dependency limits, data access methods, and failure recovery mechanisms.
Regardless of the deployment method, the following should be configured:
- Process survival and market data update checks.
- Alerts for order failures, state desyncs, and abnormal positions.
- Periodic reconciliation of accounts and positions.
- Log retention and sensitive information protection.
- Strategy stop, order cancellation, and manual takeover mechanisms.
- State recovery and duplicate submission protection after restarts.
When multiple strategies share an account, capital and order conflicts should be managed centrally to prevent each strategy from treating the account’s total cash as its own available capital.
- Acceptance Checklist: From Backtesting to Paper Trading
After completing historical backtesting, conduct continuous paper trading first, focusing on verifying whether the program works according to the rules, rather than just observing simulated returns.
Acceptance items include: whether market data arrives timely, whether indicator calculations are consistent, whether signals are duplicated, whether capital and positions are balanced, whether exceptions can be detected, whether the state is correct after a restart, and whether unexecuted orders are handled reasonably.
Before connecting to live trading, confirm account permissions, applicable trading rules, automated trading requirements, and API authorization conditions. Specific qualification and usage restrictions depend on the brokerage and applicable regulations; there is no universally applicable uniform capital threshold.
A credible quantitative stock trading model should have clear rules, reliable data, reasonable execution assumptions, and traceable operating records. Building a simple model that can be explained and reproduced first, and then gradually increasing strategy complexity, is usually more valuable than directly pursuing high-return curves. Historical backtesting and paper trading only provide validation evidence and do not guarantee future returns.
