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 @@
## 2025-02-28 - Replace O(n) Array Filtering with Binary Search on Timeseries Data
**Learning:** During backtesting, `priceOverride` and `vnindexAt` functions were evaluating closures at every turn in a loop. Both were using O(n) `Array.prototype.filter()` over long chronologically-sorted price arrays simply to find the last item prior to `asOf`, constantly allocating arrays.
**Action:** Always prefer binary search O(log n) lookups over array filtering on chronologically sorted timeseries datasets (like OHLCV arrays), especially when fetching historical state repeatedly. Added `findLastBarIndex` to abstract this logic out.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,13 @@
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.1.0",
"better-sqlite3": "^11.5.0",
"cheerio": "^1.0.0",
"cheerio": "^1.2.0",
"ink": "^5.0.1",
"ink-spinner": "^5.0.0",
"ink-text-input": "^6.0.0",
"react": "^18.3.1",
"technicalindicators": "^3.1.0",
"undici": "^6.20.0",
"undici": "^6.27.0",
"yaml": "^2.6.0",
"zod": "^3.23.8"
},
Expand Down
28 changes: 14 additions & 14 deletions pnpm-lock.yaml

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

13 changes: 8 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;
if (vnindex.length === 0) return null;
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,10 @@ 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;
const series = bars[sym];
if (!series || series.length === 0) return null;
const lastIdx = findLastBarIndex(series, asOf);
return lastIdx !== -1 ? series[lastIdx]!.close : null;
};
broker.setPriceOverride(priceOverride);
cb.onTurnStart?.({ asOf, dateIso });
Expand Down
28 changes: 26 additions & 2 deletions src/data/sources/dnsePublic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,27 @@ export interface Bar {
volume: number;
}

/**
* Finds the index of the last bar that occurred on or before a given timestamp.
* Assumes the bars array is sorted chronologically by time.
* Time complexity: O(log n)
*/
export function findLastBarIndex(bars: Bar[], time: number): number {
let low = 0;
let high = bars.length - 1;
let ans = -1;
while (low <= high) {
const mid = (low + high) >> 1;
if (bars[mid]!.time <= time) {
ans = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return ans;
}

async function fetchOhlcs(
kind: "stock" | "index",
symbol: string,
Expand Down Expand Up @@ -66,9 +87,12 @@ function clipBars(bars: Bar[]): Bar[] {
// is set, fall through unchanged — DNSE only returns historical data anyway.
const hasOverride =
asOfClock.getStore()?.asOfSec != null || isAsOfOverridden();
if (!hasOverride) return bars;
if (!hasOverride || bars.length === 0) return bars;
const asOf = nowSec();
return bars.filter((b) => b.time <= asOf);
const lastIdx = findLastBarIndex(bars, asOf);
if (lastIdx === -1) return [];
// slice is O(1) conceptually and much faster than O(n) filter
return bars.slice(0, lastIdx + 1);
}

export async function getStockOhlcv(
Expand Down
Loading