oss-backtest-kit 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,150 @@
1
+ """Fetch the most recent bars from the public futures REST market-data API.
2
+
3
+ Fetches the days that are not yet in the archive and exports them as
4
+ standalone csv files under ``<out>/rest/``. These files are NOT added to
5
+ ``MANIFEST.csv`` and are NOT read by ``engine.load_market_data``; a backtest on
6
+ a downloaded directory ends at the last archive file. Public endpoints only (no
7
+ keys), GET only, one allowed host. Only bars that closed before the server time
8
+ at fetch are kept. Each run writes new csv files (exclusive create, never
9
+ overwrites).
10
+ """
11
+
12
+ import csv
13
+ import datetime as dt
14
+ import io
15
+ import json
16
+ import re
17
+ import time
18
+ from pathlib import Path
19
+
20
+ from ._http import DataError, HttpClient
21
+ from .archive import atomic_create
22
+
23
+ __all__ = ["HOST", "KLINE_PATHS", "fetch_klines", "fetch_funding", "run"]
24
+
25
+ HOST = "fapi.binance.com"
26
+ BASE = "https://%s" % HOST
27
+ WEIGHT_BUDGET = 1920 # 80% of a 2400/minute limit
28
+ KLINE_COLS = ["open_time", "open", "high", "low", "close", "volume", "close_time",
29
+ "quote_volume", "trades", "taker_buy_volume", "taker_buy_quote_volume", "ignore"]
30
+ KLINE_PATHS = {
31
+ "klines": "/fapi/v1/klines",
32
+ "markPriceKlines": "/fapi/v1/markPriceKlines",
33
+ "indexPriceKlines": "/fapi/v1/indexPriceKlines",
34
+ "premiumIndexKlines": "/fapi/v1/premiumIndexKlines",
35
+ }
36
+ _SYMBOL_RE = re.compile(r"^[A-Z0-9]{2,20}$")
37
+ _INTERVAL_RE = re.compile(r"^[0-9]{1,2}[mhdwM]$")
38
+
39
+
40
+ def _get_json(client, path, params, sleep=time.sleep, pause_s=0.25):
41
+ query = "&".join("%s=%s" % (k, v) for k, v in params.items())
42
+ got = client.get(BASE + path + ("?" + query if query else ""))
43
+ if got is None:
44
+ raise DataError("not found: %s" % path)
45
+ body, headers = got
46
+ try:
47
+ used = int(headers.get("X-MBX-USED-WEIGHT-1M") or 0)
48
+ except (TypeError, ValueError, AttributeError):
49
+ used = 0
50
+ if used > WEIGHT_BUDGET:
51
+ sleep(61)
52
+ sleep(pause_s)
53
+ return json.loads(body)
54
+
55
+
56
+ def server_time_ms(client, **kw):
57
+ """Current server time in milliseconds."""
58
+ return int(_get_json(client, "/fapi/v1/time", {}, **kw)["serverTime"])
59
+
60
+
61
+ PAGE = 1000
62
+ MAX_PAGES = 1000 # at most 1,000,000 rows per series and run
63
+
64
+
65
+ def _paginate(get_page, time_of, start_ms, now_ms, max_pages):
66
+ """Collect pages from ``start_ms``. Each page must start at or after the cursor
67
+ and be strictly increasing, so the cursor always moves forward; at most
68
+ ``max_pages`` requests are made."""
69
+ rows, t = [], int(start_ms)
70
+ for _ in range(max_pages):
71
+ if t >= now_ms:
72
+ return rows
73
+ data = get_page(t)
74
+ if not data:
75
+ return rows
76
+ times = [int(time_of(d)) for d in data]
77
+ if times[0] < t or any(a >= b for a, b in zip(times, times[1:])):
78
+ raise DataError("page from %d is repeated or out of order; stopping" % t)
79
+ rows += data
80
+ t = times[-1] + 1
81
+ if len(data) < PAGE:
82
+ return rows
83
+ raise DataError("more than %d pages; use a shorter date range" % max_pages)
84
+
85
+
86
+ def fetch_klines(client, symbol, kind, interval, start_ms, now_ms, max_pages=MAX_PAGES, **kw):
87
+ """Closed bars (close_time < now_ms) from ``start_ms``; pages of 1000."""
88
+ if kind not in KLINE_PATHS:
89
+ raise ValueError("unknown kind %r; choose from %s" % (kind, sorted(KLINE_PATHS)))
90
+ if not _SYMBOL_RE.match(symbol) or not _INTERVAL_RE.match(interval):
91
+ raise ValueError("bad symbol or interval")
92
+ key = "pair" if kind == "indexPriceKlines" else "symbol"
93
+ rows = _paginate(lambda t: _get_json(client, KLINE_PATHS[kind], {
94
+ key: symbol, "interval": interval, "startTime": t, "limit": PAGE}, **kw),
95
+ lambda d: d[0], start_ms, now_ms, max_pages)
96
+ return [d for d in rows if d[6] < now_ms]
97
+
98
+
99
+ def fetch_funding(client, symbol, start_ms, now_ms, max_pages=MAX_PAGES, **kw):
100
+ """Funding events from ``start_ms`` up to ``now_ms``."""
101
+ if not _SYMBOL_RE.match(symbol):
102
+ raise ValueError("bad symbol")
103
+ rows = _paginate(lambda t: _get_json(client, "/fapi/v1/fundingRate", {
104
+ "symbol": symbol, "startTime": t, "limit": PAGE}, **kw),
105
+ lambda d: d["fundingTime"], start_ms, now_ms, max_pages)
106
+ return [(d["fundingTime"], d["fundingRate"], d.get("markPrice", ""))
107
+ for d in rows if d["fundingTime"] < now_ms]
108
+
109
+
110
+ def _write(out_dir, symbol, name, start, now, cols, rows):
111
+ path = Path(out_dir) / "rest" / symbol / ("%s_%d_%d.csv" % (name, start, now))
112
+ buf = io.StringIO()
113
+ w = csv.writer(buf)
114
+ w.writerow(list(cols) + ["fetched_ms"])
115
+ for r in rows:
116
+ w.writerow(list(r) + [now])
117
+ return atomic_create(path, buf.getvalue().encode("utf-8"))
118
+
119
+
120
+ def _day_ms(text):
121
+ d = dt.datetime.strptime(text, "%Y-%m-%d").replace(tzinfo=dt.timezone.utc)
122
+ return int(d.timestamp() * 1000)
123
+
124
+
125
+ def run(symbols, kinds, interval, start_day, out_dir, end_day=None, client=None,
126
+ include_funding=True, **kw):
127
+ """Fetch tails for every symbol and kind; returns the list of files written.
128
+
129
+ ``start_day`` / ``end_day`` are ``YYYY-MM-DD`` (UTC); ``end_day`` is
130
+ exclusive. File names carry the cut-off time, so reruns never collide
131
+ unless the cut-off is identical (then creation fails rather than overwrite).
132
+ """
133
+ client = client or HttpClient(HOST)
134
+ start = _day_ms(start_day)
135
+ written = []
136
+ for symbol in symbols:
137
+ now = server_time_ms(client, **kw)
138
+ if end_day:
139
+ now = min(now, _day_ms(end_day))
140
+ for kind in kinds:
141
+ if kind == "fundingRate":
142
+ continue
143
+ rows = fetch_klines(client, symbol, kind, interval, start, now, **kw)
144
+ written.append(_write(out_dir, symbol, "%s_%s" % (kind, interval), start, now,
145
+ KLINE_COLS, rows))
146
+ if include_funding and "fundingRate" in kinds:
147
+ rows = fetch_funding(client, symbol, start, now, **kw)
148
+ written.append(_write(out_dir, symbol, "fundingRate", start, now,
149
+ ["funding_time", "funding_rate", "mark_price"], rows))
150
+ return written
@@ -0,0 +1,405 @@
1
+ """A small, config-driven backtest engine for a portfolio of perpetual futures.
2
+
3
+ Model (kept deliberately simple and explicit):
4
+
5
+ * Bars have a fixed length (``config.bar``, daily by default). Bar times must
6
+ be exactly one bar length apart; a missing bar is a NaN row, not a gap.
7
+ * A strategy is a callable ``weights(t, history) -> {symbol: weight}``. It runs
8
+ at the **close** of bar ``t`` and sees only bars ``0..t`` (inclusive).
9
+ * The weights are executed at the **open** of bar ``t + 1``. A weight is the
10
+ position notional divided by equity; negative means short.
11
+ * A symbol is only traded when its target differs from the current weight by
12
+ more than ``rebalance_threshold``.
13
+ * Costs have two parts: slippage moves the fill price against the trade, and a
14
+ proportional fee is charged on the filled notional. Two named cost levels
15
+ (``base`` and ``stressed``) are carried in the config.
16
+ * Funding: at each funding event the position pays ``quantity * price * rate``
17
+ (longs pay when the rate is positive). An event at time ``t`` belongs to the
18
+ bar with ``open_time <= t < open_time + bar length``; it is charged on the
19
+ position held after that bar's opening fill, at that bar's open price.
20
+ Events outside every loaded bar are dropped.
21
+ * Ruin: if equity at a bar close is zero or below, all positions are closed at
22
+ that mark, equity stays at zero and nothing more is traded. The loss beyond
23
+ zero is reported as ``ruin_shortfall`` so that per-symbol PnL plus the
24
+ shortfall equals the change in equity.
25
+ * Equity is marked at each bar close. Positions in symbols with a missing bar
26
+ are marked at their last known close and cannot be traded on that bar.
27
+
28
+ Only numpy is required. Loading from files uses the layout written by
29
+ :mod:`oss_backtest_kit.data.archive`.
30
+ """
31
+
32
+ import csv
33
+ import datetime as dt
34
+ import io
35
+ import math
36
+ import warnings
37
+ import zipfile
38
+ from dataclasses import dataclass, field
39
+ from pathlib import Path
40
+
41
+ import numpy as np
42
+
43
+ from . import stats
44
+ from .data.check import interval_ms
45
+
46
+ __all__ = ["EngineError", "CostModel", "EngineConfig", "MarketData", "History",
47
+ "BacktestResult", "run_backtest", "load_market_data"]
48
+
49
+
50
+ class EngineError(ValueError):
51
+ """Invalid configuration, data or strategy output."""
52
+
53
+
54
+ @dataclass
55
+ class CostModel:
56
+ """Proportional fee and slippage per unit of traded notional (0.0004 = 4 bp)."""
57
+
58
+ fee_rate: float
59
+ slippage: float
60
+
61
+ def __post_init__(self):
62
+ if self.fee_rate < 0 or self.slippage < 0:
63
+ raise EngineError("costs must be non-negative")
64
+
65
+
66
+ def _default_costs():
67
+ # Placeholder textbook values, not a recommendation: set your own.
68
+ return {"base": CostModel(fee_rate=0.0004, slippage=0.0002),
69
+ "stressed": CostModel(fee_rate=0.0010, slippage=0.0005)}
70
+
71
+
72
+ @dataclass
73
+ class EngineConfig:
74
+ """Everything that defines a run apart from data and strategy."""
75
+
76
+ symbols: list
77
+ bar: str = "1d" # bar length, e.g. 1d, 4h
78
+ start: str = None # first tracked day, YYYY-MM-DD (UTC); None = first bar
79
+ end: str = None # exclusive end day; None = last bar
80
+ initial_equity: float = 1.0
81
+ max_leverage: float = 1.0 # cap on sum(|weight|)
82
+ rebalance_threshold: float = 0.0 # skip trades smaller than this weight change
83
+ funding: bool = True
84
+ costs: dict = field(default_factory=_default_costs)
85
+
86
+ @property
87
+ def periods_per_year(self):
88
+ return 365.25 * 86400000.0 / interval_ms(self.bar)
89
+
90
+
91
+ @dataclass
92
+ class MarketData:
93
+ """Aligned price panels, shape (bars, symbols); NaN marks a missing bar.
94
+
95
+ ``fund_px[i, c]`` is the sum over funding events inside bar ``i`` of
96
+ ``rate * price``; a position of ``q`` units pays ``q * fund_px[i, c]``.
97
+ """
98
+
99
+ symbols: list
100
+ times: np.ndarray
101
+ open: np.ndarray
102
+ high: np.ndarray
103
+ low: np.ndarray
104
+ close: np.ndarray
105
+ fund_px: np.ndarray = None
106
+
107
+ def __post_init__(self):
108
+ n, m = len(self.times), len(self.symbols)
109
+ for name in ("open", "high", "low", "close"):
110
+ a = np.asarray(getattr(self, name), dtype=float)
111
+ if a.shape != (n, m):
112
+ raise EngineError("%s must have shape (%d, %d)" % (name, n, m))
113
+ setattr(self, name, a)
114
+ self.times = np.asarray(self.times, dtype=np.int64)
115
+ if n > 1 and not (np.diff(self.times) > 0).all():
116
+ raise EngineError("times must be strictly increasing")
117
+ if self.fund_px is None:
118
+ self.fund_px = np.zeros((n, m))
119
+ self.fund_px = np.nan_to_num(np.asarray(self.fund_px, dtype=float))
120
+ if self.fund_px.shape != (n, m):
121
+ raise EngineError("fund_px must have shape (%d, %d)" % (n, m))
122
+ if (self.open <= 0).any() or (self.close <= 0).any():
123
+ raise EngineError("prices must be positive (use NaN for missing bars)")
124
+
125
+ def truncated(self, n_bars):
126
+ """The first ``n_bars`` bars as a new MarketData."""
127
+ s = slice(0, n_bars)
128
+ return MarketData(self.symbols, self.times[s], self.open[s], self.high[s],
129
+ self.low[s], self.close[s], self.fund_px[s])
130
+
131
+
132
+ class History:
133
+ """Read-only view of bars ``0..t`` handed to the strategy."""
134
+
135
+ def __init__(self, data, t):
136
+ self.symbols = list(data.symbols)
137
+ self.t = t
138
+ for name in ("times", "open", "high", "low", "close"):
139
+ view = getattr(data, name)[: t + 1]
140
+ view = view.view()
141
+ view.flags.writeable = False
142
+ setattr(self, name, view)
143
+
144
+
145
+ @dataclass
146
+ class BacktestResult:
147
+ """Outputs of one run. Arrays are per tracked bar."""
148
+
149
+ symbols: list
150
+ times: np.ndarray
151
+ equity: np.ndarray
152
+ returns: np.ndarray
153
+ turnover: np.ndarray # traded notional at the bar open / equity at that open
154
+ fees: float
155
+ slippage_cost: float
156
+ funding_net: float # positive = received
157
+ pnl_by_symbol: dict # net of fees, slippage and funding
158
+ funding_by_symbol: dict
159
+ periods_per_year: float
160
+ initial_equity: float
161
+ # Loss beyond zero equity at ruin, not borne by the account (limited liability):
162
+ # sum(pnl_by_symbol) + ruin_shortfall == equity[-1] - initial_equity.
163
+ ruin_shortfall: float = 0.0
164
+
165
+ def summary(self):
166
+ """Headline numbers; ``returns`` can be passed straight to stats.psr / stats.dsr."""
167
+ r = self.returns
168
+ years = len(r) / self.periods_per_year
169
+ final = float(self.equity[-1])
170
+ return {
171
+ "bars": int(len(r)),
172
+ "total_return": final / self.initial_equity - 1.0,
173
+ "sharpe_annualised": stats.sharpe_annualised(r, self.periods_per_year),
174
+ "max_drawdown": stats.max_drawdown(r),
175
+ "psr_vs_zero": stats.psr(r, 0.0),
176
+ "turnover_per_year": float(self.turnover.sum() / years) if years > 0 else 0.0,
177
+ "fees": self.fees,
178
+ "slippage_cost": self.slippage_cost,
179
+ "funding_net": self.funding_net,
180
+ "pnl_by_symbol": dict(self.pnl_by_symbol),
181
+ "ruin_shortfall": self.ruin_shortfall,
182
+ }
183
+
184
+
185
+ def _day_ms(text):
186
+ d = dt.datetime.strptime(text, "%Y-%m-%d").replace(tzinfo=dt.timezone.utc)
187
+ return int(d.timestamp() * 1000)
188
+
189
+
190
+ def _check_config(cfg, data):
191
+ if list(cfg.symbols) != list(data.symbols):
192
+ raise EngineError("config symbols must equal data symbols (same order)")
193
+ if cfg.initial_equity <= 0 or cfg.max_leverage <= 0 or cfg.rebalance_threshold < 0:
194
+ raise EngineError("initial_equity and max_leverage must be positive, threshold >= 0")
195
+ try:
196
+ step = interval_ms(cfg.bar)
197
+ except ValueError as exc:
198
+ raise EngineError(str(exc)) from None
199
+ # Annualisation counts rows, so rows must be consecutive bars of cfg.bar.
200
+ if len(data.times) > 1 and not (np.diff(data.times) == step).all():
201
+ raise EngineError("bar times must be spaced exactly %s apart (config.bar); "
202
+ "fill missing bars with NaN rows" % cfg.bar)
203
+
204
+
205
+ def _targets(strategy, t, data, cfg):
206
+ raw = strategy(t, History(data, t)) or {}
207
+ w = np.zeros(len(cfg.symbols))
208
+ index = {s: i for i, s in enumerate(cfg.symbols)}
209
+ for sym, val in raw.items():
210
+ if sym not in index:
211
+ raise EngineError("strategy returned unknown symbol %r" % (sym,))
212
+ if not math.isfinite(val):
213
+ raise EngineError("non-finite weight for %s" % sym)
214
+ w[index[sym]] = val
215
+ if np.abs(w).sum() > cfg.max_leverage * (1 + 1e-9):
216
+ raise EngineError("sum(|weights|)=%.6f exceeds max_leverage=%.6f"
217
+ % (np.abs(w).sum(), cfg.max_leverage))
218
+ return w
219
+
220
+
221
+ def run_backtest(data, strategy, config, cost_level="base"):
222
+ """Run ``strategy`` over ``data`` and return a :class:`BacktestResult`.
223
+
224
+ Bars before ``config.start`` are history only (warm-up). The first trades
225
+ fill at the open of the first tracked bar, using weights decided at the
226
+ close of the bar before it (so a warm-up bar must exist for that).
227
+ """
228
+ _check_config(config, data)
229
+ if cost_level not in config.costs:
230
+ raise EngineError("unknown cost level %r; have %s" % (cost_level, sorted(config.costs)))
231
+ cost = config.costs[cost_level]
232
+ n, m = data.open.shape
233
+ i0 = int(np.searchsorted(data.times, _day_ms(config.start))) if config.start else 0
234
+ i1 = int(np.searchsorted(data.times, _day_ms(config.end))) if config.end else n
235
+ if i1 - i0 < 1:
236
+ raise EngineError("no bars in the requested range")
237
+
238
+ cash, q = float(config.initial_equity), np.zeros(m)
239
+ flow = np.zeros(m)
240
+ fund_flow = np.zeros(m)
241
+ last_close = np.full(m, np.nan)
242
+ for i in range(i0): # warm-up marks
243
+ last_close = np.where(np.isnan(data.close[i]), last_close, data.close[i])
244
+ fees = slip_cost = 0.0
245
+ k = i1 - i0
246
+ eq, ret, turn = np.zeros(k), np.zeros(k), np.zeros(k)
247
+ prev_eq, ruined, shortfall = float(config.initial_equity), False, 0.0
248
+
249
+ for j, i in enumerate(range(i0, i1)):
250
+ if ruined:
251
+ eq[j] = 0.0
252
+ continue
253
+ o = data.open[i]
254
+ ok = ~np.isnan(o)
255
+ mark = np.where(ok, o, last_close)
256
+ e_open = cash + float(np.sum(q * np.nan_to_num(mark)))
257
+ if i >= 1 and e_open > 0:
258
+ tgt = _targets(strategy, i - 1, data, config)
259
+ traded = 0.0
260
+ for c in range(m):
261
+ if not ok[c]:
262
+ continue
263
+ cur = q[c] * o[c] / e_open
264
+ if abs(tgt[c] - cur) <= config.rebalance_threshold or tgt[c] == cur:
265
+ continue
266
+ dq = tgt[c] * e_open / o[c] - q[c]
267
+ px = o[c] * (1 + cost.slippage) if dq > 0 else o[c] * (1 - cost.slippage)
268
+ fee = abs(dq) * px * cost.fee_rate
269
+ cash -= dq * px + fee
270
+ flow[c] -= dq * px + fee
271
+ fees += fee
272
+ slip_cost += abs(dq) * o[c] * cost.slippage
273
+ traded += abs(dq) * o[c]
274
+ q[c] += dq
275
+ turn[j] = traded / e_open
276
+ if config.funding:
277
+ pay = q * data.fund_px[i]
278
+ cash -= float(pay.sum())
279
+ flow -= pay
280
+ fund_flow -= pay
281
+ last_close = np.where(np.isnan(data.close[i]), last_close, data.close[i])
282
+ eq[j] = cash + float(np.sum(q * np.nan_to_num(last_close)))
283
+ if eq[j] <= 0:
284
+ # Limited liability: positions are closed at the mark, equity stops at
285
+ # zero and the loss beyond it is reported as ruin_shortfall.
286
+ flow += q * np.nan_to_num(last_close)
287
+ shortfall, q, cash = -eq[j], np.zeros(m), 0.0
288
+ eq[j], ruined = 0.0, True
289
+ ret[j] = eq[j] / prev_eq - 1.0 if prev_eq > 0 else 0.0
290
+ prev_eq = eq[j]
291
+
292
+ pnl = flow + q * np.nan_to_num(last_close)
293
+ return BacktestResult(
294
+ symbols=list(config.symbols), times=data.times[i0:i1].copy(), equity=eq, returns=ret,
295
+ turnover=turn, fees=fees, slippage_cost=slip_cost, funding_net=float(fund_flow.sum()),
296
+ pnl_by_symbol=dict(zip(config.symbols, map(float, pnl))),
297
+ funding_by_symbol=dict(zip(config.symbols, map(float, fund_flow))),
298
+ periods_per_year=config.periods_per_year, initial_equity=float(config.initial_equity),
299
+ ruin_shortfall=float(shortfall))
300
+
301
+
302
+ # ---------------------------------------------------------------- loading
303
+
304
+ def _ms(value):
305
+ n = int(value)
306
+ return n // 1000 if n >= 10 ** 15 else n
307
+
308
+
309
+ def _manifest(directory):
310
+ path = Path(directory) / "MANIFEST.csv"
311
+ if not path.exists():
312
+ raise EngineError("no MANIFEST.csv in %s" % directory)
313
+ with open(path, newline="") as fh:
314
+ return list(csv.DictReader(fh))
315
+
316
+
317
+ def _zip_records(directory, rel):
318
+ with zipfile.ZipFile(Path(directory) / rel) as zf, zf.open(zf.namelist()[0]) as fh:
319
+ for rec in csv.reader(io.TextIOWrapper(fh, "ascii")):
320
+ if rec and rec[0].strip()[:1].isdigit():
321
+ yield rec
322
+
323
+
324
+ def _kline_bars(directory, rows, sym, interval):
325
+ """``{open_ms: [open, high, low, close]}``; the same bar in two files must agree."""
326
+ recs = {}
327
+ for r in rows:
328
+ if r["kind"] == "klines" and r["symbol"] == sym and r["interval"] == interval:
329
+ for rec in _zip_records(directory, r["local_path"]):
330
+ t, vals = _ms(rec[0]), [float(x) for x in rec[1:5]]
331
+ if recs.setdefault(t, vals) != vals:
332
+ raise EngineError("conflicting %s bars for %s at %d" % (interval, sym, t))
333
+ if not recs:
334
+ raise EngineError("no %s klines for %s in manifest" % (interval, sym))
335
+ return recs
336
+
337
+
338
+ def _funding_events(directory, rows, sym):
339
+ """``{event_ms: rate}``, one entry per event even if several files list it."""
340
+ events = {}
341
+ for r in rows:
342
+ if r["kind"] != "fundingRate" or r["symbol"] != sym:
343
+ continue
344
+ for rec in _zip_records(directory, r["local_path"]):
345
+ # archive layout: calc_time, interval_hours, last_funding_rate
346
+ t, rate = _ms(rec[0]), float(rec[2])
347
+ if events.setdefault(t, rate) != rate:
348
+ raise EngineError("conflicting funding rates for %s at %d" % (sym, t))
349
+ return events
350
+
351
+
352
+ def _funding_panel(directory, rows, symbols, times, step, open_, close):
353
+ """Sum of ``rate * price`` per bar, with bar ``i`` covering ``[times[i], times[i] + step)``.
354
+
355
+ Events before the first bar or at/after the end of the last bar belong to no
356
+ loaded bar and are dropped (never moved onto an earlier bar). The price is the
357
+ bar's open, or the symbol's most recent earlier close when that bar is missing.
358
+ """
359
+ fund_px = np.zeros((len(times), len(symbols)))
360
+ for c, sym in enumerate(symbols):
361
+ for t, rate in _funding_events(directory, rows, sym).items():
362
+ if t < times[0] or t >= times[-1] + step:
363
+ continue
364
+ i = int((t - times[0]) // step)
365
+ px = open_[i, c]
366
+ if np.isnan(px):
367
+ prev = close[:i, c][np.isfinite(close[:i, c])]
368
+ if not prev.size:
369
+ continue # no earlier price, so no position can be open
370
+ px = prev[-1]
371
+ fund_px[i, c] += rate * px
372
+ return fund_px
373
+
374
+
375
+ def load_market_data(directory, symbols, interval="1d", funding=True):
376
+ """Build :class:`MarketData` from files written by ``oss_backtest_kit.data.archive``.
377
+
378
+ Reads ``klines`` (and ``fundingRate`` when ``funding`` is true) listed in the
379
+ directory's manifest. Bars are placed on a regular ``interval`` grid from the
380
+ first to the last bar time, so the time axis has no gaps; a symbol without a
381
+ bar at some grid time gets NaN there. A bar listed in several files must have
382
+ identical values, and a funding event listed in several files counts once.
383
+
384
+ Only manifest files are read. CSV files written by ``data.rest_tail`` (under
385
+ ``rest/``) are an export and are never loaded; a warning says so when they exist.
386
+ """
387
+ step = interval_ms(interval)
388
+ rows = _manifest(directory)
389
+ if (Path(directory) / "rest").is_dir():
390
+ warnings.warn("REST tail files under %s/rest are not loaded; the data ends at the "
391
+ "last archive file in the manifest" % directory, stacklevel=2)
392
+ bars = {sym: _kline_bars(directory, rows, sym, interval) for sym in symbols}
393
+ t0 = min(min(b) for b in bars.values())
394
+ t1 = max(max(b) for b in bars.values())
395
+ times = np.arange(t0, t1 + step, step, dtype=np.int64)
396
+ panels = [np.full((len(times), len(symbols)), np.nan) for _ in range(4)]
397
+ for c, sym in enumerate(symbols):
398
+ for t, vals in bars[sym].items():
399
+ if (t - t0) % step:
400
+ raise EngineError("%s bar at %d is not on the %s grid" % (sym, t, interval))
401
+ for p in range(4):
402
+ panels[p][(t - t0) // step, c] = vals[p]
403
+ fund_px = (_funding_panel(directory, rows, symbols, times, step, panels[0], panels[3])
404
+ if funding else np.zeros((len(times), len(symbols))))
405
+ return MarketData(list(symbols), times, panels[0], panels[1], panels[2], panels[3], fund_px)