ml-quant-trading / Worked example · 简体中文
Why masking before rolling matters
Suppose a research policy excludes the day 3 close from factor inputs because it sits at an explicitly supplied price limit. The close is still an observed price. This example compares two ways to calculate a three-day moving average on day 4.
| Day | Observed close | Factor input allowed? | Reason |
|---|---|---|---|
| 1 | 100 | Not in day 4 window | Sets the prior close |
| 2 | 100 | Yes | Inside supplied limits |
| 3 | 110 | No | Illustrative limit-up close |
| 4 | 102 | Yes | Inside supplied limits |
Day 4 calculation
Calculate first and exclude only the day 3 output: (100 + 110 + 102) / 3 = 104. The day 4 factor still contains the excluded day 3 input.
Exclude the day 3 input before rolling: (100 + 102) / 2 = 101. The window uses its two remaining valid observations.
The project's ts_mean divides by the count of valid observations in each window. apply_limit_mask passes the exclusion mask into factor computation, so later windows do not read the excluded close.
Check it with the code
Run this example in Colab to inspect the factor-input mask and both values without a local setup. The notebook records the repository commit and runtime used.
From a source checkout, install the package and run the four-day reproduction script. It uses only the four values above and explicit illustrative price limits; it does not download market data.
python -m pip install --upgrade pip
python -m pip install -e .
python scripts/reproduce_mask_first_example.py
The script prints the factor-input mask and both day 4 values, and exits with an assertion error if they differ from 104 and 101.
What this does and does not establish
This is an arithmetic illustration of a chosen factor-input policy. It does not show that the observed close was erroneous, that a particular order could or could not fill, or that the resulting factor is profitable. Historical return labels and held-position P&L use their own validity rules. See the mask contract, paper, and research card for the full scope.