diff --git a/docs/backtest_standard_v1.zh-CN.md b/docs/backtest_standard_v1.zh-CN.md index efc7b17b..918e882b 100644 --- a/docs/backtest_standard_v1.zh-CN.md +++ b/docs/backtest_standard_v1.zh-CN.md @@ -4,6 +4,8 @@ 本文是 [策略晋级与风险标准](strategy_promotion_risk_standard.zh-CN.md) 的补充,规定研究回测「必须报告什么、怎么算、怎么标身份、最少要多少观察」。它不替代、不修改晋级标准的指标清单、`strategy_evidence_package.v2/v3` schema、`BacktestOrchestrator.run_promotion` 结构门或 [Kelly 契约](kelly_contract_v2.zh-CN.md)。 +指标定义、成熟系统的重要分组、已实现能力与真实输入缺口见[统一量化指标目录](unified_metric_catalog.zh-CN.md)。平均盈亏比与 Profit Factor 分开,日收益观察与闭合交易分开;B3 可选诊断不替代逐笔记账或增加晋级阈值。 + ## 0. 边界 - **本文不设任何及格线。** 不存在全系统统一的 Sharpe、CAGR、回撤、DSR、PBO 或成本门槛。每个候选的报告项、排序项和否决项(含指标、比较符、阈值、窗口、成本档和不可计算处理)必须在读取留出结果**之前**由该候选预先登记,并经人工验收(human acceptance)后才生效。未登记或未验收的阈值不能用来宣称「通过」。 diff --git a/docs/unified_metric_catalog.md b/docs/unified_metric_catalog.md new file mode 100644 index 00000000..ec751094 --- /dev/null +++ b/docs/unified_metric_catalog.md @@ -0,0 +1,44 @@ +# QSL unified quantitative metrics: semantics, capabilities and gaps + +This catalog explains the existing [backtest standard](backtest_standard_v1.zh-CN.md), [window metrics](window_metrics_semantics.zh-CN.md) and research-only B3 `build_unified_net_report`. It adds no promotion thresholds, candidates, trading permission or risk budget. See the [Chinese version](unified_metric_catalog.zh-CN.md). + +## Outcome metrics + +|Metric|Definition|Capability and boundary| +|---|---|---| +|Positive-day share `win_rate`|Positive days / all valid days, including zeros|Existing window metric; not closed-trade win rate| +|Win rate excluding zeros|Positive / (positive + negative) observations|Existing `daily_win_rate_ex_zero`; optional B3 `net_win_rate_ex_zero_per_period`; undefined for all-zero samples| +|Payoff ratio|Mean gain / absolute mean loss|Kelly has mean inputs; optional B3 `net_payoff_ratio_per_period`; both sides required| +|Profit Factor|Total gains / absolute total losses|Existing daily `profit_factor`; optional B3 `net_profit_factor_per_period`; undefined without losses, genuinely zero with losses and no gains| +|Sample mean net return|Arithmetic mean of same-period net returns, including zeros|Optional B3 `mean_net_return_per_period`; neither future profit nor compound growth| +|Closed-trade outcomes|Win rate, payoff, Profit Factor and expectancy on net realized P&L|The standard requires trade win rate/expectancy, but return-series tools do not implement trade pairing/accounting| + +Enable the four B3 diagnostics with `include_outcome_diagnostics=True`. Default output retains its original eight metrics. Each new result records positive/negative/zero counts, `aggregation_level=return_observations_not_trades`, `input_basis=same_period_net_returns` and `descriptive_only=true`. Undefined, overflowing or nonzero-underflowing results are `UNCOMPUTABLE` with null value and reason, never infinity or fabricated zero. A complete sample with exactly zero net sum, including all-zero observations or exact positive/negative cancellation, has a known zero mean. + +For a consistent sample, `Profit Factor = payoff ratio × positive count / negative count`. The mean including zeros is `p_positive × mean_gain − p_negative × absolute_mean_loss`, with both probabilities using all observations. Do not substitute the excluding-zero probability into this formula. A high win rate can have negative expectancy; positive arithmetic mean does not guarantee positive log growth. + +## Core groups for a mature system + +|Purpose|Important metrics|Current unified capability| +|---|---|---| +|Return and benchmark|Net log growth, cumulative return, CAGR, aligned excess return, alpha/beta and tracking error|B3 net per-period growth; existing window returns/CAGR/benchmark comparisons, alpha/IR and alignment counts; other attribution/tracking-error projections need explicit conventions| +|Risk-adjusted return|Sharpe, Sortino, Calmar, Information Ratio|Window implementation; B3 unannualized ddof=1 Sharpe; frequency and risk-free conventions must align| +|Loss and tails|Drawdown, monetary loss/duration/recovery, CVaR/ES, VaR, stress loss|B3 initial-NAV drawdown and exact worst-5% probability-mass CVaR95; monetary/duration/VaR/stress projections still need separate inputs| +|Outcome distribution|Win rate, payoff, Profit Factor, mean net return, loss streaks, counts and uncertainty|Four research diagnostics implemented; trade/streak definitions require accounting; bootstrap is separate, not automatic confidence intervals for new outcomes| +|Statistical reliability|PSR, DSR, MinTRL, PBO, walk-forward/OOS, parameter stability|Primitives/B3 available; PBO/bootstrap separate; actual cumulative trials and frozen assumptions must be verified| +|Execution and cost|Turnover, commissions/spread/impact/financing, cost drag, slippage/fill/rejection rates and latency|A2 models and B3 cost drag available; actual quality and denominators require timestamped order/quote/fill evidence| +|Portfolio and capacity|Correlation, concentration, risk contribution, cash/exposure, liquidity and capacity|Separate risk/portfolio tools; no claim of a completed B3 capacity or live-portfolio projection| +|Operations and data|Source/PIT, freshness, funds/position reconciliation, duplicate/unknown orders, report delivery/recovery|Actual runtime/source/receipts required; source CI is insufficient| + +Select metrics for the research/trade/portfolio/operations purpose, rather than requiring every strategy to use every metric. Disclose missing preregistered items. Reporting, ranking, veto roles and thresholds remain subject to the existing frozen contract. + +## Common evidence requirements + +1. Declare observation unit, zero handling, count denominator, window and holdings coverage. `per_period` does not imply daily or annualized. +2. Align costs, cash flows, corporate actions, currencies, cash/financing and signal/fill timing. A `net_returns` argument does not attest underlying accounting; bind A2 reconciliation and source evidence. +3. Declare calendars/annualization for equity sessions versus 24/7 crypto. Window Sharpe defaults to ddof=0; research inference uses ddof=1. +4. Freeze FIFO/other pairing, partial fills/closes, multi-leg grouping, strategy attribution, fees/FX, holding periods and open positions before trade statistics. Orders, fills and positive days are not automatically winning trades. +5. Preserve sample size, data identity and computability. No observed losses does not mean no risk. Missing trade records/prices/NAV are not zeros. Some legacy window ratios retain NaN for compatibility; consumers must handle undefined values explicitly. +6. Bind DSR to the actual cumulative trials under the frozen failed/rejected/interrupted counting rules; preserve PBO/WFA/OOS timing and isolation. Declared ledger counts, implemented formulas and synthetic regression passes do not establish an edge or live adoption. + +This batch adds only optional B3 period-return diagnostics and the catalog. Closed-trade statistics remain a separate accounting-dependent implementation; drawdown recovery, capacity and live execution quality follow their own evidence. It does not change existing window semantics, original B3 results, gates, sizing or production pins, or replace B1/B2/B4 freezing and E1 review. diff --git a/docs/unified_metric_catalog.zh-CN.md b/docs/unified_metric_catalog.zh-CN.md new file mode 100644 index 00000000..5ebbbecb --- /dev/null +++ b/docs/unified_metric_catalog.zh-CN.md @@ -0,0 +1,51 @@ +# QSL 统一量化指标:口径、能力与缺口 + +适用于既有[回测标准](backtest_standard_v1.zh-CN.md)、[窗口指标](window_metrics_semantics.zh-CN.md)和研究侧 B3 `build_unified_net_report`。这是指标解释与能力目录,不新增策略晋级阈值、候选、交易权限或风险预算。英文版见 [Unified metric catalog](unified_metric_catalog.md)。 + +## 1. 胜率、盈亏比与 Profit Factor 分开报告 + +|指标|定义|现有能力与边界| +|---|---|---| +|正收益日比例 `win_rate`|正收益日数 / 全部有效日数,零收益日计入分母|旧窗口指标已实现;不是逐笔交易胜率| +|剔零胜率|正收益观察数 /(正 + 负收益观察数)|窗口 `daily_win_rate_ex_zero` 已实现;B3 可选 `net_win_rate_ex_zero_per_period`,全零样本不可计算| +|平均盈亏比 Payoff ratio|平均盈利幅度 / 平均亏损幅度绝对值|Kelly 有均值输入;B3 可选 `net_payoff_ratio_per_period`。缺正或负任一侧不能假造均值| +|盈利因子 Profit Factor|盈利总和 / 亏损总和绝对值|旧窗口 `profit_factor` 基于日收益;B3 可选 `net_profit_factor_per_period`。无亏损观察不可计算,只有亏损时真实值为 0| +|样本平均净收益|同频净收益率算术均值,包含零收益观察|B3 可选 `mean_net_return_per_period`,不是未来利润预测,也不是复利增长| +|逐笔胜率、盈亏比、盈利因子与 expectancy|以已闭合交易的净 P&L 为观察单位|回测标准已要求逐笔胜率/expectancy,但上述日收益/单期输入不提供逐笔实现;仍需真实配对成交和记账合同| + +单期新诊断通过 `include_outcome_diagnostics=True` 加入 B3,默认保留原八项输出。所有新结果带正/负/零观察数、`aggregation_level=return_observations_not_trades`、`input_basis=same_period_net_returns`、`descriptive_only=true`。未知/无定义或数值溢出/非零下溢时 `UNCOMPUTABLE`、`value=null`、明确原因;不写无穷大或假 0。完整样本的精确净和为 0 时,平均收益的 0 是已知值;全零和正负收益精确相消均属于这种情况。 + +同一口径下,`Profit Factor = 平均盈亏比 × 盈利观察数 / 亏损观察数`;它不是平均盈亏比本身。包含零观察的平均收益为 `p正 × 平均正收益 − p负 × 平均亏损幅度`,这里两个概率均以全部观察为分母。剔零胜率不能直接代入这个含零均值公式。 + +高胜率仍可能负期望;低胜率也可能由较高盈亏比获得正期望。胜率和盈亏比要一起看净收益、样本量、持有周期与尾部损失,不能单独设全系统及格线。算术均值与净对数增长也不同,均值为正不保证复利增长为正。 + +## 2. 成熟系统的核心指标分组 + +|维度|重要指标|当前统一能力| +|---|---|---| +|收益与基准|净对数增长、累计收益、CAGR、同窗超额收益、Alpha/Beta及跟踪误差|B3 提供净单期对数增长;窗口提供累计收益/CAGR/基准对比、Alpha/IR和对齐计数;其他基准归因/跟踪误差需明确投影与口径| +|风险调整收益|Sharpe、Sortino、Calmar、Information Ratio|窗口已实现;B3 提供单期 ddof=1 Sharpe。频率、无风险基准和年化口径必须对齐| +|亏损与尾部|最大回撤、回撤金额/持续与恢复期、CVaR/ES、VaR、极端情景损失|B3 含初始 NAV 的回撤和精确最差5%质量 CVaR95;回撤金额/恢复期、VaR及压力情景仍需单列输入/统一投影| +|收益分布|胜率、盈亏比、Profit Factor、平均净收益、连续亏损、样本量与置信区间|前四项研究诊断已提供;逐笔/连亏依赖记账与观察单位;bootstrap 能力已有,不自动给新诊断附置信区间| +|统计可靠性|PSR、DSR、MinTRL、PBO、walk-forward/OOS、参数稳定性|统计原语与 B3 已有;PBO/bootstrap是独立函数,真实累计试验账本和冻结假设仍须核验| +|执行与成本|换手、佣金/价差/冲击/融资成本、成本拖累、滑点/成交率/拒单率/执行延迟|A2 成交成本模型和 B3 成本拖累已有;真实执行质量及统一分母需订单/报价/成交时间证据| +|组合与容量|相关性、集中度、风险贡献、现金与敞口、流动性、可承载资金规模|现有风险/组合模块与报告分工;不是 B3 已完成的统一容量或实时组合投影| +|运行与数据|来源/PIT、新鲜度、持仓资金对账、重复/未知订单、报告送达与恢复|依赖实际 runtime/来源/回执;源码 CI 成功不能替代这些运营证据| + +这些是按研究/交易/组合/运营目的选择的目录,不要求每种策略机械使用全部指标。被候选预注册要求的项缺失时必须披露;报告、排序和否决角色及阈值仍由既有冻结合同决定。 + +## 3. 必须绑定的统一口径 + +1. 标明观察单位:交易、交易日、自然日或小时;写清正负/零的分母、交易数和持仓覆盖范围。B3 `per_period` 不自动宣称日频或年化。 +2. 先对齐成本、资金流、价格复权、币种、现金/融资腿及信号/成交时点,再比较收益。`net_returns` 的命名不核验实际成本是否正确入账;需绑定 A2 对账与来源证据。 +3. 股市交易日与24×7加密使用明确日历/年化基数。生命周期 Sharpe 默认 ddof=0,研究推断 ddof=1,不能不说明就比较。 +4. 逐笔统计先冻结 FIFO/其他配对方式、分批成交/部分平仓、多腿组合、切换归属、费用与 FX 分配、持有期及未平仓处理;不能把一张订单、一笔 fill 或一个正收益日直接当一次获利交易。 +5. 单列样本量、窗口、数据身份与可计算状态。没有亏损样本不等于没有亏损风险;缺交易记录、缺价格或缺净值不能补 0。 + 旧窗口某些无定义比率为兼容仍保留 NaN,消费者必须显式处理,不能转为已知 0。 +6. DSR 绑定真实全累计试验(含失败/拒绝/中断等冻结口径),PBO/WFA/OOS保持时点和隔离。声明账本数、指标实现或合成回归通过均不证明统计优势或实盘采用。 + +## 4. 本批与后续 + +- 本批只补 B3 可选单期研究诊断和目录;既有窗口字段、原八项结果、晋级/风险/仓位和生产 pin不变。 +- 逐笔统计继续作为缺口:先取得/冻结完整成交记账合同,随后单独实现和验证;不读取真实账户或生成真实交易成绩。 +- 回撤恢复/容量/实际执行质量的标准化按各自证据推进,不用自选阈值替代 B1/B2/B4 冻结。B4 后验更新与 E1 仍是独立阶段。 diff --git a/docs/window_metrics_semantics.zh-CN.md b/docs/window_metrics_semantics.zh-CN.md index 69688cbf..98ef113f 100644 --- a/docs/window_metrics_semantics.zh-CN.md +++ b/docs/window_metrics_semantics.zh-CN.md @@ -20,6 +20,8 @@ v2 **只新增字段**。在相同输入、默认参数下,v1 已有字段(` ## 2. 胜率与盈亏比(日级,不是逐笔) +这里的 `profit_factor` 是盈利因子(盈利总和/亏损总和),不是平均盈亏比(平均盈利/平均亏损)。窗口对象仍未单列平均盈亏比;研究侧 B3 可选单期诊断和完整能力目录见[统一量化指标](unified_metric_catalog.zh-CN.md)。 + | 字段 | 定义 | 零收益日 | | --- | --- | --- | | `win_rate`(v1,不变) | 正收益日数 / 全部交易日数 | 计入分母(算作"非胜") | diff --git a/src/quant_platform_kit/research_stats/unified_report.py b/src/quant_platform_kit/research_stats/unified_report.py index 0480b1e5..350e8a3b 100644 --- a/src/quant_platform_kit/research_stats/unified_report.py +++ b/src/quant_platform_kit/research_stats/unified_report.py @@ -11,6 +11,7 @@ import math import re from dataclasses import dataclass +from fractions import Fraction from statistics import NormalDist, stdev from typing import Iterable @@ -151,10 +152,56 @@ def _mintrl(psr: StatResult, benchmark: float, confidence: float, floor: int) -> return _missing(name, "numerical_failure", **details) +def _outcome_diagnostics(net: tuple[float, ...]) -> tuple[StatResult, ...]: + """Descriptive period-return outcomes; never reconstruct round-trip trades.""" + wins = tuple(r for r in net if r > 0) + losses = tuple(-r for r in net if r < 0) + decisive = len(wins) + len(losses) + details = { + "aggregation_level": "return_observations_not_trades", + "input_basis": "same_period_net_returns", + "positive_observations": len(wins), + "negative_observations": len(losses), + "zero_observations": len(net) - decisive, + "descriptive_only": True, + } + # Exact sums of the supplied binary floats avoid intermediate overflow or + # underflow. Convert only the final statistic; unrepresentable ratios are + # explicitly missing rather than infinite. + gain = sum((Fraction(r) for r in wins), Fraction()) + loss = sum((Fraction(r) for r in losses), Fraction()) + + def value(name: str, ratio: Fraction) -> StatResult: + try: + number = float(ratio) + if number == 0.0 and ratio != 0: + return _missing(name, "numerical_failure", **details) + return _computed(name, number, **details) + except (ArithmeticError, ValueError): + return _missing(name, "numerical_failure", **details) + + win_name = "net_win_rate_ex_zero_per_period" + win_rate = (value(win_name, Fraction(len(wins), decisive)) if decisive else + _missing(win_name, "no_nonzero_observations", **details)) + payoff_name = "net_payoff_ratio_per_period" + if not losses: + payoff = _missing(payoff_name, "no_loss_observations", **details) + elif not wins: + payoff = _missing(payoff_name, "no_win_observations", **details) + else: + payoff = value(payoff_name, (gain / len(wins)) / (loss / len(losses))) + pf_name = "net_profit_factor_per_period" + profit_factor = (value(pf_name, gain / loss) if losses else + _missing(pf_name, "no_loss_observations", **details)) + average = value("mean_net_return_per_period", (gain - loss) / len(net)) + return win_rate, payoff, profit_factor, average + + def build_unified_net_report( net_returns: Iterable[object], *, gross_returns: Iterable[object] | None = None, trials: TrialEvidence | None = None, sr_benchmark: float = 0.0, confidence: float = .95, min_observations: int = DEFAULT_MIN_OBSERVATIONS, + include_outcome_diagnostics: bool = False, ) -> UnifiedNetReport: """Summarize validated same-period net returns; never fill/drop observations. @@ -162,8 +209,14 @@ def build_unified_net_report( with nonnegative cost deductions apart from a recorded 4-ULP roundoff bound. Invalid inputs raise ResearchInputError; missing/undefined inference is UNCOMPUTABLE with no numeric placeholder. + Optional outcome diagnostics describe the same-period net-return sample, + not closed trades or future profit. Zeros are excluded only from win rate; + the arithmetic mean includes every observation. Default eight metrics and + all existing metric values remain unchanged. No files, accounts, ledgers, policy, orders or budgets are read or written. """ + if type(include_outcome_diagnostics) is not bool: + raise ResearchInputError("include_outcome_diagnostics must be boolean") net = simple_returns(net_returns, "net_returns") if not net: raise ResearchInputError("net_returns must be nonempty") @@ -225,6 +278,9 @@ def build_unified_net_report( negative_cost_tolerance_scale="ulp(1+gross)", roundoff_negative_cost_pairs_zeroed=len(roundoff_pairs), max_roundoff_negative_return_delta=max((b - a for a, b in roundoff_pairs), default=0.0)) - return UnifiedNetReport(len(net), (growth, sharpe, psr, dsr, mintrl, cvar, drawdown, drag), + metrics = (growth, sharpe, psr, dsr, mintrl, cvar, drawdown, drag) + if include_outcome_diagnostics: + metrics += _outcome_diagnostics(net) + return UnifiedNetReport(len(net), metrics, trials.cumulative_total if trials else None, trials.ledger_sha256 if trials else None) diff --git a/tests/test_unified_outcome_diagnostics.py b/tests/test_unified_outcome_diagnostics.py new file mode 100644 index 00000000..e4305a32 --- /dev/null +++ b/tests/test_unified_outcome_diagnostics.py @@ -0,0 +1,129 @@ +"""Analytic, synthetic-only outcome diagnostics; no trade or policy inference.""" + +import json +import math +import unittest + +from quant_platform_kit.research_stats._validation import ResearchInputError +from quant_platform_kit.research_stats.unified_report import build_unified_net_report + + +NAMES = ( + "net_win_rate_ex_zero_per_period", + "net_payoff_ratio_per_period", + "net_profit_factor_per_period", + "mean_net_return_per_period", +) + + +class OutcomeDiagnosticsTests(unittest.TestCase): + def report(self, values): + return build_unified_net_report(values, include_outcome_diagnostics=True) + + def test_payoff_is_not_profit_factor_and_zero_days_are_explicit(self): + report = self.report((.02, .02, -.01, 0.)) + self.assertAlmostEqual(report.metric(NAMES[0]).value, 2 / 3) + self.assertAlmostEqual(report.metric(NAMES[1]).value, 2.) + self.assertAlmostEqual(report.metric(NAMES[2]).value, 4.) + self.assertAlmostEqual(report.metric(NAMES[3]).value, .0075) + for name in NAMES: + details = report.metric(name).details + self.assertEqual(details["positive_observations"], 2) + self.assertEqual(details["negative_observations"], 1) + self.assertEqual(details["zero_observations"], 1) + self.assertEqual(details["aggregation_level"], "return_observations_not_trades") + + def test_expected_mean_includes_zero_periods(self): + a = self.report((.02, -.01)) + b = self.report((.02, -.01, 0., 0.)) + self.assertEqual(a.metric(NAMES[0]).value, .5) + self.assertEqual(b.metric(NAMES[0]).value, .5) + self.assertEqual(a.metric(NAMES[0]).details["zero_observations"], 0) + self.assertEqual(b.metric(NAMES[0]).details["zero_observations"], 2) + for name in NAMES[:3]: + self.assertEqual(a.metric(name).value, b.metric(name).value) + self.assertAlmostEqual(a.metric(NAMES[3]).value, .005) + self.assertAlmostEqual(b.metric(NAMES[3]).value, .0025) + + def test_high_win_rate_can_have_negative_net_expectation(self): + report = self.report((.01,) * 9 + (-.2,)) + self.assertAlmostEqual(report.metric(NAMES[0]).value, .9) + self.assertAlmostEqual(report.metric(NAMES[1]).value, .05) + self.assertAlmostEqual(report.metric(NAMES[2]).value, .45) + self.assertAlmostEqual(report.metric(NAMES[3]).value, -.011) + + def test_all_positive_periods_do_not_invent_a_loss_distribution(self): + report = self.report((.01, .02, 0.)) + self.assertEqual(report.metric(NAMES[0]).value, 1.) + for name in NAMES[1:3]: + metric = report.metric(name) + self.assertEqual(metric.status, "UNCOMPUTABLE") + self.assertIsNone(metric.value) + self.assertEqual(metric.reason_code, "no_loss_observations") + + def test_all_negative_periods_have_zero_profit_factor_but_no_average_win(self): + report = self.report((-.01, -.02, 0.)) + self.assertEqual(report.metric(NAMES[0]).value, 0.) + self.assertEqual(report.metric(NAMES[2]).value, 0.) + self.assertEqual(report.metric(NAMES[1]).reason_code, "no_win_observations") + self.assertIsNone(report.metric(NAMES[1]).value) + self.assertAlmostEqual(report.metric(NAMES[3]).value, -.01) + + def test_all_zero_periods_have_known_zero_mean_and_undefined_ratios(self): + report = self.report((0., 0., 0.)) + self.assertEqual(report.metric(NAMES[3]).value, 0.) + for name in NAMES[:3]: + self.assertEqual(report.metric(name).status, "UNCOMPUTABLE") + self.assertIsNone(report.metric(name).value) + self.assertEqual(report.metric(NAMES[0]).reason_code, "no_nonzero_observations") + + def test_enabling_diagnostics_preserves_all_original_metric_results(self): + values = (.01, -.012, .005) * 20 + baseline = build_unified_net_report(values) + enabled = self.report(values) + self.assertEqual(len(baseline.metrics), 8) + self.assertEqual(enabled.metrics[:8], baseline.metrics) + self.assertEqual(len(enabled.metrics), 12) + self.assertFalse(enabled.live_ready) + self.assertTrue(enabled.no_order) + self.assertEqual(enabled.status, "DEVELOPMENT_ONLY") + self.assertEqual(baseline, build_unified_net_report(values, include_outcome_diagnostics=False)) + + def test_flag_must_be_boolean(self): + for flag in (1, 0, "true", None): + with self.subTest(flag=flag), self.assertRaises(ResearchInputError): + build_unified_net_report((.01, -.01), include_outcome_diagnostics=flag) + + def test_invalid_returns_keep_existing_rejection(self): + for values in ((), (True,), (float("nan"),), (float("inf"),), (-1.,)): + with self.subTest(values=values), self.assertRaises(ResearchInputError): + self.report(values) + + def test_unrepresentable_ratio_is_missing_and_serialization_is_finite(self): + report = self.report((1e300, -1e-300, 0.)) + for name in NAMES[1:3]: + self.assertEqual(report.metric(name).reason_code, "numerical_failure") + self.assertIsNone(report.metric(name).value) + self.assertTrue(all(x.value is None or math.isfinite(x.value) for x in report.metrics)) + json.dumps(report.to_dict(), allow_nan=False) + + def test_generator_input_is_consumed_once(self): + report = self.report(x for x in (.02, .02, -.01, 0.)) + self.assertEqual(report.observations, 4) + self.assertAlmostEqual(report.metric(NAMES[2]).value, 4.) + + def test_nonzero_mean_underflow_is_not_a_fabricated_zero(self): + report = self.report((math.nextafter(0., 1.), 0.)) + result = report.metric(NAMES[3]) + self.assertEqual(result.status, "UNCOMPUTABLE") + self.assertIsNone(result.value) + self.assertEqual(result.reason_code, "numerical_failure") + + def test_exact_cancellation_has_a_known_zero_mean(self): + result = self.report((.01, -.01)).metric(NAMES[3]) + self.assertEqual(result.status, "COMPUTED") + self.assertEqual(result.value, 0.) + + +if __name__ == "__main__": + unittest.main()