Skip to content

"Vibe-Trading: Your Personal Trading Agent"

perf(backtest): convert an index to nanoseconds only when it is not already

Haozhe Wu2100ca81385c
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index fc62a3a85..a7b9e8c4d 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -262,7 +262,12 @@ def _align(
# count in the index's own unit: a duckdb-backed local source arrives as
# datetime64[us], which read as nanoseconds put the run in 1970 and, beside
# a nanosecond source, matched none of its bars. One unit for all of them.
- indexes = [data_map[c].index.as_unit("ns") for c in codes]
+ ns_index = {
+ c: idx if idx.unit == "ns" else idx.as_unit("ns")
+ for c in codes
+ for idx in (data_map[c].index,)
+ }
+ indexes = [ns_index[c] for c in codes]
merged = np.unique(np.concatenate([index.asi8 for index in indexes]))
common_tz = indexes[0].tz
if all(index.tz == common_tz for index in indexes) and common_tz is not None:
@@ -324,7 +329,7 @@ def _align(
shifted_vals[0] = 0.0
shifted_vals[1:] = sig_vals[:-1]
# Place into unified grid via searchsorted
- row_idx = np.searchsorted(dates_i8, own_idx.as_unit("ns").asi8)
+ row_idx = np.searchsorted(dates_i8, ns_index[c].asi8)
pos_arr[row_idx, j] = shifted_vals
# Vectorized ffill with limit using pandas (C-optimized)