Skip to content

Commit e43e1fc

Browse files
Fix monthly BIST cross-section collapse on delayed Yahoo rows (#22)
* Fix monthly review common factor cross-section * Fix monthly review common factor cross-section * Fix monthly review common factor cross-section
1 parent 13ffdba commit e43e1fc

3 files changed

Lines changed: 77 additions & 11 deletions

File tree

‎config.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
import os
1313

14-
ENGINE_VERSION = "3.15.0" # V3.15: seçim puanı kârlı şirketlere daha çok ağırlık verir; sürüm değişirse motor ay ortasında taramayı yeniler
14+
ENGINE_VERSION = "3.15.1" # V3.15.1: aylık faktör kesiti tekil/gecikmeli Yahoo satırından etkilenmez
1515
STRATEGY_NAME = "ADAPTIVE_BIST_REAL_RETURN_ENGINE_V3"
1616

1717
# ---------------------------------------------------------------- objective (edit here)
@@ -48,6 +48,7 @@
4848
MIN_CROSS_SECTION = 30
4949
MIN_MEDIAN_VALUE_TRADED_TL = 20_000_000.0 # 3-month median daily value traded
5050
MIN_HISTORY_SESSIONS = 260 # price factors need ~1 year of bars
51+
MAX_FACTOR_SOURCE_LAG_SESSIONS = 1 # ücretsiz tarih kaynağı en fazla bir tamamlanmış seans gecikebilir
5152
LIMIT_MOVE_PCT = 9.5
5253
CORP_ACTION_MOVE_PCT = 10.5
5354

‎main.py‎

Lines changed: 53 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -163,18 +163,44 @@ def gold_bar_today(bm, today):
163163
index=[GOLD_TICKER])
164164

165165

166-
def factor_source_coverage(hist, universe, today):
167-
"""Count exactly the observed cross-section entering the existing factor gate."""
166+
def common_factor_date(hist, universe, today):
167+
"""Latest recent date with enough names for a real cross-sectional comparison.
168+
169+
A batch Yahoo response can contain one early/partial row while the rest of
170+
the BIST universe is still on the previous completed session. Using the
171+
union index's final row would then reduce a healthy universe to one stock.
172+
"""
173+
if not hist:
174+
return None
175+
wide = wide_from_history(hist)["close"]
176+
cols = [t for t in universe if t in wide]
177+
if not cols:
178+
return None
179+
counts = wide.loc[wide.index <= pd.Timestamp(today), cols].notna().sum(axis=1)
180+
eligible = counts[counts >= C.MIN_CROSS_SECTION]
181+
if eligible.empty:
182+
return None
183+
date = pd.Timestamp(eligible.index[-1]).normalize()
184+
if cal.sessions_after_count(date, today) > C.MAX_FACTOR_SOURCE_LAG_SESSIONS:
185+
return None
186+
return date
187+
188+
189+
def factor_source_coverage(hist, universe, today, factor_date=None):
190+
"""Count the observed cross-section at the common, recent factor date."""
168191
reasons={}
169192
if not hist:
170193
return {t:"SOURCE_MISSING" for t in universe}
171194
wide=wide_from_history(hist)["close"]
172-
pos=wide.index.searchsorted(pd.Timestamp(today),side="right")-1
195+
factor_date = pd.Timestamp(factor_date).normalize() if factor_date is not None else common_factor_date(hist, universe, today)
196+
if factor_date is None:
197+
return {t: ("SOURCE_MISSING" if t not in wide else "NO_RECENT_COMMON_SESSION") for t in universe}
198+
pos=wide.index.searchsorted(factor_date,side="right")-1
173199
for t in universe:
174200
if t not in wide:
175201
reasons[t]="SOURCE_MISSING"
176-
elif pos < 0 or wide.index[pos].normalize()!=pd.Timestamp(today).normalize() or not np.isfinite(wide[t].iloc[pos]):
177-
reasons[t]="LATEST_SESSION_MISSING"
202+
elif pos < 0 or wide.index[pos].normalize()!=factor_date or not np.isfinite(wide[t].iloc[pos]):
203+
reasons[t]="COMMON_SESSION_MISSING"
178204
elif pos<C.MIN_HISTORY_SESSIONS or int(np.isfinite(wide[t].iloc[pos-252:pos+1]).sum())<240:
179205
reasons[t]="INSUFFICIENT_HISTORY"
180206
else:
@@ -184,7 +210,11 @@ def factor_source_coverage(hist, universe, today):
184210

185211
def recover_monthly_history(hist, universe, today, start, state, loader):
186212
"""Bounded same-provider retry of only absent/incomplete whole series."""
187-
before=factor_source_coverage(hist,universe,today)
213+
# When the universe is below the gate (notably in focused unit probes),
214+
# retain exact-date per-symbol diagnostics so recovery can still be
215+
# measured. Production scoring below still requires a common cohort.
216+
before_date=common_factor_date(hist,universe,today) or pd.Timestamp(today).normalize()
217+
before=factor_source_coverage(hist,universe,today,before_date)
188218
pending=[t for t in universe if before[t]!="FACTOR_WINDOW_READY"]
189219
# Persistent rotation prevents recently listed or unavailable names from
190220
# consuming the same retry allowance on every closed-session review.
@@ -209,11 +239,15 @@ def recover_monthly_history(hist, universe, today, start, state, loader):
209239
hist[t]=g
210240
else:
211241
selected=[]
212-
after=factor_source_coverage(hist,universe,today)
242+
after_common_date=common_factor_date(hist,universe,today)
243+
after_date=after_common_date or pd.Timestamp(today).normalize()
244+
after=factor_source_coverage(hist,universe,today,after_date)
213245
return {"requested":len(universe),"attempted_recovery":len(selected),
214246
"before":{str(k):int(v) for k,v in pd.Series(list(before.values())).value_counts().items()},
215247
"after":{str(k):int(v) for k,v in pd.Series(list(after.values())).value_counts().items()},
216248
"recovered_factor_windows":sum(before[t]!="FACTOR_WINDOW_READY" and after[t]=="FACTOR_WINDOW_READY" for t in universe),
249+
"factor_date":None if after_common_date is None else str(after_common_date.date()),
250+
"source_lag_sessions":None if after_common_date is None else cal.sessions_after_count(after_common_date,today),
217251
"source":"YAHOO_ADJUSTED_WHOLE_SERIES_ONLY","recovery_error":recovery_error}
218252

219253

@@ -242,9 +276,12 @@ def monthly_review(state, research, snap, today, index_close, cpi, cpi_stats, gu
242276
if hist_fn is MD.download_history:
243277
source_coverage=recover_monthly_history(hist,universe,today,str(start.date()),state,hist_fn)
244278
else:
245-
counts=pd.Series(list(factor_source_coverage(hist,universe,today).values())).value_counts()
279+
factor_date=common_factor_date(hist,universe,today)
280+
counts=pd.Series(list(factor_source_coverage(hist,universe,today,factor_date).values())).value_counts()
246281
source_coverage={"requested":len(universe),"attempted_recovery":0,
247-
"after":{str(k):int(v) for k,v in counts.items()}}
282+
"after":{str(k):int(v) for k,v in counts.items()},
283+
"factor_date":None if factor_date is None else str(factor_date.date()),
284+
"source_lag_sessions":None if factor_date is None else cal.sessions_after_count(factor_date,today)}
248285
if len(hist) < C.MIN_CROSS_SECTION:
249286
return {"status": "HISTORY_UNAVAILABLE", "n_hist": len(hist),"factor_source_coverage":source_coverage}, []
250287
wide = wide_from_history(hist)
@@ -256,7 +293,13 @@ def monthly_review(state, research, snap, today, index_close, cpi, cpi_stats, gu
256293
state["model"]["ic_live_12m"] = ic_stats(snaps, "fwd_ret")
257294
state["model"]["ic_live_3m"] = ic_stats(snaps, "fwd_3m")
258295

259-
price_f = price_factors_at(wide, index_close, today)
296+
factor_date = common_factor_date(hist, universe, today)
297+
if factor_date is None and hist_fn is not MD.download_history:
298+
factor_date = pd.Timestamp(today).normalize()
299+
if factor_date is None:
300+
return {"status": "NO_RECENT_COMMON_FACTOR_DATE", "n_scored": 0,
301+
"factor_source_coverage": source_coverage}, []
302+
price_f = price_factors_at(wide, index_close, factor_date)
260303
if price_f.empty:
261304
return {"status": "NO_FACTORS", "n_scored": 0,"factor_source_coverage":source_coverage}, []
262305
price_f = price_f[price_f["ticker"].isin(universe)]

‎tests/test_guard_evidence.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,28 @@
2020

2121

2222
class MonthlySourceCoverageTests(unittest.TestCase):
23+
def test_partial_latest_row_uses_prior_common_session(self):
24+
from main import common_factor_date, factor_source_coverage
25+
import config as C
26+
days = pd.bdate_range("2025-10-30", periods=282)
27+
today = days[-1]
28+
universe = [f"X{i:03d}" for i in range(C.MIN_CROSS_SECTION + 5)]
29+
full = pd.DataFrame({"open": 10., "close": 10., "volume": 100.}, index=days)
30+
hist = {t: full.iloc[:-1].copy() for t in universe}
31+
hist[universe[0]] = full.copy() # provider's isolated early/partial row
32+
factor_date = common_factor_date(hist, universe, today)
33+
self.assertEqual(factor_date, days[-2])
34+
audit = factor_source_coverage(hist, universe, today, factor_date)
35+
self.assertEqual(sum(v == "FACTOR_WINDOW_READY" for v in audit.values()), len(universe))
36+
37+
def test_common_factor_date_rejects_stale_cross_section(self):
38+
from main import common_factor_date
39+
import config as C
40+
days = pd.bdate_range("2025-10-27", periods=283)
41+
universe = [f"X{i:03d}" for i in range(C.MIN_CROSS_SECTION)]
42+
bars = pd.DataFrame({"open": 10., "close": 10., "volume": 100.}, index=days[:-2])
43+
self.assertIsNone(common_factor_date({t: bars for t in universe}, universe, days[-1]))
44+
2345
def test_bounded_history_retry_without_synthetic_or_spliced_prices(self):
2446
from main import recover_monthly_history
2547
import config as C

0 commit comments

Comments
 (0)