hitherto 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hitherto-0.2.0/LICENSE +21 -0
- hitherto-0.2.0/PKG-INFO +47 -0
- hitherto-0.2.0/README.md +490 -0
- hitherto-0.2.0/WRITEUP.md +19 -0
- hitherto-0.2.0/hitherto/__init__.py +39 -0
- hitherto-0.2.0/hitherto/__main__.py +96 -0
- hitherto-0.2.0/hitherto/api.py +144 -0
- hitherto-0.2.0/hitherto/checker.py +720 -0
- hitherto-0.2.0/hitherto/emit.py +554 -0
- hitherto-0.2.0/hitherto/lexer.py +182 -0
- hitherto-0.2.0/hitherto/linter.py +1227 -0
- hitherto-0.2.0/hitherto/parser.py +340 -0
- hitherto-0.2.0/hitherto/version.py +4 -0
- hitherto-0.2.0/pyproject.toml +51 -0
- hitherto-0.2.0/runtime/hitherto.egg-info/PKG-INFO +47 -0
- hitherto-0.2.0/runtime/hitherto.egg-info/SOURCES.txt +20 -0
- hitherto-0.2.0/runtime/hitherto.egg-info/dependency_links.txt +1 -0
- hitherto-0.2.0/runtime/hitherto.egg-info/entry_points.txt +2 -0
- hitherto-0.2.0/runtime/hitherto.egg-info/requires.txt +1 -0
- hitherto-0.2.0/runtime/hitherto.egg-info/top_level.txt +2 -0
- hitherto-0.2.0/runtime/hto_rt.py +714 -0
- hitherto-0.2.0/setup.cfg +4 -0
hitherto-0.2.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tave La Rocque
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
hitherto-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hitherto
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: A typed language for time-series feature pipelines whose compiler refuses look-ahead and emits pandas
|
|
5
|
+
Author: Tave La Rocque
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/tavelarocque/hitherto
|
|
8
|
+
Project-URL: Repository, https://github.com/tavelarocque/hitherto
|
|
9
|
+
Project-URL: Issues, https://github.com/tavelarocque/hitherto/issues
|
|
10
|
+
Keywords: time-series,look-ahead,quant,backtesting,pandas,compiler,static-analysis,linter
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering
|
|
21
|
+
Classifier: Topic :: Software Development :: Compilers
|
|
22
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
23
|
+
Requires-Python: >=3.11
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Requires-Dist: pandas>=2.3
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# Hitherto in one page
|
|
30
|
+
|
|
31
|
+
**What it is.** Hitherto is a small typed language for time-series feature pipelines. Its compiler refuses any feature that reads the future, and turns everything else into ordinary Python with pandas. The compiler exists twice, once in OCaml and once in Python, and the Python one installs with `pip` and is called from a notebook in two lines.
|
|
32
|
+
|
|
33
|
+
**The problem.** Look-ahead bias is the quiet bug of backtesting. A feature at time t uses data that only existed after t, the backtest looks excellent, and the live strategy fails.
|
|
34
|
+
|
|
35
|
+
**The idea.** Every stream carries an availability lag in its type: how long after a row's timestamp its value is really known. Each operation has a rule for what it does to that lag, and anything declared a `feature` must end with a lag of zero or less. So a window centred on the present, a bar stamped with its opening time, a z-score over the whole sample and a list of "the stocks that traded today" used from the open are all compile errors, each with a line number, the cause and a fix. The typing idea is Xavier Fonseca's (arXiv 2607.04958). Three of the rules here are that paper's. The rules for shifts, centred windows, bar labelling, full-sample statistics, filling and a minimum count are additions made here, and the paper's proof does not cover them. Every rule has a written argument in `docs/`, on paper and not machine-checked.
|
|
36
|
+
|
|
37
|
+
**How it was checked.** Four ways, at every step. There are 198 expect tests. The two compilers are held to each other: on thousands of random programs they must give the same tokens, the same tree, the same types, the same error at the same place and the same generated code to the character. Three of the Python compiler's four stages were written independently of the OCaml ones. Its code generator is a port. The generated pandas is compared with a reference interpreter that uses no pandas, and then every program is run on two data sets that agree up to a cut time and differ after it, where every row the checker calls known must be identical. And 552 deliberate bugs were planted in a copy of the repository, in both compilers and in everything around them, every one of which has to be caught by some check. All are. On NASDAQ TotalView-ITCH data, three symbol-days and one day of 200 stocks, the compiled output matches a hand-written pandas version on every row, 31,363,813 of them on the day of 200 stocks.
|
|
38
|
+
|
|
39
|
+
**What a leak is worth.** On one day of Apple, a window centred on the present has a correlation of +0.566 with the price move over the next five seconds, against +0.042 for the same window trailing. Bars stamped at their start give +0.501 against +0.074. On an invented random walk the same two leaks score +0.711 and +0.441, where the arithmetic says 0.707 and 0.447. These are correlations on one day of one stock and say nothing about profit. A leak from published code was measured too. Four example strategies for the freqtrade bot, which its maintainers mark as reading the future, scale an indicator by its smallest and largest value over the whole table of prices, and one buys when a baseline of the price is near the bottom of that scale. Written in Hitherto the feature does not compile. On 200 invented days of a price nothing can predict, that rule makes +0.39% per trade at the published threshold (standard error 0.02%) where an honest scale makes -0.01%. That leak was already marked, so a second was looked for, under rules written down first: a test that changes the data after a cut, run on 355 indicators from five Python libraries. It found that finta's stochastic RSI scales RSI by its range over the whole table, which no issue or pull request of finta's mentions. On a rule from a public strategy built on it, 9% of the backtest's entries were trades the indicator, as it stood at the time, did not call for, though on invented prices the profit of the two versions could not be told apart.
|
|
40
|
+
|
|
41
|
+
**What went wrong.** The definitions of which rows a panel of stocks has were wrong six times before the tests and real data agreed. Five of the six leaked the future through which rows exist, and not through any value. Real data found things invented data had missed. And one result was withdrawn. An early measurement said a whole-day list of stocks went with future movement more strongly than an honest list. Against a fairer baseline, written down before it was run, the gap was -0.008 (-0.056 to +0.026), because a looser honest list already held 40 of the 42 stocks the hindsight list seemed to know about. The list is refused because it cannot be computed live, whatever it scores. And the measurement of the published leak failed its own check on the first run: by the average its plan had fixed, the honest rule made +0.15% per trade on a price that cannot be predicted. The plan averaged each day's mean, which divides by a count of trades that is not known until the day ends. That was a look-ahead in the evaluation, where no type reaches. Then a new version of pandas broke the promise from underneath: in 3.1 a grouped sum rounds differently when the series has a missing value anywhere, so a gap late in the day moved the last digit of an earlier bar, and the changed-future test caught it on a fresh install. The runtime now adds bars up itself.
|
|
42
|
+
|
|
43
|
+
**Limits.** The compiler checks declared lags and not reality: an input declared with the wrong lag compiles. It sees one kind of leak. Survivorship in a data file, restated data and a model fitted on its own test period all pass. "Tested" is the right word for the generated code, not "proven". The real data is three symbol-days and one day of 200 stocks, all from one exchange.
|
|
44
|
+
|
|
45
|
+
**How it was built.** With an AI coding assistant, which wrote most of the code, the tests and the walkthroughs. The checks above are the reason to believe it works.
|
|
46
|
+
|
|
47
|
+
The README has the language, the commands and the full list of limits. `docs/` has one walkthrough for each step, mistakes included.
|
hitherto-0.2.0/README.md
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
# Hitherto
|
|
2
|
+
|
|
3
|
+
[](https://github.com/tavelarocque/hitherto/actions/workflows/ci.yml)
|
|
4
|
+
|
|
5
|
+
Hitherto is a small typed language for time-series feature pipelines. Its compiler rejects any feature that reads the future, then emits ordinary Python with pandas. The name means "up to this point in time", which is all a feature is allowed to see.
|
|
6
|
+
|
|
7
|
+
Look-ahead bias is the classic silent bug in a backtest. A feature at time t quietly uses data that only existed after t, the backtest looks excellent, and the live strategy fails. Hitherto puts the check in the type system, so the mistake is a compile error with a line number.
|
|
8
|
+
|
|
9
|
+
`WRITEUP.md` is the whole project on one page.
|
|
10
|
+
|
|
11
|
+
## What it looks like
|
|
12
|
+
|
|
13
|
+
A program declares its inputs, builds streams from them, and marks each output as a `feature` or a `label`.
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
input mid : Stream[event, lag 0ms]
|
|
17
|
+
input flow : Stream[event, lag 0ms]
|
|
18
|
+
|
|
19
|
+
let mid_1s = bar(mid, 1s, last)
|
|
20
|
+
let ret_1s = mid_1s / shift(mid_1s, 1s) - 1
|
|
21
|
+
|
|
22
|
+
feature smooth = rolling(ret_1s, 10s, centred, mean)
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
A window centred on the present takes half its values from the future. The compiler says so, says where, and says how to fix it. This is `examples/leak_window.hto` with a few lines left out, which is why the message points at line 11:
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
leak_window.hto:11:18: error: feature reads the future
|
|
29
|
+
feature `smooth` has lag +5s, and a feature needs a lag of zero or less
|
|
30
|
+
cause : rolling(..., 10s, centred, ...) at 11:18 adds +5s
|
|
31
|
+
hint : use `trailing`, or shift the input back by 5s
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
No Python is produced for a rejected program. An accepted one compiles to a single function:
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
def run(mid, flow):
|
|
38
|
+
mid = hto_rt.as_stream("mid", mid, bar=None)
|
|
39
|
+
flow = hto_rt.as_stream("flow", flow, bar=None)
|
|
40
|
+
clock = hto_rt.bar(mid, pd.Timedelta("1s"), "count")
|
|
41
|
+
mid_1s = hto_rt.asof(clock, mid)
|
|
42
|
+
ret_1s = mid_1s / mid_1s.shift(freq=pd.Timedelta("1s")) - 1
|
|
43
|
+
...
|
|
44
|
+
return {
|
|
45
|
+
"features": {"momentum": momentum, "imbalance": imbalance},
|
|
46
|
+
"labels": {"fwd_ret": fwd_ret},
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## What a leak is worth
|
|
51
|
+
|
|
52
|
+
`python3 scripts/demo.py` takes three programs the compiler refuses and measures what each refused feature would have been. The compiler lets a `label` look ahead, so the same expression declared as a label does compile, and that gives the leaky series from the same generated code. Beside it goes the feature repaired the way the hint says.
|
|
53
|
+
|
|
54
|
+
The table is from one day of Apple, 30 December 2019, from NASDAQ TotalView-ITCH. The second column is the correlation with the price move over the next five seconds. The third is at how many of twenty cut times a row that was already known changed when the data after the cut was changed.
|
|
55
|
+
|
|
56
|
+
| Feature | Correlation with the next 5 seconds | Cuts at which a known row changed |
|
|
57
|
+
| --- | --- | --- |
|
|
58
|
+
| Window centred on the present, refused | +0.566 | 15 of 20 |
|
|
59
|
+
| The same window, trailing | +0.042 | 0 of 20 |
|
|
60
|
+
| Bars stamped with their start time, refused | +0.501 | 7 of 20 |
|
|
61
|
+
| The same bars, stamped at their end | +0.074 | 0 of 20 |
|
|
62
|
+
| Z-score over the whole sample, refused | +0.058 | 20 of 20 |
|
|
63
|
+
| The same z-score, expanding | +0.060 | 0 of 20 |
|
|
64
|
+
|
|
65
|
+
Two of the three leaks turn a feature with almost no relation to the future into one with a correlation of a half or more. The third predicts nothing extra. It is still a leak: its every value depends on data from later in the day, so it cannot be computed live, and the compiler refuses it for that reason and not for its score.
|
|
66
|
+
|
|
67
|
+
These are correlations on one day of one stock. They say nothing about profit. On an invented random walk, where there is nothing to predict, the same script gives +0.711 and +0.441 for the first two refused features. The arithmetic of a random walk says a five-second and a one-second look ahead should give 0.707 and 0.447.
|
|
68
|
+
|
|
69
|
+
## Many stocks
|
|
70
|
+
|
|
71
|
+
A program can hold a `Panel`, which is one stream for each stock, and compare stocks with one another at each moment. Which stocks are compared is a `Universe`, and a universe has a lag of its own: a list of the stocks trading now is known now, and a list of the stocks that trade at some point today is known at the close.
|
|
72
|
+
|
|
73
|
+
```
|
|
74
|
+
let traded = ever(ret)
|
|
75
|
+
feature relative = across(ret, traded, demean)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
```
|
|
79
|
+
leak_universe.hto:16:20: error: feature reads the future
|
|
80
|
+
feature `relative` has lag `future`, and a feature needs a lag of zero or less
|
|
81
|
+
cause : ever(...) at 14:16 uses the whole sample
|
|
82
|
+
hint : use `present`, which lists the symbols that have a value at each bar
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
`python3 scripts/demo_universe.py` measures what such a list knows, on 200 NASDAQ stocks on 30 January 2020. A stock is called active when it has traded in at least 20 different seconds of the last ten minutes. A filter run over the whole day keeps every stock that is active at some point, 111 of the 200, and lists them from the open.
|
|
86
|
+
|
|
87
|
+
| Group, once a minute | Stocks, on average | Share whose price moves in the next 5 minutes |
|
|
88
|
+
| --- | --- | --- |
|
|
89
|
+
| Active now | 29.2 | 96.3% |
|
|
90
|
+
| Active earlier today, not now | 39.3 | 78.5% |
|
|
91
|
+
| On the whole-day list, not active yet | 42.5 | 78.3% |
|
|
92
|
+
| Never active that day | 83.2 | 26.8% |
|
|
93
|
+
|
|
94
|
+
The third row is the leak: stocks that are on the list only because of something they have not done yet.
|
|
95
|
+
|
|
96
|
+
That is worth less than it looks. Being on the whole-day list has a correlation of +0.084 with the size of the next five-minute move, against +0.058 for the stocks active so far, and both of those use the same test of 20 seconds. `python3 scripts/fair_baseline.py` repeats the measurement with the test at 5, 10, 15 and 20 seconds, so the whole-day list is held against the best honest list and not one chosen to suit it. An honest list that asks for 5 seconds has +0.092. Of the 42.5 stocks the whole-day list names early, 40.2 are already on that looser honest list.
|
|
97
|
+
|
|
98
|
+
| Comparison | Gap in correlation | With the 200 stocks drawn again 2,000 times |
|
|
99
|
+
| --- | --- | --- |
|
|
100
|
+
| Whole-day list at 20, minus the best of eight honest lists. Fixed before the run | -0.008 | -0.056 to +0.026 |
|
|
101
|
+
| Whole-day list minus active so far, both at 20 | +0.026 | -0.003 to +0.057 |
|
|
102
|
+
| Both sides choose their own test. Added after the first numbers | +0.031 | +0.006 to +0.052 |
|
|
103
|
+
|
|
104
|
+
So the comparison that was fixed in advance shows no advantage for hindsight. Held to the same test the whole-day list is ahead by 0.02 to 0.03 at each of the four tests, which is about what loosening the test gives an honest list for free.
|
|
105
|
+
|
|
106
|
+
This is one day and 200 stocks, about the size of a move and not its direction, and not a profit. The reason to refuse a whole-day list is that it cannot be computed live, and that holds whatever it scores. And the checker only sees a list that is built in the program. The 200 stocks themselves were chosen by a script from those that traded that day, which is the same kind of list, made where the checker cannot see it.
|
|
107
|
+
|
|
108
|
+
## A leak that shipped
|
|
109
|
+
|
|
110
|
+
The public collection of example strategies for the freqtrade trading bot keeps a folder, [`lookahead_bias`](https://github.com/freqtrade/freqtrade-strategies/tree/main/user_data/strategies/lookahead_bias), of four strategies that its maintainers mark as reading the future. All four make the same mistake. They put an indicator on a scale from 0 to 1 using its smallest and largest value over the whole table of prices, and trade on where it sits. One of them buys when a baseline of the price is below 0.0128 on that scale, which is to say within about one percent of the lowest it will be anywhere in the data.
|
|
111
|
+
|
|
112
|
+
The compiler did not find that leak, since the maintainers had already marked it and Hitherto does not read Python. `examples/leak_minmax.hto` writes the feature in Hitherto, and the compiler refuses it:
|
|
113
|
+
|
|
114
|
+
```
|
|
115
|
+
leak_minmax.hto:20:17: error: feature reads the future
|
|
116
|
+
feature `level` has lag `future`, and a feature needs a lag of zero or less
|
|
117
|
+
cause : minmax(..., full_sample) at 20:17 uses the whole sample
|
|
118
|
+
hint : use `expanding`
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
`python3 scripts/shipped_leak.py` measures what the pattern is worth where the truth is known: 200 invented days of a price that nothing can predict, one-minute bars, entering where the scaled baseline is below a threshold and holding 30 bars. An honest rule must average zero there.
|
|
122
|
+
|
|
123
|
+
| Threshold | Scale taken over | Entries | Return per entry | Standard error |
|
|
124
|
+
| --- | --- | --- | --- | --- |
|
|
125
|
+
| 0.05 | Rows so far | 16,722 | -0.009% | 0.017% |
|
|
126
|
+
| 0.05 | Whole sample, the leak | 3,545 | +0.359% | 0.018% |
|
|
127
|
+
| 0.0128, the published value | Rows so far | 14,321 | -0.013% | 0.018% |
|
|
128
|
+
| 0.0128, the published value | Whole sample, the leak | 1,266 | +0.391% | 0.023% |
|
|
129
|
+
|
|
130
|
+
A 30-minute move of that price has a standard deviation of about 0.42%, so the leaking rule collects most of one typical move per trade from a price with nothing in it. These numbers are for the pattern on an invented price. They are not a backtest of the published strategy and say nothing about its results.
|
|
131
|
+
|
|
132
|
+
The first run of this measurement failed its own check, and the reason was a second look-ahead, in the evaluation. The plan averaged each day's mean return, and by that average the honest rule made +0.15% per trade, almost seven standard errors from zero. A day's mean divides by the number of entries in the day, which is not known until the day is over, and a day that keeps falling has more of them. `docs/26-minmax-and-a-shipped-leak.md` has the plan as it was written, the failure, a two-entry example that shows the bias by hand, and the statistic that replaced it. No type in this language would have caught that one: it is not in a feature.
|
|
133
|
+
|
|
134
|
+
## A leak in a library
|
|
135
|
+
|
|
136
|
+
The leak above was already marked by the people who published it. This one was looked for. The rules for what would count were written down first, in `leakhunt/PLAN.md`: a test that changes the data after a cut and shows an earlier value move, on default arguments, in something used as a feature, and not already reported. `leakhunt/harness.py` ran that test on all 355 indicators that five Python libraries expose on their defaults: ta, pandas-ta, finta, stockstats and freqtrade's technical. Nine moved. Eight were already known or read the future by what they are, such as an Ichimoku chikou span. The ninth is `STOCHRSI` in finta 1.3, the latest release:
|
|
137
|
+
|
|
138
|
+
```
|
|
139
|
+
((rsi - rsi.min()) / (rsi.max() - rsi.min())).rolling(window=stoch_period).mean()
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Its docstring describes the usual indicator, RSI against its range over a set time period. The code takes the range over the whole table, so every value depends on RSI values that come later. No report of it turned up in finta's issues, its pull requests or on the web. Written in Hitherto, `examples/leak_stochrsi.hto`, it is refused.
|
|
143
|
+
|
|
144
|
+
One public freqtrade strategy buys when it is below 0.2 and sells above 0.8. `leakhunt/stochrsi_measure.py` runs that rule on 200 invented paths of a price nothing can predict, as backtested and as the indicator stood at each bar:
|
|
145
|
+
|
|
146
|
+
| Version | Trades | Return per trade | Standard error |
|
|
147
|
+
| --- | --- | --- | --- |
|
|
148
|
+
| As of each bar | 111 | +2.13% | 1.37% |
|
|
149
|
+
| As backtested | 122 | +2.47% | 1.19% |
|
|
150
|
+
|
|
151
|
+
The two cannot be told apart: the rule trades about once a path and each trade is mostly noise. What the leak does change is what the backtest describes. 11 of its 122 entries, 9%, were made where the indicator as it stood then was not below 0.2, which the strategy running live would not have done. `docs/28-a-leak-in-a-library.md` has the plan as written before the run, the checks, and the limits. Nothing has been reported to finta.
|
|
152
|
+
|
|
153
|
+
## Install
|
|
154
|
+
|
|
155
|
+
```
|
|
156
|
+
pip install git+https://github.com/tavelarocque/hitherto
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
That installs the compiler written in Python, the command `hitherto`, and the one small module the generated code imports. It needs Python 3.11 or later and pandas 2.3 or later, and no OCaml.
|
|
160
|
+
|
|
161
|
+
```python
|
|
162
|
+
import hitherto
|
|
163
|
+
|
|
164
|
+
program = hitherto.compile("""
|
|
165
|
+
input mid : Stream[event, lag 0ms]
|
|
166
|
+
let mid_1s = bar(mid, 1s, last)
|
|
167
|
+
feature ret = mid_1s / shift(mid_1s, 1s) - 1
|
|
168
|
+
label next = lead(mid_1s, 5s) / mid_1s - 1
|
|
169
|
+
""")
|
|
170
|
+
|
|
171
|
+
out = program.run(mid=prices) # prices: a pandas Series indexed by timestamps
|
|
172
|
+
out["features"]["ret"]
|
|
173
|
+
print(program.python) # the pandas it compiled to
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
A program that reads the future raises `hitherto.CompileError`, and its text is the message shown above: where, what, the cause and a hint. Nothing is generated for it. From a shell, `hitherto file.hto` prints the Python and `hitherto --check file.hto` prints each name's type.
|
|
177
|
+
|
|
178
|
+
There are two compilers here and they are held to each other. `htoc` is written in OCaml and was built first. The package `hitherto` is the same four stages in Python. On every program the two must print the same tokens, the same tree, the same types, the same error at the same place and the same Python, to the character. `docs/23-a-second-generator.md` and `docs/24-a-package.md` have how.
|
|
179
|
+
|
|
180
|
+
## Linting Python, pandas, and Polars
|
|
181
|
+
|
|
182
|
+
The Python package also includes a static look-ahead linter for existing Python, pandas, and Polars code, built on the standard-library `ast` and `tokenize` modules with no extra dependencies. It applies the same row-availability lag model to pandas and Polars idioms (`shift(-k)` / `shift(n=-k)`, `diff(-k)`, `pct_change(-k)`, `rolling(..., center=True)`, whole-series reductions such as `.min()`, `.max()`, `.mean()`, `.std()`, and `np.mean()`, `.bfill()`, `.backward_fill()`, `.interpolate()`, `fill_null(strategy="backward")`, `resample(..., label="left")`, `merge_asof(..., direction="forward" | "nearest")`, `join_asof(..., strategy="forward" | "nearest")`, and `.fit_transform(...)`), while exempting causal windows (`rolling`, `expanding`, `ewm`, Polars `rolling_*` / `ewm_*`), scalar summary metrics, and cross-sectional `axis=1` operations. It tracks lags across local variables, pandas DataFrame columns, Polars `with_columns(...)` / `pl.col(...)` expressions, and same-file helper functions and methods, and accepts one or more files or directories:
|
|
183
|
+
|
|
184
|
+
```
|
|
185
|
+
hitherto --lint path/to/strategy.py
|
|
186
|
+
hitherto --lint path/to/repo/
|
|
187
|
+
hitherto --lint --ignore-labels path/to/repo/
|
|
188
|
+
hitherto --lint --format sarif path/to/repo/ > hitherto.sarif
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
It also traces local same-repo imported helper modules (`from .helpers import ...`, `import helpers`), and flags scikit-learn time-series split leaks (`train_test_split(...)` without `shuffle=False`, `KFold` / `ShuffleSplit`, and `fit(X)` called before `train_test_split(X, ...)`). Add `# hitherto: ignore` on a line to suppress an intentional look-ahead (such as a back-adjusted roll or training target), or pass `--ignore-labels` (`ignore_labels=True` in Python) to skip assignments to label-named targets (`fwd_ret`, `target`, `label`, `y`, `future_*`) while still flagging any feature that reads them downstream. Pass `--format json` or `--format sarif` for machine-readable output or GitHub Code Scanning annotations, or wire `.pre-commit-hooks.yaml` (`id: hitherto-lint`) into pre-commit. From Python, `hitherto.lint(source)`, `hitherto.lint_file(path)`, `hitherto.lint_path(path)`, `hitherto.format_json(...)`, and `hitherto.format_sarif(...)` expose the same analyzer and formatters. `scripts/check_lint.py` checks 36 leaky cases (including finta's `STOCHRSI`, freqtrade's whole-table minmax, Polars pipelines, and ML split leaks), 23 honest cases, cross-file helper tracing, 16 dynamic changed-future pipelines, the CLI on files, directories, JSON/SARIF, and multi-path invocations, and 32 planted bugs. Third-party installed libraries and dynamic imports are not traced across modules.
|
|
192
|
+
|
|
193
|
+
## Try it
|
|
194
|
+
|
|
195
|
+
```
|
|
196
|
+
python3 scripts/demo.py
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
The demo needs Python 3 with pandas. It compiles with `htoc` if that has been built with `dune build`, and with the compiler in Python if not, and prints the same either way. With no market data present it runs on an invented hour, so it works on a fresh clone.
|
|
200
|
+
|
|
201
|
+
## The idea
|
|
202
|
+
|
|
203
|
+
Every stream carries an availability lag in its type: how long after a row's timestamp its value is really known. Each operation has a rule for what it does to the lag. Anything declared a `feature` must end with a lag of zero or less. A `label` may look ahead, because it is a prediction target and not an input. Lags exist only at compile time. The emitted Python carries plain pandas objects.
|
|
204
|
+
|
|
205
|
+
| Operation | Resulting lag |
|
|
206
|
+
| --- | --- |
|
|
207
|
+
| Arithmetic on two streams (same grid) | The larger of the two lags |
|
|
208
|
+
| A stream combined with a number | Unchanged |
|
|
209
|
+
| `shift(s, d)` | Lag minus d |
|
|
210
|
+
| `lead(s, d)` | Lag plus d |
|
|
211
|
+
| `rolling(s, w, trailing, f)` | Unchanged |
|
|
212
|
+
| `rolling(s, w, centred, f)` | Lag plus half of w; on a bar grid, plus the whole bars that fit in half of w |
|
|
213
|
+
| `rolling(s, w, MODE, f, n)` | The same as without the minimum count n |
|
|
214
|
+
| `bar(s, d, f)` | Unchanged, on the grid `bar d` |
|
|
215
|
+
| `bar(s, d, f, at_start)` | Lag plus d, on the grid `bar d` |
|
|
216
|
+
| `asof(a, b)` | The larger of the two lags, on the grid of a |
|
|
217
|
+
| `asof(a, b, forward)` | `future`, which no shift can repair |
|
|
218
|
+
| `zscore(s, expanding)` | Unchanged |
|
|
219
|
+
| `zscore(s, full_sample)` | `future` |
|
|
220
|
+
| `minmax(s, expanding)` | Unchanged |
|
|
221
|
+
| `minmax(s, full_sample)` | `future` |
|
|
222
|
+
| `fill(s, x)`, x a number | Unchanged |
|
|
223
|
+
| `fill(s, b)`, b a stream (same grid) | The larger of the two lags |
|
|
224
|
+
| Any of the above on a `Panel` | The same rule, for each symbol |
|
|
225
|
+
| A stream combined with a panel (same grid) | The larger of the two lags, and the result is a panel |
|
|
226
|
+
| `shift(u, d)`, `lead(u, d)` on a `Universe` | Lag minus d, lag plus d |
|
|
227
|
+
| `across(p, u, MODE)` (same bar grid) | The larger of the panel's lag and the universe's lag |
|
|
228
|
+
| `present(p)`, `top(p, n)` | A universe with the lag of p |
|
|
229
|
+
| `ever(p)` | A universe with lag `future` |
|
|
230
|
+
| `feature x = e` | Must be zero or less |
|
|
231
|
+
| `label y = e` | Any lag |
|
|
232
|
+
|
|
233
|
+
On a bar grid, the amount in a `shift` or `lead` and the window in a `rolling` must be a whole number of bars.
|
|
234
|
+
|
|
235
|
+
The typing idea follows Xavier Fonseca's "Look-Ahead-Freedom as Temporal Non-Interference" (arXiv 2607.04958). Three rules here are that paper's: combining takes the maximum, a trailing window keeps the lag, and a feature is checked the way the paper checks a decision. The rules for `shift`, `lead`, centred windows, bar labelling, full-sample statistics, `fill` and a minimum count are additions made here, and the paper's soundness proof does not cover them. `docs/06-lag-rules.md`, `docs/07-asof-and-grids.md`, `docs/08-zscore-and-causes.md`, `docs/14-fill.md`, `docs/16-enough-data.md` and `docs/17-many-stocks.md` give a written argument for each rule. Those arguments are on paper and are not machine-checked.
|
|
236
|
+
|
|
237
|
+
## The language on one page
|
|
238
|
+
|
|
239
|
+
A program is a list of declarations, one per line. `#` starts a comment.
|
|
240
|
+
|
|
241
|
+
```
|
|
242
|
+
input NAME : TYPE a value supplied when the program runs
|
|
243
|
+
let NAME = EXPR a name for an expression
|
|
244
|
+
let NAME : TYPE = EXPR the same, with a type the checker verifies
|
|
245
|
+
feature NAME = EXPR an output that must not read the future
|
|
246
|
+
label NAME = EXPR an output that may
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
The types are `Num`, `Duration`, `Stream[GRID, lag D]`, `Panel[GRID, lag D]` and `Universe[GRID, lag D]`. A grid is `event`, for rows at any time, or `bar D`, for rows at whole multiples of D. A duration is a whole number and a unit with nothing between them: `ns`, `us`, `ms`, `s` or `min`. A lag may be negative.
|
|
250
|
+
|
|
251
|
+
A panel is one stream for each symbol. Every function below takes a panel wherever it takes a stream and works on each symbol by itself. A universe says which symbols count at each bar, with a lag of its own. It is not a series: it can be declared, built from a panel, moved in time and handed to `across`, and nothing else.
|
|
252
|
+
|
|
253
|
+
In generated code a panel is a dict from symbol to pandas Series, and a universe a dict from symbol to the DatetimeIndex of the bars at which it is a member. Four things hold for panels that a single stream never needed. A symbol with no rows and a symbol that is not there are the same thing. Two panels are matched over every symbol either has. A stream that gives rows beside a panel, as in arithmetic, is cut for each symbol to start at that symbol's first row, and a stream a panel only reads, as in `asof(panel, stream)`, is read whole. And the bars of a panel, or of a stream made from one, run from each symbol's first row to a moment worked out from the end of the whole sample, not to where that symbol's rows or that panel's rows stop. Each of these is there because the more obvious definition let the future show through which rows exist. `docs/19-panels-that-run.md` has the cases, and `docs/20-real-stocks.md` the one real data corrected.
|
|
254
|
+
|
|
255
|
+
Expressions are numbers, names, `+ - * /`, a leading minus, brackets, and calls to eleven functions.
|
|
256
|
+
|
|
257
|
+
| Function | Meaning |
|
|
258
|
+
| --- | --- |
|
|
259
|
+
| `shift(s, d)` | Every row of s moved later by d |
|
|
260
|
+
| `lead(s, d)` | Every row of s moved earlier by d |
|
|
261
|
+
| `rolling(s, w, MODE, AGG)` | At each row, AGG over a window of width w. MODE is `trailing` or `centred`. A fifth argument, a whole number n, makes the result missing unless the window holds at least n values |
|
|
262
|
+
| `bar(s, d, AGG)` | One row per bar of width d, stamped at its end. A fourth argument `at_start` stamps the start |
|
|
263
|
+
| `asof(a, b)` | At each row of a, the latest value of b at or before it. A third argument `forward` reads the next one |
|
|
264
|
+
| `zscore(s, MODE)` | Each value less the mean, over the spread. MODE is `expanding` or `full_sample` |
|
|
265
|
+
| `minmax(s, MODE)` | Each value on a scale from 0 at the smallest to 1 at the largest. MODE is `expanding` or `full_sample`. Missing where the smallest and largest are the same |
|
|
266
|
+
| `fill(s, x)` | s with x wherever its value is missing. x is a number, or a second stream on the same grid, read at the same timestamp |
|
|
267
|
+
| `across(p, u, MODE)` | At each bar, the values of panel p compared over the members of universe u that have a value there. `demean` is the value less the group's mean, `zscore` that over the group's spread, and `rank` runs from 0 for the smallest to 1 for the largest: each gives a panel with the rows of p, missing for a symbol outside the group. `mean`, `sum` and `count` give one number for the group, so a stream |
|
|
268
|
+
| `present(p)` | The universe of symbols for which p has a value at each bar |
|
|
269
|
+
| `top(p, n)` | The universe of the n symbols with the largest values of p at each bar. Equal values go to the symbol whose name sorts first |
|
|
270
|
+
| `ever(p)` | The universe of symbols for which p has a value at any time in the sample. No feature can use it |
|
|
271
|
+
|
|
272
|
+
AGG is one of `sum`, `mean`, `std`, `min`, `max`, `first`, `last`, `count`. An aggregation ignores missing values. With none present it is missing, except `count`, which is zero. With a minimum count, every aggregation is missing below it, `count` included.
|
|
273
|
+
|
|
274
|
+
A duration is not a number. `5s * 2` is an error, and a negative shift is written `lead`.
|
|
275
|
+
|
|
276
|
+
## How it was checked
|
|
277
|
+
|
|
278
|
+
The compiler was built in twenty steps, and each step had to pass the same four kinds of check before the next began.
|
|
279
|
+
|
|
280
|
+
**Expect tests.** 198 of them, recording the exact output for small programs, including every error message.
|
|
281
|
+
|
|
282
|
+
**Independent references.** The lexer, the parser and the type checker each have a second implementation in Python, written separately. The two are compared on thousands of random programs, valid and invalid, down to the position and text of every error. The code generator has a second implementation in Python too. That one is a port and not an independent design, and it has to write the same Python as the OCaml one, character for character, on every program.
|
|
283
|
+
|
|
284
|
+
**The promise itself.** The generated Python is compared with a reference interpreter that uses no pandas. Then every program is run twice, on two data sets that agree on everything available by a cut time and differ after it, and every output row the type checker says was known by then must be identical. To show that test can fail, outputs that are late by design are also treated as features, and their leak must show. For programs with many stocks, the second data set also changes which stocks there are after the cut: a stock may stop, carry on, come back or appear for the first time, and a whole panel may stop.
|
|
285
|
+
|
|
286
|
+
**Planted bugs.** 552 deliberate bugs, each applied to a copy of the repository: in both compilers, the runtime, the package, the real-data scripts, the demo and the two measurements. Every one must be caught by at least one check. All 552 are, one of them only on pandas 3.1 or later, where it changes anything.
|
|
287
|
+
|
|
288
|
+
It has also been run on real data: three symbol-days from NASDAQ TotalView-ITCH, from Apple down to the median stock by trading activity. On each, the compiled output was compared with a hand-written pandas version and with the reference interpreter on every row. Real data found things invented data had not, and `docs/12-one-real-day.md` and `docs/13-thin-stocks.md` describe them.
|
|
289
|
+
|
|
290
|
+
The program for many stocks has been run on one real day of 200 NASDAQ stocks, chosen by a fixed rule to run from the least traded to the most. A hand-written version on one table agrees on all 31,363,813 output rows, the reference interpreter agrees on short stretches, and with the day changed after each of ten cut times, stocks stopping and vanishing among the changes, every row known by the cut stayed identical. `docs/20-real-stocks.md` has it, with a measurement of what a list of stocks made with hindsight knows.
|
|
291
|
+
|
|
292
|
+
All of this was measured on one Linux machine with OCaml 4.14.1 and pandas 3.0.5. The tests of the generated code, on invented and real data, were repeated on pandas 2.3.3 and 3.1.1.
|
|
293
|
+
|
|
294
|
+
The sum, the mean and the standard deviation of a bar are added up by the runtime and not by pandas. In pandas 3.1 a grouped sum depends, in its last digit, on whether the series has a missing value anywhere, including later, and with the sums left to pandas the test above failed there. `docs/27-sums-of-its-own.md` has the account. The runtime's method is the one pandas used up to 3.0, so on those versions every digit is what it was.
|
|
295
|
+
|
|
296
|
+
The project was built with an AI coding assistant, which wrote most of the code, the tests and the walkthroughs. The checks above are the reason to believe it works.
|
|
297
|
+
|
|
298
|
+
## Limits
|
|
299
|
+
|
|
300
|
+
The compiler checks declared lags, not reality. An input declared with the wrong lag still compiles.
|
|
301
|
+
|
|
302
|
+
It sees one kind of leak. Survivorship bias, restated data, a model fitted on its own test period and a language model that memorised the answer all pass.
|
|
303
|
+
|
|
304
|
+
The arguments for the lag rules are written proofs on paper. Nothing here is machine-checked, and "tested" is the right word for the generated code, not "proven".
|
|
305
|
+
|
|
306
|
+
The changed-future test holds two things fixed: the moment the sample as a whole ends, and for each single stream the moment that stream ends. A leak that worked only through those would not be seen. Where a stock's rows stop, and where a panel's rows stop, is not held fixed.
|
|
307
|
+
|
|
308
|
+
A feature free of look-ahead is not a good feature. On a thinly traded stock the example pipeline is mostly zeros, or with a minimum count mostly missing. A minimum count is a number of values and says nothing about how they are spread in time, and bars and z-scores have none.
|
|
309
|
+
|
|
310
|
+
Programs with many stocks have run on one real day: the 200-stock check runs in a few seconds against a hand-written table, and all 2,301 NASDAQ common stocks that traded on 30 January 2020 ran in 50.35 seconds with 6.69 GB peak memory on an 8 GB machine (358,787,861 rows; one changed-future cut checked). That is still one day of one exchange, and the stocks included are chosen by what traded that day, outside the checker. The argument that the rows of a panel do not leak is on paper, and the first drafts of those definitions were wrong six times before the tests and the real day agreed.
|
|
311
|
+
|
|
312
|
+
A universe built from the whole sample is refused in a feature. That is the only kind of survivorship caught. Which symbols a panel holds comes from the data and is outside the checker: a file of survivors gives a panel of survivors, and a universe input with a false declared lag is believed.
|
|
313
|
+
|
|
314
|
+
Adding a bar up in the runtime costs time. On two million rows that step takes 0.2 to 0.4 seconds where pandas alone takes 0.03, and the day of 200 stocks runs in 8.3 seconds where it ran in 6.9. Rolling windows are still pandas' own. Those were tested for the same fault on pandas 3.1.1 and did not show it, which is not a promise about the next version.
|
|
315
|
+
|
|
316
|
+
How far a series reaches is worked out in 64-bit arithmetic that wraps round, in both generators. Two shifts of 292 years each would give a wrong moment. No run can reach it, since pandas refuses the first of those shifts with an overflow error.
|
|
317
|
+
|
|
318
|
+
Three single-stock days and one day of 200 stocks is all the real data it has seen, and that data is a tape of executions, so the mid-quote is known only at the moments something traded.
|
|
319
|
+
|
|
320
|
+
## Build and test
|
|
321
|
+
|
|
322
|
+
```
|
|
323
|
+
dune build
|
|
324
|
+
dune test
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
Requirements: OCaml, dune 3.0 or later, Menhir and ppx_expect. The generated Python and its tests need Python 3 with pandas. The real-data scripts also need pyarrow.
|
|
328
|
+
|
|
329
|
+
A program can also be compiled with Python alone: `python3 -m hitherto examples/pipeline.hto` prints what `htoc examples/pipeline.hto` prints, and the same goes for `--tokens`, `--parse`, `--ast` and `--check`.
|
|
330
|
+
|
|
331
|
+
After `dune build`:
|
|
332
|
+
|
|
333
|
+
```
|
|
334
|
+
python3 scripts/demo.py # the demo above
|
|
335
|
+
python3 scripts/check_demo.py # the demo's numbers, by a second route
|
|
336
|
+
python3 scripts/diff_lexer.py # the lexer against its reference
|
|
337
|
+
python3 scripts/diff_parser.py # the parser against its reference
|
|
338
|
+
python3 scripts/diff_check.py # the type checker against its reference
|
|
339
|
+
python3 scripts/diff_emit.py # the generated Python: its values, and that it cannot see the future
|
|
340
|
+
python3 scripts/diff_gen.py # the code generator against its second implementation in Python
|
|
341
|
+
python3 scripts/check_package.py # the Python command line and functions, and a pip install with no OCaml
|
|
342
|
+
python3 scripts/check_without_ocaml.py # what works with no htoc at all; the only check that needs none
|
|
343
|
+
python3 scripts/planted_bugs.py --first # deliberate bugs the tests must catch; about half an hour
|
|
344
|
+
python3 scripts/demo_synthetic.py # the original target program on invented data
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
These need real days in `demo/data/`, which git ignores because exchange data does not belong in a repository. The days are exported from a tape, which is the file of executions that `itch-trades` in [itchbook](https://github.com/tavelarocque/itchbook) writes from a NASDAQ TotalView-ITCH file. Set `HITHERTO_ITCH_TAPES` to the folder that holds the tapes.
|
|
348
|
+
|
|
349
|
+
```
|
|
350
|
+
python3 scripts/export_itch.py # write demo/data/ from an itchbook tape (needs the tape)
|
|
351
|
+
python3 scripts/diff_itch.py # the compiled pipelines on every exported day, checked four ways
|
|
352
|
+
python3 scripts/demo_itch.py # compile a pipeline and run it on a real day
|
|
353
|
+
python3 scripts/export_panel.py # write demo/data/panels/: 200 stocks of one day (needs the tape)
|
|
354
|
+
python3 scripts/diff_panel.py # the many-stocks program on those 200, checked five ways
|
|
355
|
+
python3 scripts/demo_universe.py # what a list of stocks made with hindsight knows
|
|
356
|
+
python3 scripts/fair_baseline.py # the same against looser honest lists, with a second route
|
|
357
|
+
python3 scripts/shipped_leak.py # the leak of four published strategies, on invented days (no tape needed)
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
## Command line
|
|
361
|
+
|
|
362
|
+
```
|
|
363
|
+
htoc --tokens file.hto print the tokens with their source spans
|
|
364
|
+
htoc --parse file.hto parse and print the program back in canonical form
|
|
365
|
+
htoc --ast file.hto the same, as a tree with the source span of every node
|
|
366
|
+
htoc --check file.hto type check and print the type of every declaration
|
|
367
|
+
htoc file.hto compile to Python and print it
|
|
368
|
+
htoc file.hto -o out.py compile to Python and write it to a file
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
The generated file defines one function, `run`, which takes a pandas Series indexed by timestamp for each stream input and returns `{"features": {...}, "labels": {...}}`. It imports `hto_rt` from the `runtime` folder, so keep that file beside it or on the Python path.
|
|
372
|
+
|
|
373
|
+
## Examples
|
|
374
|
+
|
|
375
|
+
`examples/pipeline.hto` is the first target program: mid-prices and signed trade sizes go in, two features and one training label come out.
|
|
376
|
+
|
|
377
|
+
`examples/pipeline_carry.hto` is the same program with one change that real data called for. A quiet second keeps the last known price, written with a clock of bar counts and an `asof` against it.
|
|
378
|
+
|
|
379
|
+
`examples/pipeline_fill.hto` goes one step further, for stocks that trade a few hundred times a day. A second with no trade has zero flow, and a minute with no price change has zero momentum, each written with `fill`. It is the version the demo runs.
|
|
380
|
+
|
|
381
|
+
`examples/pipeline_enough.hto` is the first program again, repaired a different way. Its spread needs ten returns, taken over a minute and, where a minute has too few, over ten minutes. On the thin stock where the first program gave infinite values, it gives none.
|
|
382
|
+
|
|
383
|
+
`examples/many_stocks.hto` is the filled program with panels for inputs and one index stream beside them, followed by two universes built from the data and three features that compare stocks with `across`. It has been run on 200 real stocks.
|
|
384
|
+
|
|
385
|
+
`examples/whole_day_universe.hto` makes three lists of active stocks from the same trades: active now, active so far today, and active at some point in the whole day. The third is refused in a feature. `scripts/demo_universe.py` measures what it knows that the other two do not, and `scripts/fair_baseline.py` repeats that with the honest lists given looser tests.
|
|
386
|
+
|
|
387
|
+
Each `leak_*.hto` file is a small program with one look-ahead leak in it. The first three are the first program with a leak added. The matching `.expected` file holds the exact error the compiler prints for it when run from the `examples` folder, and the tests compare the two byte for byte.
|
|
388
|
+
|
|
389
|
+
| File | Leak |
|
|
390
|
+
| --- | --- |
|
|
391
|
+
| `leak_window.hto` | A rolling window centred on t, which takes half its values from the future |
|
|
392
|
+
| `leak_bar.hto` | A bar's closing value stamped with the bar's opening time |
|
|
393
|
+
| `leak_zscore.hto` | A z-score computed with the mean and spread of the whole sample |
|
|
394
|
+
| `leak_universe.hto` | Stocks compared over the list of those that trade at some point in the sample |
|
|
395
|
+
| `leak_minmax.hto` | A baseline of the price scaled by its smallest and largest value over the whole sample, as in four published strategies |
|
|
396
|
+
| `leak_stochrsi.hto` | finta's stochastic RSI, scaled by the smallest and largest RSI of the whole table |
|
|
397
|
+
|
|
398
|
+
## Layout
|
|
399
|
+
|
|
400
|
+
```
|
|
401
|
+
bin/htoc.ml command-line entry point
|
|
402
|
+
lib/loc.ml source locations
|
|
403
|
+
lib/token.ml the token type
|
|
404
|
+
lib/lexer.mll the lexer (ocamllex)
|
|
405
|
+
lib/ast.ml the syntax tree
|
|
406
|
+
lib/parser.mly the grammar (Menhir)
|
|
407
|
+
lib/parse.ml lexer and parser together, with one shape of error
|
|
408
|
+
lib/duration.ml canonical spelling of durations
|
|
409
|
+
lib/print.ml syntax tree back to source text
|
|
410
|
+
lib/types.ml the checker's types and the arithmetic on lags
|
|
411
|
+
lib/check.ml the type checker
|
|
412
|
+
lib/emit.ml the code generator
|
|
413
|
+
runtime/hto_rt.py the small Python module the generated code imports
|
|
414
|
+
test/ expect tests
|
|
415
|
+
examples/ four versions of the pipeline, two for many stocks and six leak programs
|
|
416
|
+
leakhunt/ the search for a leak in five indicator libraries, and the measurement of the one found
|
|
417
|
+
docs/ one prose walkthrough per build step
|
|
418
|
+
hitherto/ the compiler a second time, in Python: lexer.py, parser.py,
|
|
419
|
+
checker.py and emit.py, with api.py and a command line around them
|
|
420
|
+
pyproject.toml what pip installs: that package and runtime/hto_rt.py
|
|
421
|
+
scripts/diff_gen.py the two generators against each other, character for character
|
|
422
|
+
scripts/check_package.py the Python command line, its functions, and a pip install with no OCaml
|
|
423
|
+
scripts/check_without_ocaml.py the leak programs, the examples and the demo, with no htoc
|
|
424
|
+
.github/workflows/ci.yml both compilers on four versions of pandas on every push, and a pip install with no OCaml on five
|
|
425
|
+
scripts/eval_ref.py reference interpreter, with no pandas in it
|
|
426
|
+
scripts/diff_lexer.py, diff_parser.py, diff_check.py
|
|
427
|
+
the two compilers against each other on random programs
|
|
428
|
+
scripts/diff_emit.py the generated Python against the reference interpreter,
|
|
429
|
+
and the test that it cannot see the future
|
|
430
|
+
scripts/planted_bugs.py deliberate bugs, each on a temporary copy of the repo
|
|
431
|
+
scripts/demo.py the demo: three refused programs, what each leak is worth,
|
|
432
|
+
and the accepted pipeline
|
|
433
|
+
scripts/check_demo.py the demo's numbers by a second route
|
|
434
|
+
scripts/demo_synthetic.py the first target program on invented data
|
|
435
|
+
scripts/export_itch.py one symbol's day from an itchbook tape, as the two inputs
|
|
436
|
+
scripts/itch_inputs.py loading an exported day and compiling a program
|
|
437
|
+
scripts/pipeline_by_hand.py the pipelines written by hand in pandas
|
|
438
|
+
scripts/diff_itch.py the compiled pipelines on every exported day, checked four ways
|
|
439
|
+
scripts/demo_itch.py a pipeline, compiled and run on a real day
|
|
440
|
+
scripts/export_panel.py many stocks of one day from a tape, chosen by a fixed rule
|
|
441
|
+
scripts/many_by_hand.py the many-stocks program written by hand on one table
|
|
442
|
+
scripts/diff_panel.py the many-stocks program on real stocks, checked five ways
|
|
443
|
+
scripts/demo_universe.py what a list of stocks made with hindsight knows
|
|
444
|
+
scripts/fair_baseline.py the same at looser tests, with a second route and an interval
|
|
445
|
+
scripts/shipped_leak.py the leak of four published strategies, measured on invented days
|
|
446
|
+
scripts/exercise_diff.py, docs/exercise-diff.md
|
|
447
|
+
an exercise: add a `diff` operator, with a script that checks the attempt
|
|
448
|
+
WRITEUP.md the project on one page
|
|
449
|
+
LICENSE MIT
|
|
450
|
+
```
|
|
451
|
+
|
|
452
|
+
## Walkthroughs
|
|
453
|
+
|
|
454
|
+
`docs/` holds one document per build step, written to be read in order.
|
|
455
|
+
|
|
456
|
+
| | |
|
|
457
|
+
| --- | --- |
|
|
458
|
+
| `02-lexer.md` | Tokens, durations as whole nanoseconds |
|
|
459
|
+
| `03-parser-declarations.md` | The grammar for declarations and types |
|
|
460
|
+
| `04-parser-expressions.md` | Expressions, precedence, printing back |
|
|
461
|
+
| `05-types-and-checker.md` | Lag arithmetic and the checker's skeleton |
|
|
462
|
+
| `06-lag-rules.md` | The rules, and the written argument for them |
|
|
463
|
+
| `07-asof-and-grids.md` | `asof`, and why bars move in whole bars |
|
|
464
|
+
| `08-zscore-and-causes.md` | `zscore`, and tracking what caused a lag |
|
|
465
|
+
| `09-error-messages.md` | The final form of a rejection |
|
|
466
|
+
| `10-code-generation.md` | Python from a checked program, and the changed-future test |
|
|
467
|
+
| `11-bars-joins-and-zscores.md` | The rest of the generator, and four things the tests found |
|
|
468
|
+
| `12-one-real-day.md` | One real day, and what it showed |
|
|
469
|
+
| `13-thin-stocks.md` | The median stock, where the pipeline is nearly empty |
|
|
470
|
+
| `14-fill.md` | `fill`, the one function real data asked for |
|
|
471
|
+
| `15-demo.md` | The demo, and what a leak is worth |
|
|
472
|
+
| `16-enough-data.md` | A minimum count for windows, and `fill` from a second stream |
|
|
473
|
+
| `17-many-stocks.md` | Panels and universes: the types, and why the old rules carry over |
|
|
474
|
+
| `18-across.md` | Comparing stocks with `across`, building a universe, and a universe from the whole sample as a type error |
|
|
475
|
+
| `19-panels-that-run.md` | Generated pandas for many stocks, the rule about which rows exist, and five definitions that leaked |
|
|
476
|
+
| `20-real-stocks.md` | Two hundred real stocks, a definition real data corrected, and what a whole-day list of stocks is worth |
|
|
477
|
+
| `21-many-stocks-in-review.md` | Milestones 17 to 20 in one place: the idea, the arguments, what went wrong, and what can be claimed |
|
|
478
|
+
| `22-a-fairer-baseline.md` | The hindsight number against looser honest lists: the plan written first, the gap that closed, and what was withdrawn |
|
|
479
|
+
| `23-a-second-generator.md` | The code generator written a second time in Python, the test that holds the two together, and what writing it found |
|
|
480
|
+
| `24-a-package.md` | The Python compiler as a package: `pip install`, `hitherto.compile`, a command line that matches `htoc`, and an install test with no OCaml |
|
|
481
|
+
| `25-ci-and-no-ocaml.md` | Checks that run on every push, a check that needs no OCaml, and scripts that work with either compiler |
|
|
482
|
+
| `26-minmax-and-a-shipped-leak.md` | `minmax`, a leak from four published strategies, and a measurement whose own average looked ahead |
|
|
483
|
+
| `27-sums-of-its-own.md` | A newer pandas that rounds a bar's sum by what comes later, and a runtime that adds bars up itself |
|
|
484
|
+
| `28-a-leak-in-a-library.md` | A changed-future test of 355 indicators, a leak in finta's StochRSI, and what it does to a rule built on it |
|
|
485
|
+
| `29-full-universe-and-linter.md` | All 2,301 NASDAQ stocks on an 8 GB machine, the Python/pandas look-ahead linter, and version 0.1.0 |
|
|
486
|
+
| `30-polars-ml-and-ci.md` | Polars rules, cross-file helper tracing, ML split checks, JSON/SARIF output, pre-commit, and version 0.2.0 |
|
|
487
|
+
|
|
488
|
+
## Licence
|
|
489
|
+
|
|
490
|
+
MIT, see [LICENSE](LICENSE). The NASDAQ market data is not part of this repository and is not covered by this licence.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Hitherto in one page
|
|
2
|
+
|
|
3
|
+
**What it is.** Hitherto is a small typed language for time-series feature pipelines. Its compiler refuses any feature that reads the future, and turns everything else into ordinary Python with pandas. The compiler exists twice, once in OCaml and once in Python, and the Python one installs with `pip` and is called from a notebook in two lines.
|
|
4
|
+
|
|
5
|
+
**The problem.** Look-ahead bias is the quiet bug of backtesting. A feature at time t uses data that only existed after t, the backtest looks excellent, and the live strategy fails.
|
|
6
|
+
|
|
7
|
+
**The idea.** Every stream carries an availability lag in its type: how long after a row's timestamp its value is really known. Each operation has a rule for what it does to that lag, and anything declared a `feature` must end with a lag of zero or less. So a window centred on the present, a bar stamped with its opening time, a z-score over the whole sample and a list of "the stocks that traded today" used from the open are all compile errors, each with a line number, the cause and a fix. The typing idea is Xavier Fonseca's (arXiv 2607.04958). Three of the rules here are that paper's. The rules for shifts, centred windows, bar labelling, full-sample statistics, filling and a minimum count are additions made here, and the paper's proof does not cover them. Every rule has a written argument in `docs/`, on paper and not machine-checked.
|
|
8
|
+
|
|
9
|
+
**How it was checked.** Four ways, at every step. There are 198 expect tests. The two compilers are held to each other: on thousands of random programs they must give the same tokens, the same tree, the same types, the same error at the same place and the same generated code to the character. Three of the Python compiler's four stages were written independently of the OCaml ones. Its code generator is a port. The generated pandas is compared with a reference interpreter that uses no pandas, and then every program is run on two data sets that agree up to a cut time and differ after it, where every row the checker calls known must be identical. And 552 deliberate bugs were planted in a copy of the repository, in both compilers and in everything around them, every one of which has to be caught by some check. All are. On NASDAQ TotalView-ITCH data, three symbol-days and one day of 200 stocks, the compiled output matches a hand-written pandas version on every row, 31,363,813 of them on the day of 200 stocks.
|
|
10
|
+
|
|
11
|
+
**What a leak is worth.** On one day of Apple, a window centred on the present has a correlation of +0.566 with the price move over the next five seconds, against +0.042 for the same window trailing. Bars stamped at their start give +0.501 against +0.074. On an invented random walk the same two leaks score +0.711 and +0.441, where the arithmetic says 0.707 and 0.447. These are correlations on one day of one stock and say nothing about profit. A leak from published code was measured too. Four example strategies for the freqtrade bot, which its maintainers mark as reading the future, scale an indicator by its smallest and largest value over the whole table of prices, and one buys when a baseline of the price is near the bottom of that scale. Written in Hitherto the feature does not compile. On 200 invented days of a price nothing can predict, that rule makes +0.39% per trade at the published threshold (standard error 0.02%) where an honest scale makes -0.01%. That leak was already marked, so a second was looked for, under rules written down first: a test that changes the data after a cut, run on 355 indicators from five Python libraries. It found that finta's stochastic RSI scales RSI by its range over the whole table, which no issue or pull request of finta's mentions. On a rule from a public strategy built on it, 9% of the backtest's entries were trades the indicator, as it stood at the time, did not call for, though on invented prices the profit of the two versions could not be told apart.
|
|
12
|
+
|
|
13
|
+
**What went wrong.** The definitions of which rows a panel of stocks has were wrong six times before the tests and real data agreed. Five of the six leaked the future through which rows exist, and not through any value. Real data found things invented data had missed. And one result was withdrawn. An early measurement said a whole-day list of stocks went with future movement more strongly than an honest list. Against a fairer baseline, written down before it was run, the gap was -0.008 (-0.056 to +0.026), because a looser honest list already held 40 of the 42 stocks the hindsight list seemed to know about. The list is refused because it cannot be computed live, whatever it scores. And the measurement of the published leak failed its own check on the first run: by the average its plan had fixed, the honest rule made +0.15% per trade on a price that cannot be predicted. The plan averaged each day's mean, which divides by a count of trades that is not known until the day ends. That was a look-ahead in the evaluation, where no type reaches. Then a new version of pandas broke the promise from underneath: in 3.1 a grouped sum rounds differently when the series has a missing value anywhere, so a gap late in the day moved the last digit of an earlier bar, and the changed-future test caught it on a fresh install. The runtime now adds bars up itself.
|
|
14
|
+
|
|
15
|
+
**Limits.** The compiler checks declared lags and not reality: an input declared with the wrong lag compiles. It sees one kind of leak. Survivorship in a data file, restated data and a model fitted on its own test period all pass. "Tested" is the right word for the generated code, not "proven". The real data is three symbol-days and one day of 200 stocks, all from one exchange.
|
|
16
|
+
|
|
17
|
+
**How it was built.** With an AI coding assistant, which wrote most of the code, the tests and the walkthroughs. The checks above are the reason to believe it works.
|
|
18
|
+
|
|
19
|
+
The README has the language, the commands and the full list of limits. `docs/` has one walkthrough for each step, mistakes included.
|