diff --git a/README.md b/README.md index 1140146..1467dfc 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,9 @@ # 基金研究工作台 +[冻结筛选研究 API](docs/SELECTION.md)提供原净值频率的风格样本外评估、保留缺失基金的 +持续性比较、已有优化器的名单配置,以及不修改账户的账本预演。 +合成示例:`python examples/selection_study.py NEW_OUTPUT`。 + [![CI](https://github.com/PureSaber/quant-fund/actions/workflows/tests.yml/badge.svg)](https://github.com/PureSaber/quant-fund/actions/workflows/tests.yml) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) diff --git a/docs/SELECTION.md b/docs/SELECTION.md new file mode 100644 index 0000000..8041a77 --- /dev/null +++ b/docs/SELECTION.md @@ -0,0 +1,72 @@ +# Frozen fund selection research + +`quant_fund.selection` consumes the existing `Dataset` and `Ledger` APIs. It does +not change NAV, historical terms, settlement or public output schemas. + +* `factor_asof`: versioned factor *returns* with `period_end,known_at,factor,value`. + Dates follow the existing daily disclosure precision. Return availability cannot + precede its period end; duplicates fail; only versions known at the decision enter. +* `style_oos`: existing unconstrained OLS fitted on the last complete contiguous + native-frequency fund/factor interval and frozen for later dates. Output includes + observed return, predicted style return, residual and completeness. This is a + return-exposure estimate, not actual holdings or evidence of skill. +* `persistence`: formation compound-return ranks within kind, strategy and identical + history endpoints. Later returns never affect formation eligibility. Missing or + later-ineligible funds stay visible; any incomplete peer suppresses that entire + peer's later ranks. A/C share groups have one deterministic representative. Rank + association is descriptive; no p-value, manager survival or skill inference. +* `screened_allocation`: explicit shortlist passed to existing allocation methods; + caps, cash buffer and peer share-class checks remain in that implementation. +* `preview_rebalance`: deep-copies the caller's ledger, attempts requests through + its existing `submit`, then checks invariants. Pending funds are skipped with a + reason. Sales do not increase spendable cash. Oversized purchases, locked shares, + notice windows and minimum subscriptions retain existing rejection reasons. + The input ledger is unchanged and accepted previews are unconfirmed requests. + +Use `ME` or `W-FRI` consistently for fund and factor periods. Factors must already +represent those exact native-period returns: this module does not resample them. +The existing Dataset determines complete NAV endpoints and known-at versions; +private monthly NAV is never interpolated. Test labels use the versions known at +the specified evaluation cutoff, not a claim of contemporaneous observation. + +## Whole-period OOS boundaries (C-FUND-01) + +Both `style_oos` and `persistence` use the same interval definition: +`(previous_native_endpoint, native_endpoint]`, where endpoints are the `ME` or +`W-FRI` labels of `Dataset.returns`. Only completed intervals whose **start is at +or after the decision** enter evaluation. A decision at an endpoint can start the +next full interval; a decision inside a month/week excludes that entire first +bucket. No return is clipped, prorated, interpolated or manufactured from the +decision-date NAV. Calendar endpoint labels retain Dataset's complete disclosed +NAV convention (for example, the last exchange session before a weekend month-end). +Factor returns must use the identical labeled native intervals. + +For a January 16 freeze, January's December 31–January 31 return is excluded; +the first monthly OOS interval is January 31–February 29. For a January 31 +freeze, that same February interval is included. A Wednesday freeze excludes the +week ending that Friday; a Friday freeze can start the next full Friday-to-Friday +interval. Thus a January 15 NAV jump cannot enter OOS returns frozen January 16. + +Both summaries retain `excluded_intervals` with start/end and +`native_return_interval_crosses_decision`, `candidate_periods`, `excluded_periods` +and `expected_periods`. Candidates are completed endpoints after the decision; +`candidate_periods = excluded_periods + expected_periods`. Style rows expose +`period_start` beside the `period_end` index; `complete_periods + missing_periods` +equals the expected count. Persistence rows expose `test_start`, `test_end`, +`expected_test_periods`, `complete_test_periods` and `missing_test_periods`. +Excluded crossing periods are never counted as missing eligible OOS observations. +Missing NAV endpoints still invalidate adjacent full-period returns, and missing +factor periods invalidate their style comparisons. Neither is filled with zero. + +When no full eligible interval exists, the summary is `no_complete_oos_periods`; +style returns an empty table and persistence retains the training cohort with +`test_return=NaN` and `test_complete=false`. Zero eligible periods do not become +a zero-return success. Run `python examples/verify_oos_boundaries.py NEW_OUTPUT` +for an independent raw-NAV control of the coordinator's predecision-jump case, +including both endpoint and within-period decisions at both supported frequencies. + +Run `python examples/selection_study.py ` for generated +synthetic input, frozen style/persistence tables and allocation/ledger previews. +Real fund conclusions still require authorized historical total-return NAV, +disclosure/terms versions, delisted/closed funds, factor release lineage and actual +dealing calendars. Missing data or a blocked preview is never a successful trade. diff --git a/examples/selection_study.py b/examples/selection_study.py new file mode 100644 index 0000000..2c1b349 --- /dev/null +++ b/examples/selection_study.py @@ -0,0 +1,42 @@ +"""Synthetic end-to-end frozen fund selection and ledger preview.""" + +import json +import sys +from pathlib import Path + +import numpy as np +import pandas as pd + +from quant_fund.data import Dataset +from quant_fund.demo import create_demo +from quant_fund.engine import Ledger +from quant_fund.selection import persistence, preview_rebalance, screened_allocation, style_oos + +root = Path(sys.argv[1]) +root.mkdir(parents=True, exist_ok=False) +dataset = Dataset.load(create_demo(root / "synthetic-data")) +table, summary = persistence(dataset, decision="2024-01-02", evaluation="2024-07-31") +table.to_csv(root / "persistence.csv", index=False) +dates = pd.date_range("2022-01-31", "2024-07-31", freq="ME") +factors = pd.DataFrame( + { + "period_end": dates, + "known_at": dates, + "factor": "synthetic_market", + "value": np.random.default_rng(7).normal(0, 0.03, len(dates)), + } +) +path, style = style_oos( + dataset, "PUB_EQ_A", factors, decision="2024-01-02", evaluation="2024-07-31" +) +path.to_csv(root / "style-oos.csv") +weights, _ = screened_allocation(dataset, "2024-01-02", ["PUB_EQ_A", "PUB_BD_A"], max_weight=0.6) +ledger = Ledger(dataset, 100_000) +ledger.advance("2024-01-02") +orders, preview = preview_rebalance(ledger, weights) +orders.to_csv(root / "preview.csv", index=False) +(root / "summary.json").write_text( + json.dumps({"persistence": summary, "style": style, "preview": preview}, default=str, indent=2), + encoding="utf-8", +) +print(root.resolve()) diff --git a/examples/verify_oos_boundaries.py b/examples/verify_oos_boundaries.py new file mode 100644 index 0000000..fd9125c --- /dev/null +++ b/examples/verify_oos_boundaries.py @@ -0,0 +1,89 @@ +"""Independent raw-NAV controls for coordinator finding C-FUND-01 (synthetic).""" + +import json +import sys +from pathlib import Path + +import numpy as np +import pandas as pd + +from quant_fund.data import Dataset, Fund, validate_nav +from quant_fund.selection import persistence, style_oos + +root = Path(sys.argv[1]) +root.mkdir(parents=True, exist_ok=False) +calendar = pd.bdate_range("2022-01-03", "2024-07-31") +levels = np.where(calendar >= "2024-01-15", 2.0, 1.0) +fund = Fund("F", "Synthetic", "Synthetic", "equity", "public", "2021-01-01", "2021-01-01") +nav = validate_nav( + pd.DataFrame( + { + "fund_id": "F", + "nav_date": calendar, + "known_at": calendar, + "unit_nav": levels, + "total_return_nav": levels, + "source": "synthetic-boundary-control", + } + ) +) +dataset = Dataset( + {"F": fund}, + nav, + calendar, + pd.DataFrame(columns=["fund_id", "ex_date", "pay_date", "known_at", "cash_per_share"]), + {"classification": "synthetic"}, + "C-FUND-01-control", +) +cases = [ + ("ME", "2024-01-16", "2024-07-31", "2024-02-29", 1), + ("ME", "2024-01-31", "2024-07-31", "2024-02-29", 0), + ("W-FRI", "2024-01-17", "2024-03-01", "2024-01-26", 1), + ("W-FRI", "2024-01-19", "2024-03-01", "2024-01-26", 0), +] +results = [] +for frequency, decision, evaluation, first_endpoint, excluded in cases: + ends = pd.date_range(calendar[0], calendar[-1], freq=frequency) + factors = pd.DataFrame( + { + "period_end": ends, + "known_at": ends, + "factor": "market", + "value": np.sin(np.arange(len(ends))) * 0.02, + } + ) + path, style = style_oos( + dataset, "F", factors, decision=decision, evaluation=evaluation, frequency=frequency + ) + ranks, info = persistence( + dataset, decision=decision, evaluation=evaluation, frequency=frequency + ) + # This control is independent of the interval helper and both return aggregators. + raw = nav.loc[(nav.nav_date >= decision) & (nav.nav_date <= evaluation)] + expected = float(raw.total_return_nav.iloc[-1] / raw.total_return_nav.iloc[0] - 1) + assert expected == 0.0 and (path.fund_return == expected).all() + assert ranks.test_return.iloc[0] == expected + assert str(path.index[0].date()) == first_endpoint + assert style["expected_periods"] == info["expected_periods"] == len(path) == 6 + assert style["excluded_periods"] == info["excluded_periods"] == excluded + assert style["missing_periods"] == ranks.missing_test_periods.iloc[0] == 0 + results.append( + { + "frequency": frequency, + "decision": decision, + "evaluation": evaluation, + "true_postdecision_raw_nav_return": expected, + "first_style_period": str(path.index[0].date()), + "first_style_return": float(path.fund_return.iloc[0]), + "persistence_test_return": float(ranks.test_return.iloc[0]), + "periods": len(path), + "excluded": style["excluded_intervals"], + "status": "pass", + } + ) + key = f"{frequency}-{decision}" + path.to_csv(root / f"{key}-style.csv") + ranks.to_csv(root / f"{key}-persistence.csv", index=False) +report = {"finding": "C-FUND-01", "evidence_kind": "synthetic", "cases": results} +(root / "independent-controls.json").write_text(json.dumps(report, indent=2), encoding="utf-8") +print(json.dumps(report, indent=2)) diff --git a/src/quant_fund/selection.py b/src/quant_fund/selection.py new file mode 100644 index 0000000..8da4ab2 --- /dev/null +++ b/src/quant_fund/selection.py @@ -0,0 +1,263 @@ +"""Native-frequency, frozen fund research and non-mutating ledger previews.""" + +from copy import deepcopy +from dataclasses import replace + +import numpy as np +import pandas as pd + +from .data import day +from .research import allocate, latest_complete_interval, style_regression + + +def factor_asof(observations, at): + required = {"period_end", "known_at", "factor", "value"} + if not required.issubset(observations) or observations.empty: + raise ValueError("factor return periods, known_at, names and values required") + frame = observations.copy() + for key in ("period_end", "known_at"): + frame[key] = frame[key].map(day) + if frame[["period_end", "known_at", "factor"]].isna().any().any(): + raise ValueError("missing factor identity or time") + if (frame.known_at < frame.period_end).any(): + raise ValueError("factor return cannot be known before period end") + if frame.duplicated(["period_end", "known_at", "factor"]).any(): + raise ValueError("duplicate factor versions") + if not np.isfinite(frame.value.to_numpy(dtype=float)).all(): + raise ValueError("finite factor returns required") + frame = frame.loc[frame.known_at <= day(at)].sort_values("known_at") + frame = frame.drop_duplicates(["period_end", "factor"], keep="last") + return frame.pivot(index="period_end", columns="factor", values="value").sort_index() + + +def _native_oos_intervals(decision, evaluation, frequency): + """Full native buckets (previous endpoint, endpoint], with no partial returns. + + Boundaries are the ME/W-FRI labels used by Dataset.returns. An endpoint decision + is the closing boundary of training and may start the next full return interval. + A decision inside a bucket excludes that bucket, even if its endpoint is later. + """ + if frequency not in {"ME", "W-FRI"}: + raise ValueError("native research frequency must be ME or W-FRI") + offset = pd.tseries.frequencies.to_offset(frequency) + ends = pd.date_range(decision, evaluation, freq=frequency) + ends = ends[ends > decision] + starts = pd.DatetimeIndex([end - offset for end in ends]) + included = starts >= decision + rejected = [ + { + "period_start": str(start.date()), + "period_end": str(end.date()), + "reason": "native_return_interval_crosses_decision", + } + for start, end in zip(starts[~included], ends[~included], strict=True) + ] + intervals = pd.DataFrame({"period_start": starts[included]}, index=ends[included]) + intervals.index.name = "period_end" + return intervals, { + "period_boundary_policy": "(previous_native_endpoint, native_endpoint]; " + "period_start >= decision; no partial-period interpolation", + "candidate_periods": len(ends), + "expected_periods": int(included.sum()), + "excluded_periods": len(rejected), + "excluded_intervals": rejected, + } + + +def style_oos(dataset, fund_id, factors, *, decision, evaluation, frequency="ME", window=24): + """Freeze existing OLS at decision; expose every missing OOS fund/factor return.""" + decision, evaluation = day(decision), day(evaluation) + if decision >= evaluation: + raise ValueError("evaluation must follow decision") + training = dataset.returns(decision, frequency, window) + if fund_id not in training: + raise ValueError("fund has no known training history") + known_factors = factor_asof(factors, decision) + joined = pd.concat([training[fund_id].rename("fund"), known_factors], axis=1).reindex( + training.index + ) + joined = latest_complete_interval(joined) + if joined.empty: + raise ValueError("no contiguous fund/factor training interval") + model = style_regression(joined.fund, joined.drop(columns="fund"), window=window) + intervals, interval_audit = _native_oos_intervals(decision, evaluation, frequency) + index = intervals.index + future = dataset.returns(evaluation, frequency, len(index) + 2).reindex(index) + factor_test = factor_asof(factors, evaluation).reindex( + index=index, columns=list(model["exposures"]) + ) + fund_test = future[fund_id] if fund_id in future else pd.Series(np.nan, index=index) + prediction = factor_test.mul(pd.Series(model["exposures"])).sum( + axis=1, min_count=factor_test.shape[1] + ) + prediction += model["intercept"] + result = pd.DataFrame({"fund_return": fund_test, "style_expected": prediction}) + result["residual"] = result.fund_return - result.style_expected + result["complete"] = result.notna().all(axis=1) + result["period_start"] = intervals.period_start + return result, { + "status": "evaluated" if len(index) else "no_complete_oos_periods", + "decision": str(decision.date()), + "evaluation": str(evaluation.date()), + "frequency": frequency, + "frozen_model": model, + "training_start": str(joined.index[0].date()), + "training_end": str(joined.index[-1].date()), + **interval_audit, + "complete_periods": int(result.complete.sum()), + "missing_periods": int((~result.complete).sum()), + "evidence_kind": dataset.metadata.get("classification", "unclassified"), + "limits": "Return exposures, not holdings. Evaluation uses versions known at evaluation. " + "No interpolation, fee model or evidence of manager skill.", + } + + +def persistence(dataset, *, decision, evaluation, frequency="ME", window=24, min_periods=12): + """Compare frozen within-peer formation ranks with complete later-period ranks. + + Every training-eligible fund stays in the output, including later unavailable ones. + Common training endpoints and kind/strategy define peer comparisons. + """ + decision, evaluation = day(decision), day(evaluation) + if decision >= evaluation or type(min_periods) is not int or min_periods < 3: + raise ValueError("later evaluation and at least three training periods required") + training = dataset.returns(decision, frequency, window) + intervals, interval_audit = _native_oos_intervals(decision, evaluation, frequency) + index = intervals.index + future = dataset.returns(evaluation, frequency, len(index) + 2).reindex(index) + rows = [] + for code in training: + series = latest_complete_interval(training[code]) + if len(series) < min_periods: + continue + fund = dataset.fund_at(code, decision, decision) + later = future[code] if code in future else pd.Series(np.nan, index=index) + complete = bool(len(index) and later.notna().all()) + rows.append( + { + "fund_id": code, + "kind": fund.kind, + "strategy": fund.strategy, + "share_group": fund.share_group or code, + "training_start": series.index[0], + "training_end": series.index[-1], + "training_periods": len(series), + "training_return": float((1 + series).prod() - 1), + "test_return": float((1 + later).prod() - 1) if complete else np.nan, + "test_complete": complete, + "expected_test_periods": len(index), + "complete_test_periods": int(later.notna().sum()), + "missing_test_periods": int(later.isna().sum()), + "test_start": intervals.period_start.iloc[0] if len(index) else pd.NaT, + "test_end": index[-1] if len(index) else pd.NaT, + "terms_version_id": fund.version_id, + } + ) + result = pd.DataFrame(rows) + if result.empty: + return result, { + "status": "insufficient_training", + "rank_correlation": None, + **interval_audit, + } + # Deterministic class representative chosen without looking at later performance. + result = result.sort_values("fund_id").drop_duplicates("share_group").reset_index(drop=True) + keys = ["kind", "strategy", "training_start", "training_end"] + result["peer_count"] = result.groupby(keys).fund_id.transform("count") + result["training_rank"] = result.groupby(keys).training_return.rank(pct=True) + result["peer_complete"] = result.groupby(keys).test_complete.transform("all") + result["test_rank"] = result.groupby(keys).test_return.rank(pct=True) + valid = result.peer_complete & result.peer_count.ge(2) + result.loc[~valid, "test_rank"] = np.nan + result.loc[result.peer_count.lt(2), "training_rank"] = np.nan + x, y = result.loc[valid, "training_rank"], result.loc[valid, "test_rank"] + correlation = float(x.corr(y)) if len(x) >= 3 and x.nunique() > 1 and y.nunique() > 1 else None + return result, { + "status": "evaluated" if len(index) else "no_complete_oos_periods", + "decision": str(decision.date()), + "evaluation": str(evaluation.date()), + "frequency": frequency, + **interval_audit, + "cohort_size": len(result), + "incomplete_funds": int((~result.test_complete).sum()), + "rank_correlation": correlation, + "evidence_kind": dataset.metadata.get("classification", "unclassified"), + "limits": "Descriptive within-peer ranks; no survivor-only aggregate " + "or persistence significance.", + } + + +def screened_allocation(dataset, date, selected, strategy="equal", **kwargs): + """Delegate portfolio construction to existing optimizers on an explicit frozen shortlist.""" + selected = tuple(selected) + if not selected or len(set(selected)) != len(selected) or set(selected) - set(dataset.funds): + raise ValueError("unique known selected fund IDs required") + subset = replace(dataset, funds={code: dataset.funds[code] for code in sorted(selected)}) + return allocate(subset, date, strategy, **kwargs) + + +def preview_rebalance(ledger, targets): + """Preview through a deep copy of the existing ledger; never mutate its account. + + Whole requested adjustments either pass existing submit checks or are reported + rejected. No optimistic redemption proceeds, partial hidden allocation or new + accounting implementation is introduced. + """ + if ledger.current_date is None: + raise ValueError("advance the existing ledger to the decision date first") + weights = pd.Series(targets, dtype=float) + if weights.index.duplicated().any() or set(weights.index) - set(ledger.dataset.funds): + raise ValueError("unique known target funds required") + if not np.isfinite(weights).all() or (weights < 0).any() or weights.sum() > 1 + 1e-10: + raise ValueError("long-only targets with explicit residual cash required") + clone = deepcopy(ledger) + snapshot = clone.snapshot() + holdings = clone.holdings() + held = holdings.set_index("fund_id") if not holdings.empty else pd.DataFrame() + pending = {order.fund_id for order in clone.orders if order.status == "pending"} + proposals, results = [], [] + for code in sorted(set(weights.index) | (set(held.index) if not held.empty else set())): + if code in pending: + results.append( + {"fund_id": code, "status": "blocked", "reason": "existing pending order"} + ) + continue + value = float(held.loc[code, "value"]) if code in held.index else 0.0 + difference = float(weights.get(code, 0)) * snapshot["total_value"] - value + if abs(difference) <= 1e-8: + continue + if difference < 0: + proposals.append((0, code, "SELL", {"shares": -difference / held.loc[code, "mark"]})) + else: + proposals.append((1, code, "BUY", {"amount": difference})) + for _, code, side, arguments in sorted(proposals): + try: + order = clone.submit(code, side, **arguments) + results.append( + { + "fund_id": code, + "side": side, + **arguments, + "status": "preview_accepted", + "deal_date": str(order.deal_date.date()), + "terms_version_id": order.terms_version_id, + } + ) + except ValueError as exc: + results.append( + { + "fund_id": code, + "side": side, + **arguments, + "status": "blocked", + "reason": str(exc), + } + ) + clone.check() + return pd.DataFrame(results), { + "mode": "non_mutating_ledger_preview", + "before": snapshot, + "after": clone.snapshot(), + "limits": "Accepted previews are pending requests, " + "not confirmed fills or permission to trade.", + } diff --git a/tests/test_selection.py b/tests/test_selection.py new file mode 100644 index 0000000..db8d80a --- /dev/null +++ b/tests/test_selection.py @@ -0,0 +1,89 @@ +import numpy as np +import pandas as pd +import pytest + +from quant_fund.data import Dataset +from quant_fund.engine import Ledger +from quant_fund.selection import ( + factor_asof, + persistence, + preview_rebalance, + screened_allocation, + style_oos, +) + + +def test_factor_versions_are_not_backdated(): + factors = pd.DataFrame( + { + "period_end": ["2023-01-31"] * 2, + "known_at": ["2023-02-01", "2024-01-01"], + "factor": ["equity"] * 2, + "value": [0.01, 9.0], + } + ) + assert factor_asof(factors, "2023-01-31").empty + assert factor_asof(factors, "2023-02-01").equity.iloc[0] == 0.01 + + +def test_native_frequency_style_and_frozen_training(demo_directory): + data = Dataset.load(demo_directory) + ends = pd.date_range("2022-01-31", "2025-12-31", freq="ME") + rng = np.random.default_rng(17) + factors = pd.DataFrame( + { + "period_end": ends, + "known_at": ends, + "factor": "market", + "value": rng.normal(0, 0.03, len(ends)), + } + ) + path, info = style_oos( + data, "PUB_EQ_A", factors, decision="2024-01-02", evaluation="2024-07-31" + ) + assert len(path) == 6 + assert info["excluded_periods"] == 1 + assert path.index[0] == pd.Timestamp("2024-02-29") + train = data.returns("2024-01-02", "ME", 24)["PUB_EQ_A"].dropna() + factor = factor_asof(factors, "2024-01-02").reindex(train.index).market + # Independent single-factor covariance/variance formula. + slope = np.cov(train, factor, ddof=1)[0, 1] / np.var(factor, ddof=1) + assert info["frozen_model"]["exposures"]["market"] == pytest.approx(slope) + revised = data.nav.copy() + revised.loc[revised.known_at > pd.Timestamp("2024-01-02"), "total_return_nav"] *= 2 + data.nav = revised + _, changed = style_oos( + data, "PUB_EQ_A", factors, decision="2024-01-02", evaluation="2024-07-31" + ) + assert changed["frozen_model"] == info["frozen_model"] + + +def test_persistence_keeps_missing_funds(demo_directory): + data = Dataset.load(demo_directory) + data.nav = data.nav.loc[ + ~((data.nav.fund_id == "PUB_EQ_A") & (data.nav.nav_date > "2024-02-01")) + ] + table, info = persistence(data, decision="2024-01-02", evaluation="2024-07-31") + assert "PUB_EQ_A" in set(table.fund_id) + assert info["incomplete_funds"] > 0 + equities = table.loc[(table.kind == "public") & (table.strategy == "equity")] + assert equities.test_rank.isna().all() + + +def test_existing_optimizer_and_nonmutating_cash_preview(demo_directory): + data = Dataset.load(demo_directory) + weights, _ = screened_allocation( + data, "2024-01-02", ["PUB_EQ_A", "PUB_BD_A"], max_weight=0.6, min_periods=12 + ) + assert weights.sum() == pytest.approx(0.95) + ledger = Ledger(data, 100_000) + ledger.advance("2024-01-02") + before = ledger.snapshot() + orders, report = preview_rebalance(ledger, weights) + assert len(orders) == 2 and (orders.status == "preview_accepted").all() + assert report["after"]["cash"] == pytest.approx(5000) + assert ledger.snapshot() == before and len(ledger.orders) == 0 + ledger.submit("PUB_EQ_A", "BUY", amount=90_000) + blocked, _ = preview_rebalance(ledger, {"PUB_EQ_A": 0.5, "PUB_BD_A": 0.5}) + assert (blocked.status == "blocked").all() + assert len(ledger.orders) == 1 diff --git a/tests/test_selection_boundaries.py b/tests/test_selection_boundaries.py new file mode 100644 index 0000000..863d484 --- /dev/null +++ b/tests/test_selection_boundaries.py @@ -0,0 +1,138 @@ +"""Regression controls for C-FUND-01: whole native intervals must follow freezing.""" + +import numpy as np +import pandas as pd +import pytest + +from quant_fund.selection import persistence, style_oos + + +def inputs(make_dataset, frequency): + calendar = pd.bdate_range("2022-01-03", "2024-07-31") + nav = np.where(calendar >= "2024-01-15", 2.0, 1.0) + dataset = make_dataset( + calendar=calendar, prices=nav, inception="2021-01-01", known_at="2021-01-01" + ) + endpoints = pd.date_range(calendar[0], calendar[-1], freq=frequency) + factors = pd.DataFrame( + { + "period_end": endpoints, + "known_at": endpoints, + "factor": "market", + "value": np.sin(np.arange(len(endpoints))) * 0.02, + } + ) + return dataset, factors + + +@pytest.mark.parametrize( + "frequency,decision,evaluation,first_start,first_end,excluded_end", + [ + ("ME", "2024-01-16", "2024-07-31", "2024-01-31", "2024-02-29", "2024-01-31"), + ("ME", "2024-01-31", "2024-07-31", "2024-01-31", "2024-02-29", None), + ("W-FRI", "2024-01-17", "2024-03-01", "2024-01-19", "2024-01-26", "2024-01-19"), + ("W-FRI", "2024-01-19", "2024-03-01", "2024-01-19", "2024-01-26", None), + ], +) +def test_predecision_jump_never_enters_oos( + make_dataset, frequency, decision, evaluation, first_start, first_end, excluded_end +): + dataset, factors = inputs(make_dataset, frequency) + path, style = style_oos( + dataset, "F", factors, decision=decision, evaluation=evaluation, frequency=frequency + ) + cohort, ranks = persistence( + dataset, decision=decision, evaluation=evaluation, frequency=frequency + ) + # Independent investor-period check: NAV is identically 2 after the decision. + raw = dataset.nav.loc[dataset.nav.nav_date >= decision, "total_return_nav"] + expected = raw.iloc[-1] / raw.iloc[0] - 1 + assert expected == 0 + assert (path.fund_return == expected).all() + assert cohort.test_return.iloc[0] == expected + assert path.index[0] == pd.Timestamp(first_end) + assert path.period_start.iloc[0] == pd.Timestamp(first_start) + assert (path.period_start >= pd.Timestamp(decision)).all() + assert cohort.test_start.iloc[0] == pd.Timestamp(first_start) + assert cohort.test_end.iloc[0] == pd.Timestamp(evaluation) + assert len(path) == style["expected_periods"] == ranks["expected_periods"] == 6 + assert style["complete_periods"] == cohort.complete_test_periods.iloc[0] == 6 + assert style["missing_periods"] == cohort.missing_test_periods.iloc[0] == 0 + for summary in (style, ranks): + assert summary["candidate_periods"] == 6 + bool(excluded_end) + assert summary["excluded_periods"] == bool(excluded_end) + if excluded_end: + assert summary["excluded_intervals"][0]["period_end"] == excluded_end + assert summary["excluded_intervals"][0]["reason"] == ( + "native_return_interval_crosses_decision" + ) + else: + assert summary["excluded_intervals"] == [] + + +@pytest.mark.parametrize( + "frequency,decision,evaluation,missing_nav,missing_factor", + [ + ("ME", "2024-01-16", "2024-07-31", "2024-03-29", "2024-05-31"), + ("W-FRI", "2024-01-17", "2024-03-01", "2024-02-02", "2024-02-16"), + ], +) +def test_missing_native_endpoints_are_separate_from_excluded_intervals( + make_dataset, frequency, decision, evaluation, missing_nav, missing_factor +): + dataset, factors = inputs(make_dataset, frequency) + dataset.nav = dataset.nav.loc[dataset.nav.nav_date != pd.Timestamp(missing_nav)] + factors = factors.loc[factors.period_end != pd.Timestamp(missing_factor)] + path, style = style_oos( + dataset, "F", factors, decision=decision, evaluation=evaluation, frequency=frequency + ) + cohort, ranks = persistence( + dataset, decision=decision, evaluation=evaluation, frequency=frequency + ) + # A missing native NAV boundary invalidates both adjacent returns; a different + # missing factor invalidates one additional style comparison. None is zero-filled. + assert len(path) == style["expected_periods"] == ranks["expected_periods"] == 6 + assert path.fund_return.isna().sum() == cohort.missing_test_periods.iloc[0] == 2 + assert cohort.complete_test_periods.iloc[0] == 4 + assert style["missing_periods"] == 3 and style["complete_periods"] == 3 + assert style["excluded_periods"] == ranks["excluded_periods"] == 1 + assert not cohort.test_complete.iloc[0] and pd.isna(cohort.test_return.iloc[0]) + + +@pytest.mark.parametrize( + "frequency,decision,evaluation", + [("ME", "2024-01-16", "2024-01-31"), ("W-FRI", "2024-01-17", "2024-01-19")], +) +def test_only_crossing_interval_is_unavailable_not_zero_performance( + make_dataset, frequency, decision, evaluation +): + dataset, factors = inputs(make_dataset, frequency) + path, style = style_oos( + dataset, "F", factors, decision=decision, evaluation=evaluation, frequency=frequency + ) + cohort, ranks = persistence( + dataset, decision=decision, evaluation=evaluation, frequency=frequency + ) + assert path.empty and not cohort.empty + for summary in (style, ranks): + assert summary["status"] == "no_complete_oos_periods" + assert summary["candidate_periods"] == summary["excluded_periods"] == 1 + assert summary["expected_periods"] == 0 + assert style["complete_periods"] == style["missing_periods"] == 0 + assert cohort.expected_test_periods.iloc[0] == cohort.missing_test_periods.iloc[0] == 0 + assert pd.isna(cohort.test_return.iloc[0]) and not cohort.test_complete.iloc[0] + + +@pytest.mark.parametrize("frequency", ["ME", "W-FRI"]) +def test_boundary_exclusion_is_stable_when_evaluation_extends(make_dataset, frequency): + dataset, factors = inputs(make_dataset, frequency) + decision = "2024-01-16" + short, before = style_oos( + dataset, "F", factors, decision=decision, evaluation="2024-03-31", frequency=frequency + ) + long, after = style_oos( + dataset, "F", factors, decision=decision, evaluation="2024-07-31", frequency=frequency + ) + pd.testing.assert_frame_equal(short, long.loc[short.index]) + assert before["frozen_model"] == after["frozen_model"] + assert before["excluded_intervals"] == after["excluded_intervals"]