@dsh-ft/dsh-fft-paper-trading 0.7.1 → 0.7.2
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/lib/client.js +1 -1
- package/package.json +1 -4
- package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +0 -611
- package/node_modules/@ftshare-lab/dsh-kline/LICENSE +0 -21
- package/node_modules/@ftshare-lab/dsh-kline/PROVENANCE.md +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/README.en.md +0 -171
- package/node_modules/@ftshare-lab/dsh-kline/README.md +0 -171
- package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +0 -687
- package/node_modules/@ftshare-lab/dsh-kline/config/basic-symbols.json +0 -570
- package/node_modules/@ftshare-lab/dsh-kline/config/dsh-kline.patch.yml +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/config/dsh-tool-catalog.json +0 -3875
- package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +0 -33
- package/node_modules/@ftshare-lab/dsh-kline/core/__init__.py +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/core/adjustment.py +0 -16
- package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +0 -691
- package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +0 -228
- package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +0 -99
- package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +0 -15
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-adjustment.js +0 -7
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +0 -33
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +0 -171
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +0 -164
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +0 -251
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-service-status.js +0 -82
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-source-status.js +0 -39
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +0 -354
- package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +0 -17581
- package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +0 -284
- package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +0 -18
- package/node_modules/@ftshare-lab/dsh-kline/lib/ftshare-settings-bridge.js +0 -159
- package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +0 -279
- package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +0 -17
- package/node_modules/@ftshare-lab/dsh-kline/lib/pattern-groups.js +0 -91
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-bands.js +0 -55
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-series.js +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-sticks.js +0 -32
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/candle-sequence.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-adjustment.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-annotations.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-applications.d.ts +0 -26
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-context.d.ts +0 -14
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-observation.d.ts +0 -8
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-service-status.d.ts +0 -22
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-source-status.d.ts +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-sources.d.ts +0 -25
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/BetterSidebarTab.d.ts +0 -12
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ClassicShell.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/KlineContent.d.ts +0 -37
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/PanelHost.d.ts +0 -25
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-apply.d.ts +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +0 -23
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-handoff.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-session-resolver.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +0 -16
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +0 -43
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/default-tab.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/embed.d.ts +0 -37
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/horizontal-lines.d.ts +0 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-options.d.ts +0 -38
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-panels.d.ts +0 -55
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/mode-preferences.d.ts +0 -25
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +0 -52
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +0 -46
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +0 -45
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/sidebar-integration.d.ts +0 -12
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ui-onboarding.d.ts +0 -7
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/version.d.ts +0 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/drawing-feedback.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/ftshare-settings-bridge.d.ts +0 -50
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/index.d.ts +0 -26
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +0 -11
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/pattern-groups.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/package.json +0 -157
- package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +0 -6
- package/node_modules/@ftshare-lab/dsh-kline/scripts/bootstrap.sh +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-bootstrap.mjs +0 -179
- package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +0 -27
- package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +0 -658
- package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.sh +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/server.py +0 -1755
- package/node_modules/@ftshare-lab/dsh-kline/tools/__init__.py +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +0 -119
- package/node_modules/@ftshare-lab/dsh-kline/tools/automatic_analysis.py +0 -158
- package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +0 -176
- package/node_modules/@ftshare-lab/dsh-kline/tools/calc.py +0 -39
- package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +0 -260
- package/node_modules/@ftshare-lab/dsh-kline/tools/channel_preview.py +0 -82
- package/node_modules/@ftshare-lab/dsh-kline/tools/channels.py +0 -104
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +0 -204
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +0 -186
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +0 -363
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +0 -451
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +0 -65
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_measurements.py +0 -84
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_source_status.py +0 -32
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_sources.py +0 -31
- package/node_modules/@ftshare-lab/dsh-kline/tools/closed_daily.py +0 -68
- package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +0 -410
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +0 -45
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +0 -117
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +0 -141
- package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +0 -4680
- package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +0 -83
- package/node_modules/@ftshare-lab/dsh-kline/tools/foreign_daily.py +0 -185
- package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +0 -483
- package/node_modules/@ftshare-lab/dsh-kline/tools/lines.py +0 -91
- package/node_modules/@ftshare-lab/dsh-kline/tools/nine_count.py +0 -66
- package/node_modules/@ftshare-lab/dsh-kline/tools/pattern_groups.py +0 -103
- package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +0 -60
- package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +0 -131
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +0 -165
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_patterns.py +0 -311
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +0 -162
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +0 -114
- package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +0 -170
- package/node_modules/@ftshare-lab/dsh-kline/tools/recent_drawing_candidates.py +0 -123
- package/node_modules/@ftshare-lab/dsh-kline/tools/rectangles.py +0 -76
- package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +0 -87
- package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +0 -228
- package/node_modules/@ftshare-lab/dsh-kline/tools/trend_lines.py +0 -106
- package/node_modules/@ftshare-lab/dsh-kline/tools/watchlist.py +0 -149
- package/node_modules/@ftshare-lab/dsh-kline/view/ft-logo.jpg +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/view/vendor/klinecharts.min.js +0 -7
|
@@ -1,691 +0,0 @@
|
|
|
1
|
-
"""Single source of truth for indicators and metrics.
|
|
2
|
-
|
|
3
|
-
Rules (locked):
|
|
4
|
-
- Public API times are unix **seconds**.
|
|
5
|
-
- `calc_metrics` / `draw_kline` share the same functions + same defaults.
|
|
6
|
-
- Summary schemas are stable; full series returned only for chart rendering.
|
|
7
|
-
- No RSI divergence in v1.
|
|
8
|
-
- duration always emits both `duration_bars` and `duration_days` (calendar).
|
|
9
|
-
"""
|
|
10
|
-
|
|
11
|
-
from __future__ import annotations
|
|
12
|
-
|
|
13
|
-
import math
|
|
14
|
-
from typing import Any, Iterable
|
|
15
|
-
|
|
16
|
-
from core.ta_engine import ENGINE_VERSION, NATIVE_VERSION, arrays as _ta_arrays, finite_map as _ta_map, talib
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
# ---------------------------------------------------------------------------
|
|
20
|
-
# Defaults (shared by calc_metrics + draw_kline)
|
|
21
|
-
# ---------------------------------------------------------------------------
|
|
22
|
-
DEFAULT_MA_PERIODS = [5, 10, 20, 30, 60]
|
|
23
|
-
DEFAULT_EMA_PERIOD = 20
|
|
24
|
-
DEFAULT_LOOKBACK = 60
|
|
25
|
-
DEFAULT_TOLERANCE_PCT = 0.5 # support/resistance touch band
|
|
26
|
-
DEFAULT_RSI_PERIOD = 14
|
|
27
|
-
DEFAULT_BOLL_PERIOD = 20
|
|
28
|
-
DEFAULT_BOLL_STD = 2.0
|
|
29
|
-
DEFAULT_ATR_PERIOD = 14
|
|
30
|
-
DEFAULT_VOLUME_MA = 20
|
|
31
|
-
DEFAULT_VOLUME_RATIO = 1.5
|
|
32
|
-
DEFAULT_MACD = (12, 26, 9)
|
|
33
|
-
DEFAULT_KDJ = (9, 3, 3)
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
# ---------------------------------------------------------------------------
|
|
37
|
-
# Helpers
|
|
38
|
-
# ---------------------------------------------------------------------------
|
|
39
|
-
def _finite(v: Any) -> float | None:
|
|
40
|
-
try:
|
|
41
|
-
f = float(v)
|
|
42
|
-
except (TypeError, ValueError):
|
|
43
|
-
return None
|
|
44
|
-
if not math.isfinite(f):
|
|
45
|
-
return None
|
|
46
|
-
return f
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
def _round(v: float | None, n: int = 4) -> float | None:
|
|
50
|
-
if v is None:
|
|
51
|
-
return None
|
|
52
|
-
return round(float(v), n)
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
def _calendar_days(t0: int, t1: int) -> int:
|
|
56
|
-
"""Calendar days between two unix-second timestamps (inclusive-ish span)."""
|
|
57
|
-
if t1 < t0:
|
|
58
|
-
t0, t1 = t1, t0
|
|
59
|
-
return max(0, int((t1 - t0) // 86400))
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
def _closes(rows: list[dict[str, Any]]) -> list[float]:
|
|
63
|
-
return [float(r["close"]) for r in rows]
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
def _highs(rows: list[dict[str, Any]]) -> list[float]:
|
|
67
|
-
return [float(r["high"]) for r in rows]
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
def _lows(rows: list[dict[str, Any]]) -> list[float]:
|
|
71
|
-
return [float(r["low"]) for r in rows]
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
def _volumes(rows: list[dict[str, Any]]) -> list[float]:
|
|
75
|
-
return [float(r.get("volume") or 0.0) for r in rows]
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
def _times(rows: list[dict[str, Any]]) -> list[int]:
|
|
79
|
-
return [int(r["time"]) for r in rows]
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
# ---------------------------------------------------------------------------
|
|
83
|
-
# Full series (used by draw_kline / SET_INDICATOR_SERIES)
|
|
84
|
-
# Keys of returned maps are **seconds** (str for JSON safety optional — we use int keys
|
|
85
|
-
# in python, tools will stringify).
|
|
86
|
-
# ---------------------------------------------------------------------------
|
|
87
|
-
def series_ma(
|
|
88
|
-
rows: list[dict[str, Any]],
|
|
89
|
-
periods: Iterable[int] | None = None,
|
|
90
|
-
) -> dict[str, dict[int, float]]:
|
|
91
|
-
"""Return {f"ma{p}": {time_sec: value}} for each period."""
|
|
92
|
-
periods = list(periods or DEFAULT_MA_PERIODS)
|
|
93
|
-
if not rows:
|
|
94
|
-
return {f"ma{int(p)}": {} for p in periods}
|
|
95
|
-
close = _ta_arrays(rows)["close"]
|
|
96
|
-
return {f"ma{int(p)}": _ta_map(rows, talib.SMA(close, timeperiod=int(p))) for p in periods}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
def series_ema(rows: list[dict[str, Any]], period: int = DEFAULT_EMA_PERIOD) -> dict[int, float]:
|
|
100
|
-
"""Return the TA-Lib EMA(close) series keyed by candle time."""
|
|
101
|
-
if not rows:
|
|
102
|
-
return {}
|
|
103
|
-
return _ta_map(rows, talib.EMA(_ta_arrays(rows)["close"], timeperiod=int(period)))
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
def series_vol_ma(
|
|
107
|
-
rows: list[dict[str, Any]],
|
|
108
|
-
period: int = DEFAULT_VOLUME_MA,
|
|
109
|
-
) -> dict[int, float]:
|
|
110
|
-
if not rows:
|
|
111
|
-
return {}
|
|
112
|
-
volume = _ta_arrays(rows)["volume"]
|
|
113
|
-
return _ta_map(rows, talib.SMA(volume, timeperiod=int(period)), digits=4)
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
def series_macd(
|
|
117
|
-
rows: list[dict[str, Any]],
|
|
118
|
-
fast: int = DEFAULT_MACD[0],
|
|
119
|
-
slow: int = DEFAULT_MACD[1],
|
|
120
|
-
signal: int = DEFAULT_MACD[2],
|
|
121
|
-
) -> dict[str, dict[int, float]]:
|
|
122
|
-
"""TA-Lib MACD; hist is DIF-DEA without the former x2 convention."""
|
|
123
|
-
if not rows:
|
|
124
|
-
return {"dif": {}, "dea": {}, "hist": {}}
|
|
125
|
-
close = _ta_arrays(rows)["close"]
|
|
126
|
-
dif, dea, hist = talib.MACD(close, fastperiod=int(fast), slowperiod=int(slow), signalperiod=int(signal))
|
|
127
|
-
return {"dif": _ta_map(rows, dif), "dea": _ta_map(rows, dea), "hist": _ta_map(rows, hist)}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
def series_kdj(
|
|
131
|
-
rows: list[dict[str, Any]],
|
|
132
|
-
n: int = DEFAULT_KDJ[0],
|
|
133
|
-
m1: int = DEFAULT_KDJ[1],
|
|
134
|
-
m2: int = DEFAULT_KDJ[2],
|
|
135
|
-
) -> dict[str, dict[int, float]]:
|
|
136
|
-
if not rows:
|
|
137
|
-
return {"k": {}, "d": {}, "j": {}}
|
|
138
|
-
values = _ta_arrays(rows)
|
|
139
|
-
k, d, j = talib.KDJ(values["high"], values["low"], values["close"],
|
|
140
|
-
fastk_period=int(n), slowk_period=int(m1), slowk_matype=13,
|
|
141
|
-
slowd_period=int(m2), slowd_matype=13)
|
|
142
|
-
return {"k": _ta_map(rows, k, 4), "d": _ta_map(rows, d, 4), "j": _ta_map(rows, j, 4)}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
def series_boll(
|
|
146
|
-
rows: list[dict[str, Any]],
|
|
147
|
-
period: int = DEFAULT_BOLL_PERIOD,
|
|
148
|
-
std_mult: float = DEFAULT_BOLL_STD,
|
|
149
|
-
) -> dict[str, dict[int, float]]:
|
|
150
|
-
if not rows:
|
|
151
|
-
return {"mid": {}, "upper": {}, "lower": {}}
|
|
152
|
-
close = _ta_arrays(rows)["close"]
|
|
153
|
-
upper, mid, lower = talib.BBANDS(close, timeperiod=int(period), nbdevup=float(std_mult),
|
|
154
|
-
nbdevdn=float(std_mult), matype=0)
|
|
155
|
-
return {"mid": _ta_map(rows, mid), "upper": _ta_map(rows, upper), "lower": _ta_map(rows, lower)}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
def series_rsi(
|
|
159
|
-
rows: list[dict[str, Any]],
|
|
160
|
-
period: int = DEFAULT_RSI_PERIOD,
|
|
161
|
-
) -> dict[int, float]:
|
|
162
|
-
if not rows:
|
|
163
|
-
return {}
|
|
164
|
-
close = _ta_arrays(rows)["close"]
|
|
165
|
-
return _ta_map(rows, talib.RSI(close, timeperiod=int(period)), digits=4)
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
def series_vwap(rows: list[dict[str, Any]]) -> dict[int, float]:
|
|
169
|
-
"""TA-Lib path-dependent VWAP anchored at the first supplied bar."""
|
|
170
|
-
if not rows:
|
|
171
|
-
return {}
|
|
172
|
-
values = _ta_arrays(rows)
|
|
173
|
-
return _ta_map(rows, talib.VWAP(values["high"], values["low"], values["close"], values["volume"]))
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
def series_atr(
|
|
177
|
-
rows: list[dict[str, Any]],
|
|
178
|
-
period: int = DEFAULT_ATR_PERIOD,
|
|
179
|
-
) -> dict[int, float]:
|
|
180
|
-
if not rows:
|
|
181
|
-
return {}
|
|
182
|
-
values = _ta_arrays(rows)
|
|
183
|
-
return _ta_map(rows, talib.ATR(values["high"], values["low"], values["close"], timeperiod=int(period)))
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
# ---------------------------------------------------------------------------
|
|
187
|
-
# Metric summaries (stable schemas for host LLM)
|
|
188
|
-
# ---------------------------------------------------------------------------
|
|
189
|
-
def metric_max_drawdown(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
|
190
|
-
"""Peak-to-trough max drawdown on close series."""
|
|
191
|
-
if not rows:
|
|
192
|
-
return {
|
|
193
|
-
"max_drawdown_pct": None,
|
|
194
|
-
"peak": None,
|
|
195
|
-
"trough": None,
|
|
196
|
-
"duration_bars": 0,
|
|
197
|
-
"duration_days": 0,
|
|
198
|
-
}
|
|
199
|
-
peak_idx = 0
|
|
200
|
-
peak_price = float(rows[0]["close"])
|
|
201
|
-
worst = 0.0
|
|
202
|
-
worst_peak_idx = 0
|
|
203
|
-
worst_trough_idx = 0
|
|
204
|
-
for i, r in enumerate(rows):
|
|
205
|
-
c = float(r["close"])
|
|
206
|
-
if c > peak_price:
|
|
207
|
-
peak_price = c
|
|
208
|
-
peak_idx = i
|
|
209
|
-
if peak_price > 0:
|
|
210
|
-
dd = c / peak_price - 1.0
|
|
211
|
-
if dd < worst:
|
|
212
|
-
worst = dd
|
|
213
|
-
worst_peak_idx = peak_idx
|
|
214
|
-
worst_trough_idx = i
|
|
215
|
-
peak = rows[worst_peak_idx]
|
|
216
|
-
trough = rows[worst_trough_idx]
|
|
217
|
-
t0, t1 = int(peak["time"]), int(trough["time"])
|
|
218
|
-
return {
|
|
219
|
-
"max_drawdown_pct": round(worst * 100.0, 4),
|
|
220
|
-
"peak": {
|
|
221
|
-
"time": t0,
|
|
222
|
-
"price": round(float(peak["close"]), 4),
|
|
223
|
-
"idx": worst_peak_idx,
|
|
224
|
-
},
|
|
225
|
-
"trough": {
|
|
226
|
-
"time": t1,
|
|
227
|
-
"price": round(float(trough["close"]), 4),
|
|
228
|
-
"idx": worst_trough_idx,
|
|
229
|
-
},
|
|
230
|
-
"duration_bars": max(0, worst_trough_idx - worst_peak_idx),
|
|
231
|
-
"duration_days": _calendar_days(t0, t1),
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
def metric_support_resistance(
|
|
236
|
-
rows: list[dict[str, Any]],
|
|
237
|
-
*,
|
|
238
|
-
lookback: int = DEFAULT_LOOKBACK,
|
|
239
|
-
tolerance_pct: float = DEFAULT_TOLERANCE_PCT,
|
|
240
|
-
max_levels: int = 5,
|
|
241
|
-
) -> dict[str, Any]:
|
|
242
|
-
"""Fractal swing highs/lows clustered by tolerance_pct."""
|
|
243
|
-
n = len(rows)
|
|
244
|
-
lookback = max(5, min(int(lookback), n))
|
|
245
|
-
window = rows[-lookback:]
|
|
246
|
-
offset = n - len(window)
|
|
247
|
-
# fractal: local max/min with 2-bar wings
|
|
248
|
-
swings_high: list[tuple[int, float]] = []
|
|
249
|
-
swings_low: list[tuple[int, float]] = []
|
|
250
|
-
for i in range(2, len(window) - 2):
|
|
251
|
-
h = float(window[i]["high"])
|
|
252
|
-
l = float(window[i]["low"])
|
|
253
|
-
if (
|
|
254
|
-
h >= float(window[i - 1]["high"])
|
|
255
|
-
and h >= float(window[i - 2]["high"])
|
|
256
|
-
and h >= float(window[i + 1]["high"])
|
|
257
|
-
and h >= float(window[i + 2]["high"])
|
|
258
|
-
):
|
|
259
|
-
swings_high.append((offset + i, h))
|
|
260
|
-
if (
|
|
261
|
-
l <= float(window[i - 1]["low"])
|
|
262
|
-
and l <= float(window[i - 2]["low"])
|
|
263
|
-
and l <= float(window[i + 1]["low"])
|
|
264
|
-
and l <= float(window[i + 2]["low"])
|
|
265
|
-
):
|
|
266
|
-
swings_low.append((offset + i, l))
|
|
267
|
-
|
|
268
|
-
def cluster(levels: list[tuple[int, float]], *, kind: str) -> list[dict[str, Any]]:
|
|
269
|
-
if not levels:
|
|
270
|
-
return []
|
|
271
|
-
# sort by price
|
|
272
|
-
levels = sorted(levels, key=lambda x: x[1])
|
|
273
|
-
clusters: list[list[tuple[int, float]]] = []
|
|
274
|
-
for idx, price in levels:
|
|
275
|
-
placed = False
|
|
276
|
-
for cl in clusters:
|
|
277
|
-
rep = sum(p for _, p in cl) / len(cl)
|
|
278
|
-
if rep > 0 and abs(price - rep) / rep * 100.0 <= tolerance_pct:
|
|
279
|
-
cl.append((idx, price))
|
|
280
|
-
placed = True
|
|
281
|
-
break
|
|
282
|
-
if not placed:
|
|
283
|
-
clusters.append([(idx, price)])
|
|
284
|
-
out: list[dict[str, Any]] = []
|
|
285
|
-
last_close = float(rows[-1]["close"])
|
|
286
|
-
for cl in clusters:
|
|
287
|
-
prices = [p for _, p in cl]
|
|
288
|
-
idxs = [i for i, _ in cl]
|
|
289
|
-
level = sum(prices) / len(prices)
|
|
290
|
-
# A later bar crossing the level invalidates its original role.
|
|
291
|
-
# Keep historical pivots out of the current support/resistance set.
|
|
292
|
-
later = rows[max(idxs) + 1:]
|
|
293
|
-
if kind == "support" and any(float(r["low"]) < level for r in later):
|
|
294
|
-
continue
|
|
295
|
-
if kind == "resistance" and any(float(r["high"]) > level for r in later):
|
|
296
|
-
continue
|
|
297
|
-
# touches: bars whose high/low within band
|
|
298
|
-
band = level * (tolerance_pct / 100.0)
|
|
299
|
-
touches = 0
|
|
300
|
-
for r in window:
|
|
301
|
-
if kind == "resistance":
|
|
302
|
-
if abs(float(r["high"]) - level) <= band:
|
|
303
|
-
touches += 1
|
|
304
|
-
elif abs(float(r["low"]) - level) <= band:
|
|
305
|
-
touches += 1
|
|
306
|
-
out.append(
|
|
307
|
-
{
|
|
308
|
-
"price": round(level, 4),
|
|
309
|
-
"touches": int(touches),
|
|
310
|
-
"strength": round(min(1.0, touches / 5.0), 3),
|
|
311
|
-
"last_idx": int(max(idxs)),
|
|
312
|
-
"last_time": int(rows[max(idxs)]["time"]),
|
|
313
|
-
"side": "above" if level >= last_close else "below",
|
|
314
|
-
}
|
|
315
|
-
)
|
|
316
|
-
# Rank all candidates first. Side filtering happens before the limit so
|
|
317
|
-
# stale levels cannot consume the five available slots.
|
|
318
|
-
out.sort(key=lambda x: (-x["touches"], abs(x["price"] - last_close)))
|
|
319
|
-
return out
|
|
320
|
-
|
|
321
|
-
last_close = float(rows[-1]["close"])
|
|
322
|
-
supports = [x for x in cluster(swings_low, kind="support") if x["price"] <= last_close][:max_levels]
|
|
323
|
-
resistances = [
|
|
324
|
-
x
|
|
325
|
-
for x in cluster(swings_high, kind="resistance")
|
|
326
|
-
if x["price"] >= last_close
|
|
327
|
-
][:max_levels]
|
|
328
|
-
return {
|
|
329
|
-
"method": "fractal",
|
|
330
|
-
"lookback": lookback,
|
|
331
|
-
"tolerance_pct": float(tolerance_pct),
|
|
332
|
-
"support": supports,
|
|
333
|
-
"resistance": resistances,
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
def metric_ma_cross(
|
|
338
|
-
rows: list[dict[str, Any]],
|
|
339
|
-
*,
|
|
340
|
-
ma_periods: list[int] | None = None,
|
|
341
|
-
) -> dict[str, Any]:
|
|
342
|
-
"""All C(n,2) pairs among ma_periods. Distinguish empty crosses vs not requested.
|
|
343
|
-
|
|
344
|
-
Schema:
|
|
345
|
-
{
|
|
346
|
-
"periods": [5,10,20],
|
|
347
|
-
"pairs": ["5x10","5x20","10x20"],
|
|
348
|
-
"crosses": [{time, idx, type: golden|death, fast, slow, price}],
|
|
349
|
-
"pair_stats": {"5x10": {"cross_count": 0, "last": null}, ...}
|
|
350
|
-
}
|
|
351
|
-
"""
|
|
352
|
-
periods = sorted({int(p) for p in (ma_periods or DEFAULT_MA_PERIODS) if int(p) > 0})
|
|
353
|
-
pairs = [(periods[i], periods[j]) for i in range(len(periods)) for j in range(i + 1, len(periods))]
|
|
354
|
-
pair_keys = [f"{a}x{b}" for a, b in pairs]
|
|
355
|
-
series = series_ma(rows, periods)
|
|
356
|
-
closes = _closes(rows)
|
|
357
|
-
times = _times(rows)
|
|
358
|
-
crosses: list[dict[str, Any]] = []
|
|
359
|
-
pair_stats: dict[str, Any] = {k: {"cross_count": 0, "last": None} for k in pair_keys}
|
|
360
|
-
|
|
361
|
-
for a, b in pairs:
|
|
362
|
-
key = f"{a}x{b}"
|
|
363
|
-
ma_a = series.get(f"ma{a}", {})
|
|
364
|
-
ma_b = series.get(f"ma{b}", {})
|
|
365
|
-
prev_diff: float | None = None
|
|
366
|
-
for i, t in enumerate(times):
|
|
367
|
-
va = ma_a.get(int(t))
|
|
368
|
-
vb = ma_b.get(int(t))
|
|
369
|
-
if va is None or vb is None:
|
|
370
|
-
prev_diff = None
|
|
371
|
-
continue
|
|
372
|
-
diff = va - vb
|
|
373
|
-
# Exact touch (diff==0) carries no cross direction; keep previous sign.
|
|
374
|
-
# Using <=0 / >=0 would phantom-cross on flat MA equalities (limit-up days).
|
|
375
|
-
if diff == 0:
|
|
376
|
-
continue
|
|
377
|
-
if prev_diff is not None:
|
|
378
|
-
# golden: fast crosses above slow (a is faster = smaller period)
|
|
379
|
-
if prev_diff < 0 < diff:
|
|
380
|
-
item = {
|
|
381
|
-
"time": int(t),
|
|
382
|
-
"idx": i,
|
|
383
|
-
"type": "golden",
|
|
384
|
-
"fast": a,
|
|
385
|
-
"slow": b,
|
|
386
|
-
"price": round(closes[i], 4),
|
|
387
|
-
}
|
|
388
|
-
crosses.append(item)
|
|
389
|
-
pair_stats[key]["cross_count"] += 1
|
|
390
|
-
pair_stats[key]["last"] = item
|
|
391
|
-
elif prev_diff > 0 > diff:
|
|
392
|
-
item = {
|
|
393
|
-
"time": int(t),
|
|
394
|
-
"idx": i,
|
|
395
|
-
"type": "death",
|
|
396
|
-
"fast": a,
|
|
397
|
-
"slow": b,
|
|
398
|
-
"price": round(closes[i], 4),
|
|
399
|
-
}
|
|
400
|
-
crosses.append(item)
|
|
401
|
-
pair_stats[key]["cross_count"] += 1
|
|
402
|
-
pair_stats[key]["last"] = item
|
|
403
|
-
prev_diff = diff
|
|
404
|
-
|
|
405
|
-
crosses.sort(key=lambda x: x["time"])
|
|
406
|
-
return {
|
|
407
|
-
"periods": periods,
|
|
408
|
-
"pairs": pair_keys,
|
|
409
|
-
"crosses": crosses,
|
|
410
|
-
"pair_stats": pair_stats,
|
|
411
|
-
# Convenience: empty crosses means computed but none found (pairs non-empty).
|
|
412
|
-
# Missing pair key in pair_stats would mean "not computed" — we always fill all pairs.
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
def metric_volume_breakout(
|
|
417
|
-
rows: list[dict[str, Any]],
|
|
418
|
-
*,
|
|
419
|
-
volume_ma: int = DEFAULT_VOLUME_MA,
|
|
420
|
-
volume_ratio: float = DEFAULT_VOLUME_RATIO,
|
|
421
|
-
ma_period: int = 20,
|
|
422
|
-
) -> dict[str, Any]:
|
|
423
|
-
"""Volume spike + close cross above/below MA."""
|
|
424
|
-
times = _times(rows)
|
|
425
|
-
closes = _closes(rows)
|
|
426
|
-
vols = _volumes(rows)
|
|
427
|
-
ma_map = series_ma(rows, [ma_period]).get(f"ma{ma_period}", {})
|
|
428
|
-
vol_ma_map = series_vol_ma(rows, volume_ma)
|
|
429
|
-
events: list[dict[str, Any]] = []
|
|
430
|
-
for i in range(1, len(rows)):
|
|
431
|
-
t = int(times[i])
|
|
432
|
-
t_prev = int(times[i - 1])
|
|
433
|
-
ma = ma_map.get(t)
|
|
434
|
-
ma_prev = ma_map.get(t_prev)
|
|
435
|
-
vma = vol_ma_map.get(t)
|
|
436
|
-
if ma is None or ma_prev is None or not vma or vma <= 0:
|
|
437
|
-
continue
|
|
438
|
-
ratio = vols[i] / vma
|
|
439
|
-
if ratio < volume_ratio:
|
|
440
|
-
continue
|
|
441
|
-
c, c_prev = closes[i], closes[i - 1]
|
|
442
|
-
direction = None
|
|
443
|
-
if c_prev <= ma_prev and c > ma:
|
|
444
|
-
direction = "breakout_up"
|
|
445
|
-
elif c_prev >= ma_prev and c < ma:
|
|
446
|
-
direction = "breakdown"
|
|
447
|
-
if not direction:
|
|
448
|
-
continue
|
|
449
|
-
events.append(
|
|
450
|
-
{
|
|
451
|
-
"time": t,
|
|
452
|
-
"idx": i,
|
|
453
|
-
"price": round(c, 4),
|
|
454
|
-
"ma": round(ma, 4),
|
|
455
|
-
"volume": round(vols[i], 2),
|
|
456
|
-
"volume_ma": round(vma, 2),
|
|
457
|
-
"volume_ratio": round(ratio, 3),
|
|
458
|
-
"direction": direction,
|
|
459
|
-
"ma_period": ma_period,
|
|
460
|
-
}
|
|
461
|
-
)
|
|
462
|
-
return {
|
|
463
|
-
"volume_ma": int(volume_ma),
|
|
464
|
-
"volume_ratio": float(volume_ratio),
|
|
465
|
-
"ma_period": int(ma_period),
|
|
466
|
-
"events": events,
|
|
467
|
-
"count": len(events),
|
|
468
|
-
}
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
def metric_bollinger(
|
|
472
|
-
rows: list[dict[str, Any]],
|
|
473
|
-
*,
|
|
474
|
-
period: int = DEFAULT_BOLL_PERIOD,
|
|
475
|
-
std_mult: float = DEFAULT_BOLL_STD,
|
|
476
|
-
) -> dict[str, Any]:
|
|
477
|
-
series = series_boll(rows, period=period, std_mult=std_mult)
|
|
478
|
-
last_t = int(rows[-1]["time"])
|
|
479
|
-
last_c = float(rows[-1]["close"])
|
|
480
|
-
mid = series["mid"].get(last_t)
|
|
481
|
-
upper = series["upper"].get(last_t)
|
|
482
|
-
lower = series["lower"].get(last_t)
|
|
483
|
-
width_pct = None
|
|
484
|
-
pct_b = None
|
|
485
|
-
if mid is not None and upper is not None and lower is not None and upper != lower and mid != 0:
|
|
486
|
-
width_pct = round((upper - lower) / mid * 100.0, 4)
|
|
487
|
-
pct_b = round((last_c - lower) / (upper - lower), 4)
|
|
488
|
-
return {
|
|
489
|
-
"period": int(period),
|
|
490
|
-
"std_mult": float(std_mult),
|
|
491
|
-
"last": {
|
|
492
|
-
"time": last_t,
|
|
493
|
-
"close": round(last_c, 4),
|
|
494
|
-
"mid": _round(mid),
|
|
495
|
-
"upper": _round(upper),
|
|
496
|
-
"lower": _round(lower),
|
|
497
|
-
"width_pct": width_pct,
|
|
498
|
-
"pct_b": pct_b,
|
|
499
|
-
},
|
|
500
|
-
}
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
def metric_rsi(
|
|
504
|
-
rows: list[dict[str, Any]],
|
|
505
|
-
*,
|
|
506
|
-
period: int = DEFAULT_RSI_PERIOD,
|
|
507
|
-
) -> dict[str, Any]:
|
|
508
|
-
"""RSI summary. No divergence in v1."""
|
|
509
|
-
s = series_rsi(rows, period=period)
|
|
510
|
-
if not s:
|
|
511
|
-
return {"period": int(period), "last": None, "overbought": [], "oversold": []}
|
|
512
|
-
last_t = max(s)
|
|
513
|
-
last_v = s[last_t]
|
|
514
|
-
overbought = [
|
|
515
|
-
{"time": t, "value": v} for t, v in s.items() if v >= 70
|
|
516
|
-
][-10:]
|
|
517
|
-
oversold = [
|
|
518
|
-
{"time": t, "value": v} for t, v in s.items() if v <= 30
|
|
519
|
-
][-10:]
|
|
520
|
-
return {
|
|
521
|
-
"period": int(period),
|
|
522
|
-
"last": {"time": int(last_t), "value": last_v},
|
|
523
|
-
"overbought": overbought,
|
|
524
|
-
"oversold": oversold,
|
|
525
|
-
# divergence intentionally omitted in v1
|
|
526
|
-
}
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
def metric_atr(
|
|
530
|
-
rows: list[dict[str, Any]],
|
|
531
|
-
*,
|
|
532
|
-
period: int = DEFAULT_ATR_PERIOD,
|
|
533
|
-
) -> dict[str, Any]:
|
|
534
|
-
s = series_atr(rows, period=period)
|
|
535
|
-
if not s:
|
|
536
|
-
return {"period": int(period), "last": None, "atr_pct": None}
|
|
537
|
-
last_t = max(s)
|
|
538
|
-
last_atr = s[last_t]
|
|
539
|
-
last_c = float(rows[-1]["close"])
|
|
540
|
-
atr_pct = round(last_atr / last_c * 100.0, 4) if last_c else None
|
|
541
|
-
return {
|
|
542
|
-
"period": int(period),
|
|
543
|
-
"last": {"time": int(last_t), "value": last_atr},
|
|
544
|
-
"atr_pct": atr_pct,
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
# ---------------------------------------------------------------------------
|
|
549
|
-
# Public aggregators
|
|
550
|
-
# ---------------------------------------------------------------------------
|
|
551
|
-
AVAILABLE_METRICS = (
|
|
552
|
-
"max_drawdown",
|
|
553
|
-
"support_resistance",
|
|
554
|
-
"ma_cross",
|
|
555
|
-
"volume_breakout",
|
|
556
|
-
"bollinger",
|
|
557
|
-
"rsi",
|
|
558
|
-
"atr",
|
|
559
|
-
)
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
def calc_metrics(
|
|
563
|
-
rows: list[dict[str, Any]],
|
|
564
|
-
metrics: list[str] | None = None,
|
|
565
|
-
*,
|
|
566
|
-
lookback: int = DEFAULT_LOOKBACK,
|
|
567
|
-
ma_periods: list[int] | None = None,
|
|
568
|
-
tolerance_pct: float = DEFAULT_TOLERANCE_PCT,
|
|
569
|
-
rsi_period: int = DEFAULT_RSI_PERIOD,
|
|
570
|
-
boll_period: int = DEFAULT_BOLL_PERIOD,
|
|
571
|
-
boll_std: float = DEFAULT_BOLL_STD,
|
|
572
|
-
atr_period: int = DEFAULT_ATR_PERIOD,
|
|
573
|
-
volume_ma: int = DEFAULT_VOLUME_MA,
|
|
574
|
-
volume_ratio: float = DEFAULT_VOLUME_RATIO,
|
|
575
|
-
) -> dict[str, Any]:
|
|
576
|
-
"""Compute selected metric **summaries** (no full series)."""
|
|
577
|
-
wanted = list(metrics or list(AVAILABLE_METRICS))
|
|
578
|
-
# preserve order, drop unknown
|
|
579
|
-
ordered = [m for m in wanted if m in AVAILABLE_METRICS]
|
|
580
|
-
unknown = [m for m in wanted if m not in AVAILABLE_METRICS]
|
|
581
|
-
result: dict[str, Any] = {
|
|
582
|
-
"calculation_engine": {"name": "TA-Lib", "wrapper_version": ENGINE_VERSION,
|
|
583
|
-
"native_version": NATIVE_VERSION},
|
|
584
|
-
"count": len(rows),
|
|
585
|
-
"start_time": int(rows[0]["time"]) if rows else None,
|
|
586
|
-
"end_time": int(rows[-1]["time"]) if rows else None,
|
|
587
|
-
"metrics_computed": ordered,
|
|
588
|
-
"metrics_unknown": unknown,
|
|
589
|
-
}
|
|
590
|
-
for m in ordered:
|
|
591
|
-
if m == "max_drawdown":
|
|
592
|
-
result[m] = metric_max_drawdown(rows)
|
|
593
|
-
elif m == "support_resistance":
|
|
594
|
-
result[m] = metric_support_resistance(
|
|
595
|
-
rows, lookback=lookback, tolerance_pct=tolerance_pct
|
|
596
|
-
)
|
|
597
|
-
elif m == "ma_cross":
|
|
598
|
-
result[m] = metric_ma_cross(rows, ma_periods=ma_periods)
|
|
599
|
-
elif m == "volume_breakout":
|
|
600
|
-
result[m] = metric_volume_breakout(
|
|
601
|
-
rows, volume_ma=volume_ma, volume_ratio=volume_ratio
|
|
602
|
-
)
|
|
603
|
-
elif m == "bollinger":
|
|
604
|
-
result[m] = metric_bollinger(rows, period=boll_period, std_mult=boll_std)
|
|
605
|
-
elif m == "rsi":
|
|
606
|
-
result[m] = metric_rsi(rows, period=rsi_period)
|
|
607
|
-
elif m == "atr":
|
|
608
|
-
result[m] = metric_atr(rows, period=atr_period)
|
|
609
|
-
return result
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
def calc_range(
|
|
613
|
-
rows: list[dict[str, Any]],
|
|
614
|
-
*,
|
|
615
|
-
start_time: int | None = None,
|
|
616
|
-
end_time: int | None = None,
|
|
617
|
-
start_idx: int | None = None,
|
|
618
|
-
end_idx: int | None = None,
|
|
619
|
-
) -> dict[str, Any]:
|
|
620
|
-
"""Interval stats over a sub-range of rows."""
|
|
621
|
-
n = len(rows)
|
|
622
|
-
if n == 0:
|
|
623
|
-
raise ValueError("empty rows")
|
|
624
|
-
|
|
625
|
-
if start_idx is not None or end_idx is not None:
|
|
626
|
-
s = 0 if start_idx is None else max(0, min(n - 1, int(start_idx)))
|
|
627
|
-
e = n - 1 if end_idx is None else max(0, min(n - 1, int(end_idx)))
|
|
628
|
-
else:
|
|
629
|
-
s, e = 0, n - 1
|
|
630
|
-
if start_time is not None:
|
|
631
|
-
st = int(start_time)
|
|
632
|
-
# nearest >= start_time, else last
|
|
633
|
-
s = next((i for i, r in enumerate(rows) if int(r["time"]) >= st), n - 1)
|
|
634
|
-
if end_time is not None:
|
|
635
|
-
et = int(end_time)
|
|
636
|
-
e = next(
|
|
637
|
-
(i for i in range(n - 1, -1, -1) if int(rows[i]["time"]) <= et),
|
|
638
|
-
0,
|
|
639
|
-
)
|
|
640
|
-
if e < s:
|
|
641
|
-
s, e = e, s
|
|
642
|
-
win = rows[s : e + 1]
|
|
643
|
-
if len(win) < 1:
|
|
644
|
-
raise ValueError("empty range window")
|
|
645
|
-
|
|
646
|
-
first, last = win[0], win[-1]
|
|
647
|
-
o = float(first["open"])
|
|
648
|
-
c = float(last["close"])
|
|
649
|
-
hh = max(float(r["high"]) for r in win)
|
|
650
|
-
ll = min(float(r["low"]) for r in win)
|
|
651
|
-
ret_pct = (c / o - 1.0) * 100.0 if o else 0.0
|
|
652
|
-
amp_pct = (hh - ll) / o * 100.0 if o else 0.0
|
|
653
|
-
up_days = sum(1 for r in win if float(r["close"]) >= float(r["open"]))
|
|
654
|
-
down_days = len(win) - up_days
|
|
655
|
-
# consecutive runs
|
|
656
|
-
max_up = max_down = cur_up = cur_down = 0
|
|
657
|
-
for r in win:
|
|
658
|
-
if float(r["close"]) >= float(r["open"]):
|
|
659
|
-
cur_up += 1
|
|
660
|
-
cur_down = 0
|
|
661
|
-
else:
|
|
662
|
-
cur_down += 1
|
|
663
|
-
cur_up = 0
|
|
664
|
-
max_up = max(max_up, cur_up)
|
|
665
|
-
max_down = max(max_down, cur_down)
|
|
666
|
-
total_vol = sum(float(r.get("volume") or 0) for r in win)
|
|
667
|
-
avg_vol = total_vol / len(win) if win else 0.0
|
|
668
|
-
dd = metric_max_drawdown(win)
|
|
669
|
-
t0, t1 = int(first["time"]), int(last["time"])
|
|
670
|
-
return {
|
|
671
|
-
"start_idx": s,
|
|
672
|
-
"end_idx": e,
|
|
673
|
-
"start_time": t0,
|
|
674
|
-
"end_time": t1,
|
|
675
|
-
"bars": len(win),
|
|
676
|
-
"duration_bars": len(win),
|
|
677
|
-
"duration_days": _calendar_days(t0, t1),
|
|
678
|
-
"open": round(o, 4),
|
|
679
|
-
"close": round(c, 4),
|
|
680
|
-
"high": round(hh, 4),
|
|
681
|
-
"low": round(ll, 4),
|
|
682
|
-
"return_pct": round(ret_pct, 4),
|
|
683
|
-
"amplitude_pct": round(amp_pct, 4),
|
|
684
|
-
"up_bars": up_days,
|
|
685
|
-
"down_bars": down_days,
|
|
686
|
-
"max_up_streak": max_up,
|
|
687
|
-
"max_down_streak": max_down,
|
|
688
|
-
"total_volume": round(total_vol, 2),
|
|
689
|
-
"avg_volume": round(avg_vol, 2),
|
|
690
|
-
"max_drawdown": dd,
|
|
691
|
-
}
|