@senpi/runtime 3.0.9-dev.20260710204324 → 3.0.9-dev.feat-strategy-compos.20260716013009
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.
- package/dist/cli/composer-commands.d.ts +37 -0
- package/dist/cli/composer-commands.d.ts.map +1 -0
- package/dist/cli/composer-commands.js +287 -0
- package/dist/cli/composer-commands.js.map +1 -0
- package/dist/cli/senpi-commands.d.ts.map +1 -1
- package/dist/cli/senpi-commands.js +2 -0
- package/dist/cli/senpi-commands.js.map +1 -1
- package/dist/cli/validate-runtime-config.mjs +124 -0
- package/dist/composer/AUTHORING.md +233 -0
- package/dist/composer/__init__.py +29 -0
- package/dist/composer/authoring/__init__.py +49 -0
- package/dist/composer/authoring/answers.py +226 -0
- package/dist/composer/authoring/archetypes/__init__.py +25 -0
- package/dist/composer/authoring/archetypes/_common.py +218 -0
- package/dist/composer/authoring/archetypes/classifier.py +109 -0
- package/dist/composer/authoring/archetypes/skeleton.py +54 -0
- package/dist/composer/authoring/archetypes/thesis_fund.py +103 -0
- package/dist/composer/authoring/archetypes/trend_momentum.py +104 -0
- package/dist/composer/authoring/builder.py +191 -0
- package/dist/composer/authoring/emit.py +264 -0
- package/dist/composer/authoring/gaps.py +115 -0
- package/dist/composer/authoring/generate.py +131 -0
- package/dist/composer/authoring/presets.py +168 -0
- package/dist/composer/authoring/runtime_emit.py +266 -0
- package/dist/composer/authoring/strategy_manifest.py +94 -0
- package/dist/composer/cli.py +355 -0
- package/dist/composer/compiler/__init__.py +22 -0
- package/dist/composer/compiler/compile.py +550 -0
- package/dist/composer/examples/breakout_swing.graph.yaml +121 -0
- package/dist/composer/examples/conviction_scorer.graph.yaml +216 -0
- package/dist/composer/examples/macro_thesis_basket.graph.yaml +247 -0
- package/dist/composer/examples/pre_listing_classifier.graph.yaml +204 -0
- package/dist/composer/examples/trend_momentum_majors.graph.yaml +133 -0
- package/dist/composer/generated/README.md +22 -0
- package/dist/composer/generated/catalog.md +84 -0
- package/dist/composer/generated/describe.md +703 -0
- package/dist/composer/generated/graph.schema.json +1203 -0
- package/dist/composer/primitives/__init__.py +239 -0
- package/dist/composer/primitives/_candles.py +76 -0
- package/dist/composer/primitives/adapter.py +120 -0
- package/dist/composer/primitives/emitters.py +142 -0
- package/dist/composer/primitives/filters.py +71 -0
- package/dist/composer/primitives/indicators.py +203 -0
- package/dist/composer/primitives/rankers.py +40 -0
- package/dist/composer/primitives/scorers.py +100 -0
- package/dist/composer/primitives/sources.py +405 -0
- package/dist/composer/primitives/stateful.py +52 -0
- package/dist/composer/pure_fn/__init__.py +34 -0
- package/dist/composer/pure_fn/checks.py +39 -0
- package/dist/composer/pure_fn/models.py +177 -0
- package/dist/composer/pure_fn/purity.py +311 -0
- package/dist/composer/pure_fn/runtests.py +155 -0
- package/dist/composer/registry/__init__.py +40 -0
- package/dist/composer/registry/generate.py +422 -0
- package/dist/composer/registry/models.py +331 -0
- package/dist/composer/registry/nodes.py +673 -0
- package/dist/composer/requirements.txt +21 -0
- package/dist/composer/templates/__init__.py +13 -0
- package/dist/composer/templates/scan.py.j2 +31 -0
- package/dist/composer/validator/__init__.py +29 -0
- package/dist/composer/validator/desugar.py +133 -0
- package/dist/composer/validator/errors.py +191 -0
- package/dist/composer/validator/graph_checks.py +348 -0
- package/dist/composer/validator/loader.py +110 -0
- package/dist/composer/validator/schema_checks.py +147 -0
- package/dist/composer/validator/validate.py +86 -0
- package/dist/composer/verbs/__init__.py +33 -0
- package/dist/composer/verbs/check.py +193 -0
- package/dist/composer/verbs/deploy.py +223 -0
- package/dist/composer/verbs/docs.py +30 -0
- package/dist/composer/verbs/runtime_validate.py +262 -0
- package/dist/composer/verbs/smoke.py +115 -0
- package/dist/composer/verbs/status.py +205 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -9
- package/dist/index.js.map +1 -1
- package/dist/runtime-api/config.d.ts +2 -2
- package/dist/runtime-api/config.js +4 -4
- package/dist/runtime-api/config.js.map +1 -1
- package/dist/runtime-api/handlers/ingest-signals.d.ts +3 -5
- package/dist/runtime-api/handlers/ingest-signals.d.ts.map +1 -1
- package/dist/runtime-api/handlers/ingest-signals.js +5 -14
- package/dist/runtime-api/handlers/ingest-signals.js.map +1 -1
- package/dist/runtime-api/intake/intake-mount.d.ts.map +1 -1
- package/dist/runtime-api/intake/intake-mount.js +2 -8
- package/dist/runtime-api/intake/intake-mount.js.map +1 -1
- package/dist/skills-manager/manifest.js +1 -1
- package/dist/skills-manager/manifest.js.map +1 -1
- package/dist/skills-manager/skills-manifest.json +1 -1
- package/package.json +4 -2
- package/dist/runtime-api/intake/ingest-mutex.d.ts +0 -16
- package/dist/runtime-api/intake/ingest-mutex.d.ts.map +0 -1
- package/dist/runtime-api/intake/ingest-mutex.js +0 -18
- package/dist/runtime-api/intake/ingest-mutex.js.map +0 -1
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""indicators — pure per-asset indicator primitives (candles -> feature_map).
|
|
2
|
+
|
|
3
|
+
Each function takes the ``candles`` port value (``{asset: {interval: [candle]}}``)
|
|
4
|
+
plus the node's registry params, and returns one feature_map per declared output
|
|
5
|
+
port (``{asset: value}``). Pure compute, no I/O.
|
|
6
|
+
|
|
7
|
+
Convention (compiler + goldens rely on it): an asset with INSUFFICIENT data for the
|
|
8
|
+
indicator is OMITTED from the returned map(s). A downstream required gate that names
|
|
9
|
+
this feature then fails for that asset (missing key -> not truthy), which reproduces
|
|
10
|
+
the corpus originals' "return None -> no signal" behaviour without special-casing.
|
|
11
|
+
|
|
12
|
+
Semantics are ported from the corpus originals under
|
|
13
|
+
``/Users/duncan/Senpi/skills/strategies/{stag,hawk}/main/scanners/scoring.py``
|
|
14
|
+
(cited per function). The per-primitive golden vectors WE author define correctness.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from ._candles import _closes, _high, _low, _pct_change, _vol
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def sma(candles: dict, *, period: int, interval: str) -> tuple[dict, dict]:
|
|
23
|
+
"""SMA of close + a close>SMA flag. Ports: value (feature_map), above (feature_map).
|
|
24
|
+
|
|
25
|
+
Ported from stag ``scoring.sma`` / ``is_above_sma``: mean of the last ``period``
|
|
26
|
+
closes; ``above`` is latest_close > SMA. Assets with < ``period`` closes are omitted.
|
|
27
|
+
"""
|
|
28
|
+
value: dict = {}
|
|
29
|
+
above: dict = {}
|
|
30
|
+
for asset in sorted(candles):
|
|
31
|
+
closes = _closes(candles[asset].get(interval, []))
|
|
32
|
+
if len(closes) < period:
|
|
33
|
+
continue
|
|
34
|
+
window = closes[-period:]
|
|
35
|
+
s = sum(window) / period
|
|
36
|
+
value[asset] = s
|
|
37
|
+
above[asset] = closes[-1] > s
|
|
38
|
+
return value, above
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def pct_change(candles: dict, *, lookback: int, interval: str) -> dict:
|
|
42
|
+
"""Percent change of close over ``lookback`` bars. Port: pct (feature_map).
|
|
43
|
+
|
|
44
|
+
Ported from stag ``scoring.pct_change`` (7d trend %). Assets with <= ``lookback``
|
|
45
|
+
closes, or a non-positive reference price, are omitted.
|
|
46
|
+
"""
|
|
47
|
+
out: dict = {}
|
|
48
|
+
for asset in sorted(candles):
|
|
49
|
+
closes = _closes(candles[asset].get(interval, []))
|
|
50
|
+
pct = _pct_change(closes, lookback)
|
|
51
|
+
if pct is not None:
|
|
52
|
+
out[asset] = pct
|
|
53
|
+
return out
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def recent_high_bars_ago(candles: dict, *, window: int, interval: str) -> dict:
|
|
57
|
+
"""Bars since the highest close in the window. Port: bars_ago (feature_map).
|
|
58
|
+
|
|
59
|
+
Ported from stag ``scoring.recent_high_bars_ago`` (fresh-high freshness check;
|
|
60
|
+
``window`` maps to the original ``lookback``): 0 = the latest bar is the high.
|
|
61
|
+
Assets with <= ``window`` closes are omitted.
|
|
62
|
+
"""
|
|
63
|
+
out: dict = {}
|
|
64
|
+
for asset in sorted(candles):
|
|
65
|
+
closes = _closes(candles[asset].get(interval, []))
|
|
66
|
+
if len(closes) <= window:
|
|
67
|
+
continue
|
|
68
|
+
win = closes[-(window + 1):]
|
|
69
|
+
high_idx = max(range(len(win)), key=lambda i: win[i])
|
|
70
|
+
out[asset] = len(win) - 1 - high_idx
|
|
71
|
+
return out
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def volume_surge_ratio(candles: dict, *, recent_window: int, baseline_window: int, interval: str) -> dict:
|
|
75
|
+
"""mean(recent volumes) / mean(baseline volumes). Port: ratio (feature_map).
|
|
76
|
+
|
|
77
|
+
Unifies stag ``scoring.volume_surge`` (ratio part), hawk ``volume_ratio`` and
|
|
78
|
+
bison ``volume_trend`` into one parameterized primitive. Assets with < baseline
|
|
79
|
+
volumes, or a non-positive baseline mean, are omitted.
|
|
80
|
+
"""
|
|
81
|
+
out: dict = {}
|
|
82
|
+
for asset in sorted(candles):
|
|
83
|
+
vols = [_vol(c) for c in candles[asset].get(interval, [])]
|
|
84
|
+
if len(vols) < baseline_window:
|
|
85
|
+
continue
|
|
86
|
+
recent = vols[-recent_window:]
|
|
87
|
+
baseline = vols[-baseline_window:]
|
|
88
|
+
rmean = sum(recent) / len(recent) if recent else 0.0
|
|
89
|
+
bmean = sum(baseline) / len(baseline) if baseline else 0.0
|
|
90
|
+
if bmean <= 0:
|
|
91
|
+
continue
|
|
92
|
+
out[asset] = rmean / bmean
|
|
93
|
+
return out
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def acceleration(candles: dict, *, short_window: int, long_window: int, interval: str) -> dict:
|
|
97
|
+
"""Whether the short-window move is >= half the long-window move. Port: accelerating.
|
|
98
|
+
|
|
99
|
+
Ported from stag ``scoring.is_accelerating`` composed with ``pct_change``: the
|
|
100
|
+
recent half is keeping pace or faster, and the long move is positive (LONG-bias).
|
|
101
|
+
Assets where either move is uncomputable are omitted.
|
|
102
|
+
"""
|
|
103
|
+
out: dict = {}
|
|
104
|
+
for asset in sorted(candles):
|
|
105
|
+
closes = _closes(candles[asset].get(interval, []))
|
|
106
|
+
short_move = _pct_change(closes, short_window)
|
|
107
|
+
long_move = _pct_change(closes, long_window)
|
|
108
|
+
if short_move is None or long_move is None:
|
|
109
|
+
continue
|
|
110
|
+
out[asset] = bool(long_move > 0 and short_move >= (long_move / 2.0))
|
|
111
|
+
return out
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def trend_structure(candles: dict, *, lookback: int, interval: str) -> dict:
|
|
115
|
+
"""Higher-lows / lower-highs structure. Port: direction (feature_map).
|
|
116
|
+
|
|
117
|
+
Ported VERBATIM from hawk ``scoring.trend_4h`` (the corpus' single most-duplicated
|
|
118
|
+
indicator): strict higher-low / lower-high counting, gated at ``>= (lookback-1)*0.6``.
|
|
119
|
+
Emits the corpus' BULLISH / BEARISH / NEUTRAL vocabulary (a deliberate deviation
|
|
120
|
+
from the registry prose's "LONG/SHORT/NEUTRAL": keeping this distinct from a trade
|
|
121
|
+
DIRECTION lets a graph wire both breakout_detect.direction AND trend_structure into
|
|
122
|
+
one scorer without the direction detector confusing the two). Assets with < lookback
|
|
123
|
+
candles are omitted.
|
|
124
|
+
"""
|
|
125
|
+
out: dict = {}
|
|
126
|
+
for asset in sorted(candles):
|
|
127
|
+
series = candles[asset].get(interval, [])
|
|
128
|
+
if len(series) < lookback:
|
|
129
|
+
continue
|
|
130
|
+
lows = [_low(c) for c in series[-lookback:]]
|
|
131
|
+
highs = [_high(c) for c in series[-lookback:]]
|
|
132
|
+
higher_lows = sum(1 for i in range(1, len(lows)) if lows[i] > lows[i - 1])
|
|
133
|
+
lower_highs = sum(1 for i in range(1, len(highs)) if highs[i] < highs[i - 1])
|
|
134
|
+
total = lookback - 1
|
|
135
|
+
if higher_lows >= total * 0.6:
|
|
136
|
+
out[asset] = "BULLISH"
|
|
137
|
+
elif lower_highs >= total * 0.6:
|
|
138
|
+
out[asset] = "BEARISH"
|
|
139
|
+
else:
|
|
140
|
+
out[asset] = "NEUTRAL"
|
|
141
|
+
return out
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def rsi(candles: dict, *, period: int, interval: str) -> dict:
|
|
145
|
+
"""Relative Strength Index over the last ``period`` bars. Port: rsi (feature_map).
|
|
146
|
+
|
|
147
|
+
Ported VERBATIM from bison ``scoring.calc_rsi`` / thesis-fund ``scoring.calc_rsi``
|
|
148
|
+
(both use the trailing-window variant: the LAST ``period`` gains/losses). ``avg_l == 0``
|
|
149
|
+
-> 100.0. Assets with < ``period + 1`` closes are omitted (the corpus returns a neutral
|
|
150
|
+
50 there; omission lets a downstream consumer supply its own default, per this module's
|
|
151
|
+
insufficient-data convention).
|
|
152
|
+
"""
|
|
153
|
+
out: dict = {}
|
|
154
|
+
for asset in sorted(candles):
|
|
155
|
+
closes = _closes(candles[asset].get(interval, []))
|
|
156
|
+
if len(closes) < period + 1:
|
|
157
|
+
continue
|
|
158
|
+
gains: list = []
|
|
159
|
+
losses: list = []
|
|
160
|
+
for i in range(1, len(closes)):
|
|
161
|
+
d = closes[i] - closes[i - 1]
|
|
162
|
+
gains.append(max(0.0, d))
|
|
163
|
+
losses.append(max(0.0, -d))
|
|
164
|
+
g = gains[-period:]
|
|
165
|
+
l = losses[-period:]
|
|
166
|
+
avg_g = sum(g) / period
|
|
167
|
+
avg_l = sum(l) / period
|
|
168
|
+
if avg_l == 0:
|
|
169
|
+
out[asset] = 100.0
|
|
170
|
+
else:
|
|
171
|
+
out[asset] = 100.0 - (100.0 / (1.0 + avg_g / avg_l))
|
|
172
|
+
return out
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def breakout_detect(candles: dict, *, window: int, interval: str) -> dict:
|
|
176
|
+
"""Directional breakout of the prior-window close high/low. Port: direction.
|
|
177
|
+
|
|
178
|
+
Ported from hawk ``scoring.detect_breakout``: LONG if the latest close breaks the
|
|
179
|
+
max of the PRIOR ``window`` closes (the latest bar excluded from its own range),
|
|
180
|
+
SHORT if it breaks the min, else NEUTRAL. Emits LONG / SHORT / NEUTRAL (a trade
|
|
181
|
+
direction; the scorer's direction detector reads it). Assets with < window+1
|
|
182
|
+
closes, or a non-positive latest close, are omitted.
|
|
183
|
+
"""
|
|
184
|
+
out: dict = {}
|
|
185
|
+
for asset in sorted(candles):
|
|
186
|
+
series = candles[asset].get(interval, [])
|
|
187
|
+
if len(series) < window + 1:
|
|
188
|
+
continue
|
|
189
|
+
win = series[-window:]
|
|
190
|
+
closes = _closes(win)
|
|
191
|
+
latest_close = closes[-1]
|
|
192
|
+
prior = closes[:-1]
|
|
193
|
+
if not prior or latest_close <= 0:
|
|
194
|
+
continue
|
|
195
|
+
high = max(prior)
|
|
196
|
+
low = min(prior)
|
|
197
|
+
if latest_close > high:
|
|
198
|
+
out[asset] = "LONG"
|
|
199
|
+
elif latest_close < low:
|
|
200
|
+
out[asset] = "SHORT"
|
|
201
|
+
else:
|
|
202
|
+
out[asset] = "NEUTRAL"
|
|
203
|
+
return out
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""rankers — selection primitives over a score_map.
|
|
2
|
+
|
|
3
|
+
``emit_single_best`` is the stag/hawk/bison selector: sort descending, keep the top
|
|
4
|
+
one at/above the floor. Ported from stag/hawk ``candidates.sort(..., reverse=True)[0]``.
|
|
5
|
+
``rank_pool_cap_to_open_slots`` is thesis-fund's rank-the-pool-then-cap selector: sort the
|
|
6
|
+
whole confirming pool descending and take the top ``max_slots - held`` — the one corpus
|
|
7
|
+
strategy that is not single-best.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def emit_single_best(scores: dict, *, min_score: float) -> dict:
|
|
14
|
+
"""Select the single highest-scoring candidate at/above ``min_score``. Port: selected.
|
|
15
|
+
|
|
16
|
+
Deterministic tie-break: highest ``score``, then asset name ascending. Returns a
|
|
17
|
+
score_map with at most one entry (``{}`` when nothing clears the floor).
|
|
18
|
+
"""
|
|
19
|
+
eligible = [(a, e) for a, e in scores.items() if e.get("score", 0) >= min_score]
|
|
20
|
+
if not eligible:
|
|
21
|
+
return {}
|
|
22
|
+
# highest score first; ascending asset name as the deterministic tie-break.
|
|
23
|
+
eligible.sort(key=lambda item: (-item[1].get("score", 0), item[0]))
|
|
24
|
+
asset, entry = eligible[0]
|
|
25
|
+
return {asset: entry}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def rank_pool_cap_to_open_slots(scores: dict, held: list, *, max_slots: int, min_score: float) -> dict:
|
|
29
|
+
"""Rank the confirming pool and cap emissions to the open slots. Port: selected.
|
|
30
|
+
|
|
31
|
+
Ported from thesis-fund ``scan.scan``: ``open_slots = max(0, max_slots - len(held))``;
|
|
32
|
+
sort all candidates at/above ``min_score`` by score desc (asset name asc tie-break) and
|
|
33
|
+
keep the top ``open_slots``. When every slot is already taken (open_slots == 0) the pool
|
|
34
|
+
is ranked but NOTHING is selected — the recon's "pool ranked but all open slots taken"
|
|
35
|
+
case. Returns a score_map with 0..open_slots entries.
|
|
36
|
+
"""
|
|
37
|
+
eligible = [(a, e) for a, e in scores.items() if e.get("score", 0) >= min_score]
|
|
38
|
+
eligible.sort(key=lambda item: (-item[1].get("score", 0), item[0]))
|
|
39
|
+
open_slots = max(0, int(max_slots) - len(held or []))
|
|
40
|
+
return {a: e for a, e in eligible[:open_slots]}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""scorers — the weighted-sum-with-gates scorer primitive + the merge helper.
|
|
2
|
+
|
|
3
|
+
The corpus scorers are all "weighted sum + reasons[]" at the core, differing only in
|
|
4
|
+
the gate wrapper. ``hard_gates_all`` is the stag/hawk pattern (a set of hard gates,
|
|
5
|
+
then a weighted score with a min-score floor). Correctness is defined by the goldens
|
|
6
|
+
WE author (the graph re-expresses the strategy via registry primitives; it is not a
|
|
7
|
+
bit-transcription of stag's ``parabolic_score`` — see the POC plan slice-3 note).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def merge_features(feature_maps: dict) -> dict:
|
|
14
|
+
"""Merge several feature_maps into one per-asset record keyed by SOURCE NODE ID.
|
|
15
|
+
|
|
16
|
+
``feature_maps`` = ``{node_id: {asset: value}}`` (the compiler passes the wired
|
|
17
|
+
producers). Returns ``{asset: {node_id: value}}`` over the union of assets. Keying
|
|
18
|
+
by node id (not port name) is collision-free even when two producers share a port
|
|
19
|
+
name (e.g. breakout_detect.direction and trend_structure.direction), and it is what
|
|
20
|
+
a graph's ``required_gates`` / ``weights`` reference.
|
|
21
|
+
"""
|
|
22
|
+
assets: set = set()
|
|
23
|
+
for fm in feature_maps.values():
|
|
24
|
+
assets.update(fm.keys())
|
|
25
|
+
merged: dict = {}
|
|
26
|
+
for asset in sorted(assets):
|
|
27
|
+
rec: dict = {}
|
|
28
|
+
for node_id in sorted(feature_maps):
|
|
29
|
+
fm = feature_maps[node_id]
|
|
30
|
+
if asset in fm:
|
|
31
|
+
rec[node_id] = fm[asset]
|
|
32
|
+
merged[asset] = rec
|
|
33
|
+
return merged
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _truthy(value) -> bool:
|
|
37
|
+
"""Gate truthiness: a decisive, present feature. bool -> itself; number -> > 0;
|
|
38
|
+
str -> a decisive direction (not '' / 'NEUTRAL'); missing/None -> False."""
|
|
39
|
+
if isinstance(value, bool):
|
|
40
|
+
return value
|
|
41
|
+
if isinstance(value, (int, float)):
|
|
42
|
+
return value > 0
|
|
43
|
+
if isinstance(value, str):
|
|
44
|
+
return value.strip().upper() not in ("", "NEUTRAL")
|
|
45
|
+
return False
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _num(value) -> float:
|
|
49
|
+
"""Scoring coercion: bool -> 1/0; number -> itself; decisive str -> 1.0 else 0.0;
|
|
50
|
+
missing/None -> 0.0."""
|
|
51
|
+
if isinstance(value, bool):
|
|
52
|
+
return 1.0 if value else 0.0
|
|
53
|
+
if isinstance(value, (int, float)):
|
|
54
|
+
return float(value)
|
|
55
|
+
if isinstance(value, str):
|
|
56
|
+
return 1.0 if _truthy(value) else 0.0
|
|
57
|
+
return 0.0
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _detect_direction(rec: dict) -> str:
|
|
61
|
+
"""A candidate's trade direction = the unique feature whose value is a trade
|
|
62
|
+
direction ('LONG'/'SHORT'). None or ambiguous -> 'LONG' (LONG-only default)."""
|
|
63
|
+
dirs = {
|
|
64
|
+
v.strip().upper()
|
|
65
|
+
for v in rec.values()
|
|
66
|
+
if isinstance(v, str) and v.strip().upper() in ("LONG", "SHORT")
|
|
67
|
+
}
|
|
68
|
+
return dirs.pop() if len(dirs) == 1 else "LONG"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def hard_gates_all(features: dict, *, required_gates: list, weights: dict, min_score: float) -> dict:
|
|
72
|
+
"""Require every named gate, then score survivors by a weighted sum. Port: scores.
|
|
73
|
+
|
|
74
|
+
``features`` = merged ``{asset: {node_id: value}}``. For each asset: every key in
|
|
75
|
+
``required_gates`` must be truthy; the score is ``sum(weights[k] * num(features[k]))``
|
|
76
|
+
over the (sorted) weight keys; keep the asset iff score >= ``min_score``. Emits a
|
|
77
|
+
``score_map`` = ``{asset: {score, direction, reasons[], features}}``.
|
|
78
|
+
"""
|
|
79
|
+
out: dict = {}
|
|
80
|
+
for asset in sorted(features):
|
|
81
|
+
rec = features[asset]
|
|
82
|
+
if not all(_truthy(rec.get(g)) for g in required_gates):
|
|
83
|
+
continue
|
|
84
|
+
score = 0.0
|
|
85
|
+
reasons: list = []
|
|
86
|
+
for gate in required_gates:
|
|
87
|
+
reasons.append(f"gate:{gate}")
|
|
88
|
+
for key in sorted(weights):
|
|
89
|
+
contribution = weights[key] * _num(rec.get(key))
|
|
90
|
+
score += contribution
|
|
91
|
+
reasons.append(f"{key}={round(contribution, 4)}")
|
|
92
|
+
if score < min_score:
|
|
93
|
+
continue
|
|
94
|
+
out[asset] = {
|
|
95
|
+
"score": round(score, 6),
|
|
96
|
+
"direction": _detect_direction(rec),
|
|
97
|
+
"reasons": reasons,
|
|
98
|
+
"features": dict(rec),
|
|
99
|
+
}
|
|
100
|
+
return out
|