Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 2024-06-25 - [Binary Search for Chronological Time Series Arrays]
**Learning:** Time-series market data arrays (like OHLCV bars) are chronologically sorted in this codebase. O(n) array filtering operations (e.g. `bars.filter(b => b.time <= asOf)`) on these arrays within hot paths like backtesting loops cause significant performance overhead.
**Action:** Replace `Array.prototype.filter` with an O(log n) binary search lookup (e.g., a `findLastBarIndex` utility) when truncating or querying the latest available bar up to a specific time. Use `.slice(0, lastIndex + 1)` if the truncated array is needed, or just access the index directly if only the latest bar is required.
9 changes: 7 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,12 @@
"pnpm": {
"onlyBuiltDependencies": [
"better-sqlite3"
]
],
"overrides": {
"ws": ">=8.21.0",
"cheerio>undici": ">=7.28.0",
"undici": "^6.27.0"
}
},
"packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8"
}
}
33 changes: 19 additions & 14 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 9 additions & 5 deletions src/agent/backtestRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
import { loadConfig } from "../config/loader.js";
import { getDb } from "../storage/db.js";
import { getBacktestBroker } from "../broker/index.js";
import { getStockOhlcv, getIndexOhlcv, type Bar } from "../data/sources/dnsePublic.js";
import { getStockOhlcv, getIndexOhlcv, findLastBarIndex, type Bar } from "../data/sources/dnsePublic.js";
import { DISCOVERY_UNIVERSE, discoverTickers } from "../tools/discover.js";
import { setActiveAsOf } from "./clock.js";
import { runTeamAnalysis } from "./team/index.js";
Expand Down Expand Up @@ -298,8 +298,9 @@ export async function runBacktestSession(
);

const vnindexAt = (asOf: number): number | null => {
const series = vnindex.filter((b) => b.time <= asOf);
return series.length ? series[series.length - 1]!.close : null;
// ⚡ Bolt: Replace O(n) filtering with O(log n) binary search lookup
const lastIdx = findLastBarIndex(vnindex, asOf);
return lastIdx !== -1 ? vnindex[lastIdx]!.close : null;
};
const vnindexBaseline = vnindexAt(intervalTurns[0]!);
if (vnindexBaseline == null) throw new Error(`no VNINDEX data at first ${interval.label} turn`);
Expand All @@ -312,8 +313,11 @@ export async function runBacktestSession(
throwIfAborted(cb.signal);
const dateIso = ictLabel(asOf);
const priceOverride = (sym: string): number | null => {
const series = bars[sym]?.filter((b) => b.time <= asOf) ?? [];
return series.length ? series[series.length - 1]!.close : null;
// ⚡ Bolt: Replace O(n) filtering with O(log n) binary search lookup
const symBars = bars[sym];
if (!symBars || symBars.length === 0) return null;
const lastIdx = findLastBarIndex(symBars, asOf);
return lastIdx !== -1 ? symBars[lastIdx]!.close : null;
};
broker.setPriceOverride(priceOverride);
cb.onTurnStart?.({ asOf, dateIso });
Expand Down
27 changes: 26 additions & 1 deletion src/data/sources/dnsePublic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,28 @@ async function fetchOhlcs(
return (await body.json()) as OhlcvSeries;
}

/**
* Reusable binary search utility to find the index of the last bar with a time <= targetTime.
* Returns -1 if no such bar exists.
*/
export function findLastBarIndex(bars: Bar[], targetTime: number): number {
let left = 0;
let right = bars.length - 1;
let result = -1;

while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (bars[mid].time <= targetTime) {
result = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}

return result;
}

export function seriesToBars(s: OhlcvSeries): Bar[] {
const out: Bar[] = [];
for (let i = 0; i < s.t.length; i++) {
Expand All @@ -68,7 +90,10 @@ function clipBars(bars: Bar[]): Bar[] {
asOfClock.getStore()?.asOfSec != null || isAsOfOverridden();
if (!hasOverride) return bars;
const asOf = nowSec();
return bars.filter((b) => b.time <= asOf);
// ⚡ Bolt: Replace O(n) filtering with O(log n) binary search lookup
const lastIndex = findLastBarIndex(bars, asOf);
if (lastIndex === -1) return [];
return bars.slice(0, lastIndex + 1);
}

export async function getStockOhlcv(
Expand Down
Loading