Skip to content
Merged
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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -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)

Expand Down
72 changes: 72 additions & 0 deletions docs/SELECTION.md
Original file line number Diff line number Diff line change
@@ -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 <new-output-directory>` 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.
42 changes: 42 additions & 0 deletions examples/selection_study.py
Original file line number Diff line number Diff line change
@@ -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())
89 changes: 89 additions & 0 deletions examples/verify_oos_boundaries.py
Original file line number Diff line number Diff line change
@@ -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))
Loading