portfolio-twr 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,32 @@
1
+ name: CI
2
+
3
+ on:
4
+ pull_request:
5
+ push:
6
+ branches: [main]
7
+ workflow_dispatch:
8
+ workflow_call:
9
+
10
+ permissions:
11
+ contents: read
12
+
13
+ concurrency:
14
+ group: ci-${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
15
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
16
+
17
+ jobs:
18
+ test:
19
+ strategy:
20
+ fail-fast: false
21
+ matrix:
22
+ python: ['3.11', '3.12', '3.13']
23
+ runs-on: ubuntu-latest
24
+ timeout-minutes: 10
25
+ steps:
26
+ - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5
27
+ with:
28
+ persist-credentials: false
29
+ - uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
30
+ with:
31
+ python-version: ${{ matrix.python }}
32
+ - run: make check
@@ -0,0 +1,41 @@
1
+ name: PyPI
2
+
3
+ on:
4
+ push:
5
+ tags: ['v*.*.*']
6
+ workflow_dispatch: {}
7
+
8
+ permissions: {}
9
+
10
+ concurrency:
11
+ group: pypi-${{ github.ref }}
12
+ cancel-in-progress: false
13
+
14
+ jobs:
15
+ ci:
16
+ if: github.ref_type == 'tag' && (github.event_name == 'workflow_dispatch' || vars.PYPI_PUBLISH == 'true')
17
+ uses: ./.github/workflows/ci.yml
18
+ permissions:
19
+ contents: read
20
+
21
+ publish:
22
+ needs: ci
23
+ if: github.ref_type == 'tag' && (github.event_name == 'workflow_dispatch' || vars.PYPI_PUBLISH == 'true')
24
+ runs-on: ubuntu-latest
25
+ timeout-minutes: 10
26
+ environment: pypi
27
+ permissions:
28
+ contents: read
29
+ id-token: write
30
+ steps:
31
+ - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5
32
+ with:
33
+ persist-credentials: false
34
+ - uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
35
+ - name: Build
36
+ run: |
37
+ version="$(python3 -c 'import tomllib; print(tomllib.load(open("pyproject.toml", "rb"))["project"]["version"])')"
38
+ [ "${GITHUB_REF_NAME#v}" = "$version" ] || { echo "tag $GITHUB_REF_NAME is not version $version" >&2; exit 1; }
39
+ uv build
40
+ - name: Upload
41
+ run: uv publish --trusted-publishing always --check-url https://pypi.org/simple/
@@ -0,0 +1,66 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ tags: ['v*.*.*']
6
+ workflow_dispatch: {}
7
+
8
+ permissions: {}
9
+
10
+ concurrency:
11
+ group: release-${{ github.ref }}
12
+ cancel-in-progress: false
13
+
14
+ jobs:
15
+ released:
16
+ runs-on: ubuntu-latest
17
+ timeout-minutes: 5
18
+ permissions:
19
+ contents: read
20
+ outputs:
21
+ done: ${{ steps.check.outputs.done }}
22
+ steps:
23
+ - id: check
24
+ env:
25
+ GH_TOKEN: ${{ github.token }}
26
+ TAG: ${{ github.ref_name }}
27
+ run: |
28
+ done=false
29
+ if [ "$GITHUB_REF_TYPE" = tag ] && gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
30
+ done=true
31
+ echo "$TAG is already released: nothing to do"
32
+ fi
33
+ echo "done=$done" >> "$GITHUB_OUTPUT"
34
+
35
+ ci:
36
+ needs: released
37
+ if: needs.released.outputs.done != 'true'
38
+ uses: ./.github/workflows/ci.yml
39
+ permissions:
40
+ contents: read
41
+
42
+ github-release:
43
+ needs: ci
44
+ if: github.event_name == 'push' && github.ref_type == 'tag'
45
+ runs-on: ubuntu-latest
46
+ timeout-minutes: 10
47
+ permissions:
48
+ contents: write
49
+ steps:
50
+ - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5
51
+ with:
52
+ persist-credentials: false
53
+ - uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
54
+ - name: Build
55
+ run: |
56
+ version="$(python3 -c 'import tomllib; print(tomllib.load(open("pyproject.toml", "rb"))["project"]["version"])')"
57
+ [ "${GITHUB_REF_NAME#v}" = "$version" ] || { echo "tag $GITHUB_REF_NAME is not version $version" >&2; exit 1; }
58
+ uv build
59
+ - env:
60
+ GH_TOKEN: ${{ github.token }}
61
+ TAG: ${{ github.ref_name }}
62
+ run: |
63
+ object=$(gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$TAG" --jq 'select(.object.type == "tag") | .object.sha')
64
+ test -n "$object" || { echo "::error::$TAG is not an annotated tag carrying release notes"; exit 1; }
65
+ gh api "repos/$GITHUB_REPOSITORY/git/tags/$object" --jq .message > "$RUNNER_TEMP/notes.md"
66
+ gh release create "$TAG" dist/* --repo "$GITHUB_REPOSITORY" --verify-tag --title "$TAG" --notes-file "$RUNNER_TEMP/notes.md"
@@ -0,0 +1,8 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ dist/
7
+ build/
8
+ *.egg-info/
@@ -0,0 +1,12 @@
1
+ # Changelog
2
+
3
+ ## [0.1.0] - 2026-11-29
4
+
5
+ ### Added
6
+ - `twr`: `weekday_sessions`, `prior_weekday`, `linked_twr` (geometric daily TWR linking, reconciliation guards, and additive wealth-scaled percentage-point contribution attribution), and `monthly_returns`.
7
+ - `risk`: `risk_statistics` (annualised arithmetic/log volatility, semi-deviation, drawdown depth/duration/recovery, Sharpe/Sortino/Calmar with optional holiday compounding) and `benchmark_statistics` (Active Return, Beta, Correlation, Tracking Error, Information Ratio).
8
+ - `dietz`: base-currency-agnostic reconciled `modified_dietz` with flow-identity, interval, and NAV/P&L reconciliation guards.
9
+
10
+ ### Upgrade
11
+ - Action required: None.
12
+ - Rollback: Uninstall `portfolio-twr` or pin a prior local module.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 benjamin-di
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,8 @@
1
+ .PHONY: bootstrap check lock
2
+ bootstrap:
3
+ uv sync --locked
4
+ check:
5
+ ./scripts/test.sh
6
+ @if [ -f publish/config.toml ] && command -v publish-public >/dev/null 2>&1; then publish-public --check-head .; fi
7
+ lock:
8
+ uv lock
@@ -0,0 +1,75 @@
1
+ Metadata-Version: 2.5
2
+ Name: portfolio-twr
3
+ Version: 0.1.0
4
+ Summary: Zero-dependency Time-Weighted Return (TWR) linking, geometric contribution attribution, Portfolio-Performance-aligned risk/drawdown/benchmark statistics, and reconciled Modified Dietz
5
+ Project-URL: Homepage, https://github.com/benjamin-di/portfolio-twr
6
+ Project-URL: Issues, https://github.com/benjamin-di/portfolio-twr/issues
7
+ Author: benjamin-di
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: attribution,drawdown,finance,modified-dietz,portfolio,sharpe,sortino,time-weighted-return,tracking-error,twr
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Financial and Insurance Industry
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Office/Business :: Financial :: Investment
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+
24
+ # portfolio-twr
25
+
26
+ Zero-dependency Python library for daily Time-Weighted Return (TWR) linking, geometric contribution attribution, Portfolio-Performance-aligned risk/drawdown/benchmark analytics, and reconciled Modified Dietz returns:
27
+
28
+ - **Linked TWR & attribution (`portfolio_twr.twr`)**:
29
+ - `linked_twr`: geometrically links daily P&L over beginning-of-day invested capital, enforces weekday session completeness and P&L reconciliation, and computes exact additive wealth-scaled percentage-point contributions (`sum(instrument_pp) + fees_pp == 100 * twr`).
30
+ - `monthly_returns`: calendar-month linked TWR slices plus compounded YTD TWR.
31
+ - **Risk & benchmark statistics (`portfolio_twr.risk`)**:
32
+ - `risk_statistics`: annualised arithmetic and log volatility, downside semi-deviation, max drawdown, peak/trough/recovery dates, max drawdown duration and longest recovery days, annualised TWR (`>= 30` calendar days), and Sharpe/Sortino/Calmar ratios (`>= 60` sessions), with optional holiday compounding via `is_holiday`.
33
+ - `benchmark_statistics`: aligns daily portfolio returns with a benchmark series (compounding across benchmark holidays) to compute Active Return, Correlation, Beta, Annualised Tracking Error, and Information Ratio.
34
+ - **Reconciled Modified Dietz (`portfolio_twr.dietz`)**:
35
+ - `modified_dietz`: base-currency-agnostic Daily Modified Dietz over end-of-day external equity flows with strict flow-identity, interval, and NAV/P&L reconciliation checks.
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ pip install portfolio-twr
41
+ ```
42
+
43
+ ## Quick Start
44
+
45
+ ```python
46
+ from datetime import date
47
+ from portfolio_twr import linked_twr, risk_statistics, monthly_returns, modified_dietz
48
+
49
+ rows = [
50
+ {"date": "2026-01-02", "pnl": 1000.0, "basis": 100_000.0, "isin": {"A": 1000.0},
51
+ "groups": {"Equities": {"pnl": 1000.0, "basis": 100_000.0}}, "estimated": False},
52
+ {"date": "2026-01-05", "pnl": -500.0, "basis": 101_000.0, "isin": {"A": -500.0},
53
+ "groups": {"Equities": {"pnl": -500.0, "basis": 101_000.0}}, "estimated": False},
54
+ ]
55
+
56
+ res = linked_twr(rows, date(2026, 1, 2), date(2026, 1, 5), expected_pnl=500.0)
57
+ print(f"TWR: {res['twr']:.4%}, contribution_pp: {res['isin_contribution_pp']}")
58
+
59
+ stats = risk_statistics(rows)
60
+ print(f"Max drawdown: {stats['max_drawdown']:.4%}")
61
+
62
+ md = modified_dietz(
63
+ opening=100_000.0,
64
+ closing=112_500.0,
65
+ start=date(2026, 1, 1),
66
+ end=date(2026, 1, 31),
67
+ flows=[{"id": "dep-1", "kind": "external_equity", "date": "2026-01-16", "amount": 10_000.0}],
68
+ expected_pnl=2_500.0,
69
+ )
70
+ print(f"Modified Dietz: {md['value']:.4%}")
71
+ ```
72
+
73
+ ## License
74
+
75
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,52 @@
1
+ # portfolio-twr
2
+
3
+ Zero-dependency Python library for daily Time-Weighted Return (TWR) linking, geometric contribution attribution, Portfolio-Performance-aligned risk/drawdown/benchmark analytics, and reconciled Modified Dietz returns:
4
+
5
+ - **Linked TWR & attribution (`portfolio_twr.twr`)**:
6
+ - `linked_twr`: geometrically links daily P&L over beginning-of-day invested capital, enforces weekday session completeness and P&L reconciliation, and computes exact additive wealth-scaled percentage-point contributions (`sum(instrument_pp) + fees_pp == 100 * twr`).
7
+ - `monthly_returns`: calendar-month linked TWR slices plus compounded YTD TWR.
8
+ - **Risk & benchmark statistics (`portfolio_twr.risk`)**:
9
+ - `risk_statistics`: annualised arithmetic and log volatility, downside semi-deviation, max drawdown, peak/trough/recovery dates, max drawdown duration and longest recovery days, annualised TWR (`>= 30` calendar days), and Sharpe/Sortino/Calmar ratios (`>= 60` sessions), with optional holiday compounding via `is_holiday`.
10
+ - `benchmark_statistics`: aligns daily portfolio returns with a benchmark series (compounding across benchmark holidays) to compute Active Return, Correlation, Beta, Annualised Tracking Error, and Information Ratio.
11
+ - **Reconciled Modified Dietz (`portfolio_twr.dietz`)**:
12
+ - `modified_dietz`: base-currency-agnostic Daily Modified Dietz over end-of-day external equity flows with strict flow-identity, interval, and NAV/P&L reconciliation checks.
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ pip install portfolio-twr
18
+ ```
19
+
20
+ ## Quick Start
21
+
22
+ ```python
23
+ from datetime import date
24
+ from portfolio_twr import linked_twr, risk_statistics, monthly_returns, modified_dietz
25
+
26
+ rows = [
27
+ {"date": "2026-01-02", "pnl": 1000.0, "basis": 100_000.0, "isin": {"A": 1000.0},
28
+ "groups": {"Equities": {"pnl": 1000.0, "basis": 100_000.0}}, "estimated": False},
29
+ {"date": "2026-01-05", "pnl": -500.0, "basis": 101_000.0, "isin": {"A": -500.0},
30
+ "groups": {"Equities": {"pnl": -500.0, "basis": 101_000.0}}, "estimated": False},
31
+ ]
32
+
33
+ res = linked_twr(rows, date(2026, 1, 2), date(2026, 1, 5), expected_pnl=500.0)
34
+ print(f"TWR: {res['twr']:.4%}, contribution_pp: {res['isin_contribution_pp']}")
35
+
36
+ stats = risk_statistics(rows)
37
+ print(f"Max drawdown: {stats['max_drawdown']:.4%}")
38
+
39
+ md = modified_dietz(
40
+ opening=100_000.0,
41
+ closing=112_500.0,
42
+ start=date(2026, 1, 1),
43
+ end=date(2026, 1, 31),
44
+ flows=[{"id": "dep-1", "kind": "external_equity", "date": "2026-01-16", "amount": 10_000.0}],
45
+ expected_pnl=2_500.0,
46
+ )
47
+ print(f"Modified Dietz: {md['value']:.4%}")
48
+ ```
49
+
50
+ ## License
51
+
52
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,55 @@
1
+ [project]
2
+ name = "portfolio-twr"
3
+ version = "0.1.0"
4
+ description = "Zero-dependency Time-Weighted Return (TWR) linking, geometric contribution attribution, Portfolio-Performance-aligned risk/drawdown/benchmark statistics, and reconciled Modified Dietz"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "benjamin-di" }]
9
+ requires-python = ">=3.11"
10
+ keywords = ["portfolio", "twr", "time-weighted-return", "modified-dietz", "sharpe", "sortino", "drawdown", "tracking-error", "attribution", "finance"]
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "Intended Audience :: Developers",
14
+ "Intended Audience :: Financial and Insurance Industry",
15
+ "License :: OSI Approved :: MIT License",
16
+ "Operating System :: OS Independent",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Topic :: Office/Business :: Financial :: Investment",
22
+ ]
23
+ dependencies = []
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/benjamin-di/portfolio-twr"
27
+ Issues = "https://github.com/benjamin-di/portfolio-twr/issues"
28
+
29
+ [dependency-groups]
30
+ dev = [
31
+ "pytest>=8",
32
+ "ruff>=0.14",
33
+ ]
34
+
35
+ [build-system]
36
+ requires = ["hatchling"]
37
+ build-backend = "hatchling.build"
38
+
39
+ [tool.hatch.build.targets.wheel]
40
+ packages = ["src/portfolio_twr"]
41
+
42
+ [tool.pytest.ini_options]
43
+ testpaths = ["tests"]
44
+ addopts = "-q"
45
+
46
+ [tool.ruff]
47
+ line-length = 120
48
+ target-version = "py311"
49
+
50
+ [tool.ruff.lint]
51
+ select = ["E", "F", "I", "B", "UP", "S", "RUF"]
52
+ ignore = ["S101", "RUF001", "RUF002", "RUF003"]
53
+
54
+ [tool.ruff.lint.per-file-ignores]
55
+ "tests/*" = ["S", "E501", "B905"]
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ # The gate: lint, format, then the tests.
3
+ set -euo pipefail
4
+ cd "$(dirname "${BASH_SOURCE[0]}")/.."
5
+ uv sync --locked
6
+ .venv/bin/ruff check src tests
7
+ .venv/bin/ruff format --check src tests
8
+ .venv/bin/python -m pytest "$@"
@@ -0,0 +1,20 @@
1
+ """Zero-dependency Time-Weighted Return, attribution, risk/benchmark statistics, and Modified Dietz."""
2
+
3
+ from .dietz import modified_dietz
4
+ from .errors import PerformanceUnavailable
5
+ from .risk import benchmark_statistics, risk_statistics
6
+ from .twr import linked_twr, monthly_returns, prior_weekday, weekday_sessions
7
+
8
+ __version__ = "0.1.0"
9
+
10
+ __all__ = [
11
+ "PerformanceUnavailable",
12
+ "__version__",
13
+ "benchmark_statistics",
14
+ "linked_twr",
15
+ "modified_dietz",
16
+ "monthly_returns",
17
+ "prior_weekday",
18
+ "risk_statistics",
19
+ "weekday_sessions",
20
+ ]
@@ -0,0 +1,81 @@
1
+ """Base-currency-agnostic reconciled Daily Modified Dietz return calculation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections.abc import Iterable, Mapping
7
+ from datetime import date
8
+ from typing import Any
9
+
10
+ from .errors import PerformanceUnavailable
11
+
12
+
13
+ def _finite_float(value: Any, label: str) -> float:
14
+ try:
15
+ out = float(value)
16
+ except (TypeError, ValueError) as exc:
17
+ raise PerformanceUnavailable(f"Non-numeric {label}") from exc
18
+ if not math.isfinite(out):
19
+ raise PerformanceUnavailable(f"Non-finite {label}")
20
+ return out
21
+
22
+
23
+ def modified_dietz(
24
+ opening: float,
25
+ closing: float,
26
+ start: date,
27
+ end: date,
28
+ flows: Iterable[Mapping[str, Any]],
29
+ expected_pnl: float,
30
+ *,
31
+ amount_key: str = "amount",
32
+ currency_label: str = "",
33
+ tolerance: float = 0.05,
34
+ ) -> dict[str, Any]:
35
+ """Signed external equity only; explicit end-of-day timing, never trades/debt/variation margin."""
36
+ opening_val = _finite_float(opening, "opening NAV")
37
+ closing_val = _finite_float(closing, "closing NAV")
38
+ expected_val = _finite_float(expected_pnl, "expected P&L")
39
+ days = (end - start).days
40
+ if days <= 0:
41
+ raise PerformanceUnavailable("Invalid NAV valuation interval")
42
+
43
+ net = 0.0
44
+ weighted = 0.0
45
+ seen: set[Any] = set()
46
+ for flow in flows:
47
+ identity = flow.get("id")
48
+ if not identity or identity in seen:
49
+ raise PerformanceUnavailable("Missing or duplicate equity-flow identity")
50
+ seen.add(identity)
51
+ if flow.get("kind") != "external_equity":
52
+ raise PerformanceUnavailable("Unclassified external equity flow")
53
+ when = date.fromisoformat(str(flow["date"]))
54
+ if not start < when <= end:
55
+ raise PerformanceUnavailable("External flow outside NAV interval")
56
+ if amount_key not in flow:
57
+ raise PerformanceUnavailable(f"Missing flow amount field: {amount_key}")
58
+ amount = _finite_float(flow[amount_key], "external equity flow")
59
+ net += amount
60
+ weighted += amount * (end - when).days / days
61
+
62
+ pnl = closing_val - opening_val - net
63
+ residual = pnl - expected_val
64
+ if abs(residual) > tolerance:
65
+ prefix = f"{currency_label.strip()} " if currency_label.strip() else ""
66
+ raise PerformanceUnavailable(
67
+ f"NAV / flow / P&L reconciliation difference {prefix}{residual:+,.2f}; investigate cash movements"
68
+ )
69
+ capital = opening_val + weighted
70
+ if opening_val <= 0 or capital <= 0:
71
+ raise PerformanceUnavailable("Nonpositive portfolio return capital")
72
+ return {
73
+ "value": pnl / capital,
74
+ "pnl": pnl,
75
+ "capital": capital,
76
+ "external_equity": net,
77
+ "weighted_external_equity": weighted,
78
+ "reconciliation_residual": residual,
79
+ "method": "Daily Modified Dietz; external equity at end of day",
80
+ "estimated": True,
81
+ }
@@ -0,0 +1,5 @@
1
+ """Error types for `portfolio-twr`."""
2
+
3
+
4
+ class PerformanceUnavailable(ValueError):
5
+ """Raised when required return history or reconciliation invariants are missing or violated."""
File without changes
@@ -0,0 +1,237 @@
1
+ """Portfolio-Performance-aligned risk, drawdown, and benchmark-relative statistics."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections.abc import Callable, Mapping, Sequence
7
+ from datetime import date
8
+ from typing import Any
9
+
10
+ from .twr import prior_weekday
11
+
12
+
13
+ def risk_statistics(
14
+ rows: Sequence[Mapping[str, Any]],
15
+ *,
16
+ rf_annual: float = 0.0,
17
+ is_holiday: Callable[[str], bool] | None = None,
18
+ ) -> dict[str, Any]:
19
+ """Annualised volatility, log/semi-deviation, risk-adjusted ratios and drawdown metrics.
20
+
21
+ Sessions with positive invested capital contribute one return each (P&L over
22
+ beginning-of-day capital), optionally compounding holiday sessions (`is_holiday`)
23
+ into the next trading session. Publishes arithmetic and log volatility, downside
24
+ semi-deviation, max drawdown depth/duration/longest recovery, annualised TWR
25
+ (>= 30 calendar days), and Sharpe/Sortino/Calmar ratios (>= 60 sessions).
26
+ """
27
+ holiday_fn = is_holiday or (lambda _day: False)
28
+ funded_rows = [r for r in rows if (r.get("basis") or 0.0) > 0]
29
+ rates: list[tuple[str, float]] = []
30
+ pending_growth = 1.0
31
+ for r in funded_rows:
32
+ r_day = float(r["pnl"]) / float(r["basis"])
33
+ day_str = str(r["date"])
34
+ if holiday_fn(day_str):
35
+ pending_growth *= 1.0 + r_day
36
+ continue
37
+ rates.append((day_str, pending_growth * (1.0 + r_day) - 1.0))
38
+ pending_growth = 1.0
39
+
40
+ if len(rates) < 2:
41
+ return {
42
+ "sessions": len(rates),
43
+ "annualised_volatility": None,
44
+ "annualised_log_volatility": None,
45
+ "annualised_semi_deviation": None,
46
+ "annualised_twr": None,
47
+ "sharpe_ratio": None,
48
+ "sortino_ratio": None,
49
+ "calmar_ratio": None,
50
+ "max_drawdown": None,
51
+ "max_drawdown_duration_days": None,
52
+ "longest_recovery_days": None,
53
+ "reason": "Fewer than two sessions with investment capital",
54
+ }
55
+
56
+ mean = sum(v for _, v in rates) / len(rates)
57
+ variance = sum((v - mean) ** 2 for _, v in rates) / (len(rates) - 1)
58
+ if all(1.0 + v > 0 for _, v in rates):
59
+ log_rates = [math.log(1.0 + v) for _, v in rates]
60
+ mean_log = sum(log_rates) / len(log_rates)
61
+ log_var = sum((x - mean_log) ** 2 for x in log_rates) / (len(log_rates) - 1)
62
+ semi_var = sum((x - mean_log) ** 2 for x in log_rates if x < mean_log) / (len(log_rates) - 1)
63
+ ann_log_vol: float | None = math.sqrt(log_var * 252)
64
+ ann_semi_dev: float | None = math.sqrt(semi_var * 252)
65
+ else:
66
+ ann_log_vol = None
67
+ ann_semi_dev = None
68
+
69
+ anchor = prior_weekday(date.fromisoformat(str(funded_rows[0]["date"]))).isoformat()
70
+ index, peak, peak_date = 1.0, 1.0, anchor
71
+ trough, trough_date = 1.0, anchor
72
+ worst, worst_peak, worst_peak_date, worst_trough_date = 0.0, 1.0, None, None
73
+ max_dd_duration = 0
74
+ longest_recovery = 0
75
+ in_drawdown = False
76
+ path: list[tuple[str, float]] = []
77
+ drawdown_series: list[tuple[str, float]] = [(anchor, 0.0)]
78
+
79
+ for day, rate in rates:
80
+ index *= 1.0 + rate
81
+ d_cur = date.fromisoformat(day)
82
+ d_peak = date.fromisoformat(peak_date)
83
+ d_trough = date.fromisoformat(trough_date)
84
+ if index >= peak:
85
+ if in_drawdown:
86
+ longest_recovery = max(longest_recovery, (d_cur - d_trough).days)
87
+ max_dd_duration = max(max_dd_duration, (d_cur - d_peak).days)
88
+ in_drawdown = False
89
+ peak, peak_date = index, day
90
+ trough, trough_date = index, day
91
+ else:
92
+ in_drawdown = True
93
+ max_dd_duration = max(max_dd_duration, (d_cur - d_peak).days)
94
+ if index < trough:
95
+ trough, trough_date = index, day
96
+ drawdown = index / peak - 1.0
97
+ if drawdown < worst:
98
+ worst, worst_peak, worst_peak_date, worst_trough_date = drawdown, peak, peak_date, day
99
+ path.append((day, index))
100
+ drawdown_series.append((day, index / peak - 1.0))
101
+
102
+ end_date = rates[-1][0]
103
+ if abs(pending_growth - 1.0) > 1e-12:
104
+ end_date = str(funded_rows[-1]["date"])
105
+ index *= pending_growth
106
+ d_cur = date.fromisoformat(end_date)
107
+ d_peak = date.fromisoformat(peak_date)
108
+ d_trough = date.fromisoformat(trough_date)
109
+ if index >= peak:
110
+ if in_drawdown:
111
+ longest_recovery = max(longest_recovery, (d_cur - d_trough).days)
112
+ max_dd_duration = max(max_dd_duration, (d_cur - d_peak).days)
113
+ peak, peak_date = index, end_date
114
+ else:
115
+ max_dd_duration = max(max_dd_duration, (d_cur - d_peak).days)
116
+ drawdown = index / peak - 1.0
117
+ if drawdown < worst:
118
+ worst, worst_peak, worst_peak_date, worst_trough_date = drawdown, peak, peak_date, end_date
119
+ path.append((end_date, index))
120
+ drawdown_series.append((end_date, index / peak - 1.0))
121
+
122
+ recovered_on = None
123
+ if worst_trough_date:
124
+ recovered_on = next((day for day, level in path if day > worst_trough_date and level >= worst_peak), None)
125
+
126
+ cal_days = (date.fromisoformat(end_date) - date.fromisoformat(anchor)).days
127
+ ann_twr = (index ** (365.0 / cal_days) - 1.0) if (cal_days >= 30 and index > 0) else None
128
+ has_ratio_sample = len(rates) >= 60 and ann_twr is not None
129
+ sharpe = ((ann_twr - rf_annual) / ann_log_vol) if (has_ratio_sample and ann_log_vol and ann_log_vol > 0) else None
130
+ sortino = (
131
+ ((ann_twr - rf_annual) / ann_semi_dev) if (has_ratio_sample and ann_semi_dev and ann_semi_dev > 0) else None
132
+ )
133
+ calmar = (ann_twr / abs(worst)) if (has_ratio_sample and worst < 0) else None
134
+
135
+ return {
136
+ "sessions": len(rates),
137
+ "start": rates[0][0],
138
+ "end": end_date,
139
+ "annualised_volatility": math.sqrt(variance * 252),
140
+ "annualised_log_volatility": ann_log_vol,
141
+ "annualised_semi_deviation": ann_semi_dev,
142
+ "annualised_twr": ann_twr,
143
+ "sharpe_ratio": sharpe,
144
+ "sortino_ratio": sortino,
145
+ "calmar_ratio": calmar,
146
+ "max_drawdown": worst,
147
+ "drawdown_peak": worst_peak_date,
148
+ "drawdown_trough": worst_trough_date,
149
+ "recovered_on": recovered_on,
150
+ "max_drawdown_duration_days": max_dd_duration,
151
+ "longest_recovery_days": longest_recovery,
152
+ "current_drawdown": index / peak - 1.0,
153
+ "drawdown_series": drawdown_series,
154
+ "estimated": any(bool(r.get("estimated")) for r in rows),
155
+ "basis": (
156
+ "Daily linked investment TWR on invested capital before financing; "
157
+ "sample standard deviation × √252 (plus PP-aligned log volatility, "
158
+ "semi-deviation, drawdown durations and >=60-session risk ratios)"
159
+ ),
160
+ }
161
+
162
+
163
+ def benchmark_statistics(
164
+ rows: Sequence[Mapping[str, Any]],
165
+ benchmark_returns: Mapping[str, float],
166
+ ) -> dict[str, Any]:
167
+ """Align daily investment TWR with a daily benchmark series: Active Return, Beta, Corr, TE, IR.
168
+
169
+ Compounds portfolio returns across unmatched benchmark-holiday sessions into the next
170
+ common benchmark session so multi-day benchmark moves pair with multi-day portfolio moves.
171
+ """
172
+ paired: list[tuple[str, float, float]] = []
173
+ pending_p = 1.0
174
+ for r in rows:
175
+ if (r.get("basis") or 0.0) <= 0:
176
+ continue
177
+ p_day = float(r["pnl"]) / float(r["basis"])
178
+ day_str = str(r["date"])
179
+ b = benchmark_returns.get(day_str)
180
+ if b is None or not math.isfinite(b):
181
+ pending_p *= 1.0 + p_day
182
+ continue
183
+ p_comp = pending_p * (1.0 + p_day) - 1.0
184
+ pending_p = 1.0
185
+ paired.append((day_str, p_comp, float(b)))
186
+
187
+ if not paired:
188
+ return {
189
+ "sessions": 0,
190
+ "portfolio_twr": None,
191
+ "benchmark_twr": None,
192
+ "active_return": None,
193
+ "correlation": None,
194
+ "beta": None,
195
+ "tracking_error": None,
196
+ "information_ratio": None,
197
+ }
198
+
199
+ p_growth = math.prod(1.0 + p for _, p, _ in paired)
200
+ b_growth = math.prod(1.0 + b for _, _, b in paired)
201
+ active = (p_growth - 1.0) - (b_growth - 1.0)
202
+ if len(paired) < 60:
203
+ return {
204
+ "sessions": len(paired),
205
+ "portfolio_twr": p_growth - 1.0,
206
+ "benchmark_twr": b_growth - 1.0,
207
+ "active_return": active,
208
+ "correlation": None,
209
+ "beta": None,
210
+ "tracking_error": None,
211
+ "information_ratio": None,
212
+ }
213
+
214
+ n = len(paired)
215
+ ps = [p for _, p, _ in paired]
216
+ bs = [b for _, _, b in paired]
217
+ mp, mb = sum(ps) / n, sum(bs) / n
218
+ cov = sum((p - mp) * (b - mb) for p, b in zip(ps, bs, strict=True)) / (n - 1)
219
+ var_p = sum((p - mp) ** 2 for p in ps) / (n - 1)
220
+ var_b = sum((b - mb) ** 2 for b in bs) / (n - 1)
221
+ diffs = [p - b for p, b in zip(ps, bs, strict=True)]
222
+ md = sum(diffs) / n
223
+ te_daily = math.sqrt(sum((d - md) ** 2 for d in diffs) / (n - 1))
224
+ te_ann = te_daily * math.sqrt(252)
225
+ corr = (cov / math.sqrt(var_p * var_b)) if (var_p > 0 and var_b > 0) else None
226
+ beta = (cov / var_b) if var_b > 0 else None
227
+ ir = ((md * 252) / te_ann) if te_ann > 0 else None
228
+ return {
229
+ "sessions": n,
230
+ "portfolio_twr": p_growth - 1.0,
231
+ "benchmark_twr": b_growth - 1.0,
232
+ "active_return": active,
233
+ "correlation": corr,
234
+ "beta": beta,
235
+ "tracking_error": te_ann,
236
+ "information_ratio": ir,
237
+ }
@@ -0,0 +1,182 @@
1
+ """Daily geometric Time-Weighted Return (TWR) linking, attribution, and monthly return slices."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections import defaultdict
7
+ from collections.abc import Iterable, Iterator, Mapping, Sequence
8
+ from datetime import date, timedelta
9
+ from typing import Any
10
+
11
+ from .errors import PerformanceUnavailable
12
+
13
+
14
+ def weekday_sessions(start: date, end: date) -> Iterator[date]:
15
+ """Yield every Monday–Friday date in `[start, end]` inclusive."""
16
+ day = start
17
+ while day <= end:
18
+ if day.weekday() < 5:
19
+ yield day
20
+ day += timedelta(days=1)
21
+
22
+
23
+ def prior_weekday(when: date) -> date:
24
+ """Return the latest Monday–Friday date strictly before `when`."""
25
+ day = when - timedelta(days=1)
26
+ while day.weekday() >= 5:
27
+ day -= timedelta(days=1)
28
+ return day
29
+
30
+
31
+ def _chain_returns(values: Iterable[tuple[float, float]]) -> float | None:
32
+ growth, active = 1.0, False
33
+ for profit, capital in values:
34
+ if not math.isfinite(profit) or not math.isfinite(capital):
35
+ raise PerformanceUnavailable("Non-finite daily investment performance")
36
+ if capital <= 0:
37
+ if abs(profit) > 0.005 or capital < -0.005:
38
+ raise PerformanceUnavailable("Daily return has no positive investment capital")
39
+ continue
40
+ rate = profit / capital
41
+ if not math.isfinite(rate) or rate < -1.0:
42
+ raise PerformanceUnavailable("Daily investment loss exceeds its capital")
43
+ growth *= 1.0 + rate
44
+ active = True
45
+ return growth - 1.0 if active else None
46
+
47
+
48
+ def linked_twr(
49
+ rows: Sequence[Mapping[str, Any]],
50
+ start: date,
51
+ end: date,
52
+ expected_pnl: float | None = None,
53
+ expected_isins: Mapping[str, Mapping[str, Any]] | None = None,
54
+ *,
55
+ missing_history_message: str = "Daily performance/capital history is incomplete for this window",
56
+ ) -> dict[str, Any]:
57
+ """Require every weekday session in `[start, end]` and reconcile P&L before publishing linked TWR.
58
+
59
+ Computes exact additive daily wealth-scaled percentage-point contributions:
60
+ `sum(isin_contribution_pp.values()) + fees_contribution_pp == 100 * twr` and
61
+ `sum(g['contribution_pp'] for g in exposures.values()) + fees_contribution_pp == 100 * twr`.
62
+ """
63
+ selected = [r for r in rows if str(start) <= str(r["date"]) <= str(end)]
64
+ if [str(r["date"]) for r in selected] != [str(d) for d in weekday_sessions(start, end)]:
65
+ raise PerformanceUnavailable(missing_history_message)
66
+ pnl = sum(float(r["pnl"]) for r in selected)
67
+ tolerance = max(0.05, 0.01 * len(selected))
68
+ if not math.isfinite(pnl):
69
+ raise PerformanceUnavailable("Non-finite daily investment performance")
70
+ if expected_pnl is not None:
71
+ exp_pnl = float(expected_pnl)
72
+ if not math.isfinite(exp_pnl) or abs(pnl - exp_pnl) > tolerance:
73
+ raise PerformanceUnavailable("Daily investment P&L does not reconcile to the period result")
74
+
75
+ isins: dict[str, float] = defaultdict(float)
76
+ for row in selected:
77
+ for isin, value in (row.get("isin") or {}).items():
78
+ val = float(value)
79
+ if not math.isfinite(val):
80
+ raise PerformanceUnavailable("Non-finite daily investment performance")
81
+ isins[str(isin)] += val
82
+ if expected_isins is not None:
83
+ for isin in isins.keys() | expected_isins.keys():
84
+ exp_isin = float((expected_isins.get(isin) or {}).get("pnl", 0.0))
85
+ if not math.isfinite(exp_isin) or abs(isins[isin] - exp_isin) > tolerance:
86
+ raise PerformanceUnavailable("Daily security P&L does not reconcile to the period result: " + str(isin))
87
+
88
+ twr = _chain_returns((float(r["pnl"]), float(r["basis"])) for r in selected)
89
+
90
+ isin_pp: dict[str, float] = defaultdict(float)
91
+ group_pp: dict[str, float] = defaultdict(float)
92
+ fees_pp = 0.0
93
+ if twr is not None:
94
+ growth = 1.0
95
+ for r in selected:
96
+ capital = float(r["basis"])
97
+ if capital <= 0:
98
+ continue
99
+ factor = 100.0 * growth / capital
100
+ row_isins = r.get("isin") or {}
101
+ for isin, val in row_isins.items():
102
+ isin_pp[str(isin)] += float(val) * factor
103
+ for label, grp in (r.get("groups") or {}).items():
104
+ group_pp[str(label)] += float(grp["pnl"]) * factor
105
+ fees_pp += (float(r["pnl"]) - sum(float(v) for v in row_isins.values())) * factor
106
+ growth *= 1.0 + float(r["pnl"]) / capital
107
+
108
+ groups: dict[str, dict[str, Any]] = {}
109
+ all_labels = sorted(set().union(*((r.get("groups") or {}).keys() for r in selected))) if selected else []
110
+ for label in all_labels:
111
+ values = [(r.get("groups") or {}).get(label, {"pnl": 0.0, "basis": 0.0}) for r in selected]
112
+ try:
113
+ rate = _chain_returns((float(v["pnl"]), float(v["basis"])) for v in values)
114
+ reason = None
115
+ except PerformanceUnavailable as error:
116
+ rate, reason = None, str(error)
117
+ groups[str(label)] = {
118
+ "pnl": sum(float(v["pnl"]) for v in values),
119
+ "twr": rate,
120
+ "contribution_pp": group_pp.get(str(label), 0.0) if twr is not None else None,
121
+ "reason": reason,
122
+ }
123
+ return {
124
+ "pnl": pnl,
125
+ "twr": twr,
126
+ "exposures": groups,
127
+ "isin": dict(isins),
128
+ "isin_contribution_pp": dict(isin_pp) if twr is not None else {},
129
+ "fees_contribution_pp": fees_pp if twr is not None else None,
130
+ "estimated": any(bool(r.get("estimated")) for r in selected),
131
+ "sessions": len(selected),
132
+ "start": str(start),
133
+ "end": str(end),
134
+ }
135
+
136
+
137
+ def monthly_returns(rows: Sequence[Mapping[str, Any]]) -> dict[str, Any]:
138
+ """Calendar-month linked investment TWR slices plus compounded YTD TWR."""
139
+ by_month: dict[str, list[Mapping[str, Any]]] = defaultdict(list)
140
+ for r in rows:
141
+ by_month[str(r["date"])[:7]].append(r)
142
+ out = []
143
+ ytd_growth = 1.0
144
+ ytd_valid = True
145
+ for month in sorted(by_month):
146
+ days = by_month[month]
147
+ total_pnl = sum(float(d.get("pnl") or 0.0) for d in days)
148
+ growth = 1.0
149
+ valid = True
150
+ funded = 0
151
+ for d in days:
152
+ basis = float(d.get("basis") or 0.0)
153
+ pnl = float(d.get("pnl") or 0.0)
154
+ if not math.isfinite(basis) or not math.isfinite(pnl):
155
+ valid = False
156
+ break
157
+ if basis < -0.005 or (basis <= 0.0 and abs(pnl) > 0.005):
158
+ valid = False
159
+ break
160
+ if basis > 0.0:
161
+ ret = pnl / basis
162
+ if not math.isfinite(ret) or ret <= -1.0:
163
+ valid = False
164
+ break
165
+ growth *= 1.0 + ret
166
+ funded += 1
167
+ twr_val = (growth - 1.0) if (valid and funded > 0) else None
168
+ if twr_val is None:
169
+ ytd_valid = False
170
+ else:
171
+ ytd_growth *= growth
172
+ out.append(
173
+ {
174
+ "month": month,
175
+ "twr": twr_val,
176
+ "pnl": total_pnl,
177
+ "sessions": funded,
178
+ "start": str(days[0]["date"]),
179
+ "end": str(days[-1]["date"]),
180
+ }
181
+ )
182
+ return {"months": out, "ytd_twr": (ytd_growth - 1.0) if (out and ytd_valid) else None}
@@ -0,0 +1,56 @@
1
+ """Synthetic tests for reconciled Daily Modified Dietz."""
2
+
3
+ from datetime import date
4
+
5
+ import pytest
6
+
7
+ from portfolio_twr import PerformanceUnavailable, modified_dietz
8
+
9
+
10
+ def test_modified_dietz_with_external_equity_flow():
11
+ res = modified_dietz(
12
+ opening=1000.0,
13
+ closing=1264.0,
14
+ start=date(2026, 1, 1),
15
+ end=date(2026, 1, 11),
16
+ flows=[{"id": "f1", "kind": "external_equity", "date": "2026-01-06", "amount": 150.0}],
17
+ expected_pnl=114.0,
18
+ )
19
+ # weighted flow = 150 * (5 / 10) = 75 -> capital = 1075, pnl = 114
20
+ assert res["capital"] == pytest.approx(1075.0)
21
+ assert res["pnl"] == pytest.approx(114.0)
22
+ assert res["value"] == pytest.approx(114.0 / 1075.0)
23
+ assert res["reconciliation_residual"] == pytest.approx(0.0)
24
+
25
+
26
+ def test_modified_dietz_custom_amount_key_and_guards():
27
+ res = modified_dietz(
28
+ opening=1000.0,
29
+ closing=1020.0,
30
+ start=date(2026, 1, 1),
31
+ end=date(2026, 1, 2),
32
+ flows=[],
33
+ expected_pnl=20.0,
34
+ amount_key="eur",
35
+ currency_label="EUR",
36
+ )
37
+ assert res["value"] == pytest.approx(0.02)
38
+
39
+ with pytest.raises(PerformanceUnavailable, match="interval"):
40
+ modified_dietz(1000.0, 1020.0, date(2026, 1, 2), date(2026, 1, 2), [], 20.0)
41
+ with pytest.raises(PerformanceUnavailable, match="reconciliation difference"):
42
+ modified_dietz(1000.0, 1020.0, date(2026, 1, 1), date(2026, 1, 2), [], 15.0)
43
+ with pytest.raises(PerformanceUnavailable, match="duplicate"):
44
+ modified_dietz(
45
+ 1000.0,
46
+ 1200.0,
47
+ date(2026, 1, 1),
48
+ date(2026, 1, 5),
49
+ [
50
+ {"id": "dup", "kind": "external_equity", "date": "2026-01-02", "amount": 100.0},
51
+ {"id": "dup", "kind": "external_equity", "date": "2026-01-03", "amount": 100.0},
52
+ ],
53
+ 0.0,
54
+ )
55
+ with pytest.raises(PerformanceUnavailable, match="Non-finite"):
56
+ modified_dietz(float("nan"), 1020.0, date(2026, 1, 1), date(2026, 1, 2), [], 20.0)
@@ -0,0 +1,87 @@
1
+ """Synthetic tests for risk_statistics and benchmark_statistics."""
2
+
3
+ from datetime import date, timedelta
4
+
5
+ import pytest
6
+
7
+ from portfolio_twr import benchmark_statistics, risk_statistics, weekday_sessions
8
+
9
+
10
+ def _make_series(returns: list[float], start: date = date(2026, 1, 2)) -> list[dict]:
11
+ days = []
12
+ cur = start
13
+ while len(days) < len(returns):
14
+ if cur.weekday() < 5:
15
+ days.append(cur)
16
+ cur += timedelta(days=1)
17
+ rows = []
18
+ basis = 100.0
19
+ for d, r in zip(days, returns, strict=True):
20
+ pnl = basis * r
21
+ rows.append({"date": d.isoformat(), "pnl": pnl, "basis": basis, "estimated": False})
22
+ basis += pnl
23
+ return rows
24
+
25
+
26
+ def test_risk_statistics_drawdown_recovery_and_holiday_compounding():
27
+ rows = [
28
+ {"date": "2026-01-01", "pnl": 1.0, "basis": 100.0}, # holiday -> compounds into Jan 2
29
+ {"date": "2026-01-02", "pnl": 0.0, "basis": 101.0},
30
+ {"date": "2026-01-05", "pnl": -10.1, "basis": 101.0}, # -10% drawdown
31
+ {"date": "2026-01-06", "pnl": 10.1, "basis": 90.9}, # recovers peak
32
+ ]
33
+ stats = risk_statistics(rows, is_holiday=lambda d: d == "2026-01-01")
34
+ assert stats["sessions"] == 3
35
+ assert stats["max_drawdown"] == pytest.approx(-0.10, abs=1e-12)
36
+ assert stats["drawdown_trough"] == "2026-01-05"
37
+ assert stats["recovered_on"] == "2026-01-06"
38
+ assert stats["longest_recovery_days"] == 1
39
+ assert stats["annualised_volatility"] > 0.0
40
+ assert stats["sharpe_ratio"] is None # < 60 sessions
41
+
42
+
43
+ def test_risk_statistics_60_sessions_ratios_and_total_loss_guard():
44
+ # Alternating positive returns over 70 weekday sessions -> positive Sharpe/Sortino.
45
+ rets = [0.008 if i % 3 != 0 else -0.003 for i in range(70)]
46
+ rows = _make_series(rets)
47
+ stats = risk_statistics(rows, rf_annual=0.02)
48
+ assert stats["sessions"] == 70
49
+ assert stats["annualised_twr"] is not None
50
+ assert stats["sharpe_ratio"] is not None
51
+ assert stats["sortino_ratio"] is not None
52
+ assert stats["calmar_ratio"] is not None
53
+
54
+ # Total-loss session (-100%) makes log volatility None rather than crashing.
55
+ loss_rows = [
56
+ {"date": "2026-01-02", "pnl": 1.0, "basis": 100.0},
57
+ {"date": "2026-01-05", "pnl": -101.0, "basis": 101.0},
58
+ ]
59
+ loss_stats = risk_statistics(loss_rows)
60
+ assert loss_stats["annualised_log_volatility"] is None
61
+ assert loss_stats["annualised_semi_deviation"] is None
62
+
63
+ assert risk_statistics(loss_rows[:1])["annualised_volatility"] is None
64
+
65
+
66
+ def test_benchmark_statistics_holiday_alignment_and_ratios():
67
+ days = list(weekday_sessions(date(2026, 1, 2), date(2026, 4, 20)))
68
+ assert len(days) >= 70
69
+ rows = []
70
+ bench = {}
71
+ for i, d in enumerate(days[:70]):
72
+ b_ret = 0.004 if i % 2 == 0 else -0.002
73
+ p_ret = 1.5 * b_ret + 0.0005
74
+ rows.append({"date": d.isoformat(), "pnl": 100.0 * p_ret, "basis": 100.0})
75
+ if i != 10: # skip one benchmark holiday to test compounding
76
+ bench[d.isoformat()] = b_ret
77
+ bs = benchmark_statistics(rows, bench)
78
+ assert bs["sessions"] == 69
79
+ assert bs["active_return"] > 0.0
80
+ assert bs["correlation"] > 0.9
81
+ assert 1.2 < bs["beta"] < 1.8
82
+ assert bs["tracking_error"] > 0.0
83
+ assert bs["information_ratio"] > 0.0
84
+
85
+ empty = benchmark_statistics(rows[:5], {})
86
+ assert empty["sessions"] == 0
87
+ assert empty["beta"] is None
@@ -0,0 +1,88 @@
1
+ """Synthetic tests for linked TWR, geometric contribution attribution, and monthly returns."""
2
+
3
+ from datetime import date, timedelta
4
+
5
+ import pytest
6
+
7
+ from portfolio_twr import PerformanceUnavailable, linked_twr, monthly_returns, prior_weekday, weekday_sessions
8
+
9
+
10
+ def _row(day: date, pnl: float, basis: float, groups=None, isin=None, estimated=False):
11
+ return {
12
+ "date": day.isoformat(),
13
+ "pnl": pnl,
14
+ "basis": basis,
15
+ "groups": groups if groups is not None else {"Equities": {"pnl": pnl, "basis": basis}},
16
+ "isin": isin if isin is not None else {"SYNTH001": pnl},
17
+ "estimated": estimated,
18
+ }
19
+
20
+
21
+ def test_weekday_sessions_and_prior_weekday():
22
+ days = list(weekday_sessions(date(2026, 1, 2), date(2026, 1, 6)))
23
+ assert days == [date(2026, 1, 2), date(2026, 1, 5), date(2026, 1, 6)]
24
+ assert prior_weekday(date(2026, 1, 5)) == date(2026, 1, 2)
25
+
26
+
27
+ def test_linked_twr_geometric_chaining_and_additive_contributions():
28
+ d1, d2 = date(2026, 1, 5), date(2026, 1, 6)
29
+ rows = [
30
+ _row(
31
+ d1,
32
+ pnl=11.0,
33
+ basis=100.0,
34
+ groups={"Equities": {"pnl": 10.0, "basis": 80.0}, "Bonds": {"pnl": 2.0, "basis": 20.0}},
35
+ isin={"SYNTH_EQ": 10.0, "SYNTH_BD": 2.0},
36
+ ),
37
+ _row(
38
+ d2,
39
+ pnl=-5.55,
40
+ basis=111.0,
41
+ groups={"Equities": {"pnl": -5.55, "basis": 90.0}, "Bonds": {"pnl": 0.0, "basis": 21.0}},
42
+ isin={"SYNTH_EQ": -5.55, "SYNTH_BD": 0.0},
43
+ ),
44
+ ]
45
+ res = linked_twr(rows, d1, d2, expected_pnl=5.45)
46
+ # (1 + 0.11) * (1 - 0.05) - 1 = 0.0545
47
+ assert res["twr"] == pytest.approx(0.0545, abs=1e-12)
48
+ # Exact additivity in percentage points: sum(isin_pp) + fees_pp == 100 * twr
49
+ total_isin_pp = sum(res["isin_contribution_pp"].values()) + res["fees_contribution_pp"]
50
+ assert total_isin_pp == pytest.approx(100.0 * res["twr"], abs=1e-12)
51
+ total_group_pp = sum(g["contribution_pp"] for g in res["exposures"].values()) + res["fees_contribution_pp"]
52
+ assert total_group_pp == pytest.approx(100.0 * res["twr"], abs=1e-12)
53
+
54
+
55
+ def test_linked_twr_rejects_missing_session_mismatch_and_invalid_capital():
56
+ d1, d2 = date(2026, 1, 5), date(2026, 1, 6)
57
+ with pytest.raises(PerformanceUnavailable, match="incomplete"):
58
+ linked_twr([_row(d1, 1.0, 100.0)], d1, d2)
59
+ with pytest.raises(PerformanceUnavailable, match="reconcile"):
60
+ linked_twr([_row(d1, 1.0, 100.0)], d1, d1, expected_pnl=5.0)
61
+ with pytest.raises(PerformanceUnavailable, match="positive investment capital"):
62
+ linked_twr([_row(d1, 5.0, 0.0)], d1, d1)
63
+ with pytest.raises(PerformanceUnavailable, match="exceeds its capital"):
64
+ linked_twr([_row(d1, -150.0, 100.0)], d1, d1)
65
+ with pytest.raises(PerformanceUnavailable, match="reconcile"):
66
+ linked_twr([_row(d1, 1.0, 100.0)], d1, d1, expected_pnl=float("nan"))
67
+ with pytest.raises(PerformanceUnavailable, match="Non-finite"):
68
+ linked_twr([_row(d1, 1.0, 100.0, isin={"SYNTH001": float("nan")})], d1, d1)
69
+
70
+
71
+ def test_monthly_returns_compounds_months_to_ytd():
72
+ rows = [
73
+ _row(date(2026, 1, 2), 2.0, 100.0),
74
+ _row(date(2026, 1, 5), 3.0, 102.0),
75
+ _row(date(2026, 2, 2), -1.05, 105.0),
76
+ ]
77
+ res = monthly_returns(rows)
78
+ assert len(res["months"]) == 2
79
+ assert res["months"][0]["month"] == "2026-01"
80
+ assert res["months"][0]["twr"] == pytest.approx(0.05, abs=1e-12)
81
+ assert res["months"][1]["twr"] == pytest.approx(-0.01, abs=1e-12)
82
+ assert res["ytd_twr"] == pytest.approx(1.05 * 0.99 - 1.0, abs=1e-12)
83
+ # Invalid negative basis invalidates month & YTD.
84
+ bad = [*rows, _row(date(2026, 2, 3), 1.0, -5.0)]
85
+ res_bad = monthly_returns(bad)
86
+ assert res_bad["months"][1]["twr"] is None
87
+ assert res_bad["ytd_twr"] is None
88
+ assert date(2026, 1, 2) + timedelta(days=3) == date(2026, 1, 5)
@@ -0,0 +1,108 @@
1
+ version = 1
2
+ revision = 5
3
+ requires-python = ">=3.11"
4
+
5
+ [[package]]
6
+ name = "colorama"
7
+ version = "0.4.6"
8
+ source = { registry = "https://pypi.org/simple" }
9
+ sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" }
10
+ wheels = [
11
+ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
12
+ ]
13
+
14
+ [[package]]
15
+ name = "iniconfig"
16
+ version = "2.3.1"
17
+ source = { registry = "https://pypi.org/simple" }
18
+ sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209, upload-time = "2026-10-06T22:48:38.076Z" }
19
+ wheels = [
20
+ { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" },
21
+ ]
22
+
23
+ [[package]]
24
+ name = "packaging"
25
+ version = "26.4"
26
+ source = { registry = "https://pypi.org/simple" }
27
+ sdist = { url = "https://files.pythonhosted.org/packages/c3/75/ffb1dc0ed12352139fb4ca0e3fde4325a23e3d0f3f40efe89717bc4f557b/packaging-26.4.tar.gz", hash = "sha256:c4b671c41ddb9bf26e543c37723610d28fb6bf7affc4da17cf048d419d2c062a", size = 355877, upload-time = "2026-11-23T21:44:11.152Z" }
28
+ wheels = [
29
+ { url = "https://files.pythonhosted.org/packages/ba/7b/5504f91c9c2733f693d7759e50ede5d27119d4da7e5836c46d3b5ff81d56/packaging-26.4-py3-none-any.whl", hash = "sha256:81383611a09c1bc0b08b76e0fd5829d7c6824c65b27a6aee339da133f4233ea2", size = 140049, upload-time = "2026-11-23T21:44:09.531Z" },
30
+ ]
31
+
32
+ [[package]]
33
+ name = "pluggy"
34
+ version = "1.7.0"
35
+ source = { registry = "https://pypi.org/simple" }
36
+ sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304, upload-time = "2026-10-15T09:50:58.343Z" }
37
+ wheels = [
38
+ { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" },
39
+ ]
40
+
41
+ [[package]]
42
+ name = "portfolio-twr"
43
+ version = "0.1.0"
44
+ source = { editable = "." }
45
+
46
+ [package.dev-dependencies]
47
+ dev = [
48
+ { name = "pytest" },
49
+ { name = "ruff" },
50
+ ]
51
+
52
+ [package.metadata]
53
+
54
+ [package.metadata.requires-dev]
55
+ dev = [
56
+ { name = "pytest", specifier = ">=8" },
57
+ { name = "ruff", specifier = ">=0.14" },
58
+ ]
59
+
60
+ [[package]]
61
+ name = "pygments"
62
+ version = "2.21.0"
63
+ source = { registry = "https://pypi.org/simple" }
64
+ sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" }
65
+ wheels = [
66
+ { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" },
67
+ ]
68
+
69
+ [[package]]
70
+ name = "pytest"
71
+ version = "9.2.0"
72
+ source = { registry = "https://pypi.org/simple" }
73
+ dependencies = [
74
+ { name = "colorama", marker = "sys_platform == 'win32'" },
75
+ { name = "iniconfig" },
76
+ { name = "packaging" },
77
+ { name = "pluggy" },
78
+ { name = "pygments" },
79
+ ]
80
+ sdist = { url = "https://files.pythonhosted.org/packages/79/42/bb4641652e58dedeac2ec51abc1f8cae4fee4ec63899a0999016229a0f2a/pytest-9.2.0.tar.gz", hash = "sha256:97c4f3b1f3c7414aa36465e09b8220f1d03627993bd51b1282e193753c80557b", size = 1797555, upload-time = "2026-10-27T21:30:20.728Z" }
81
+ wheels = [
82
+ { url = "https://files.pythonhosted.org/packages/51/39/1f5d8c8877a0fa327db959c19341d4be61660de1ab6b7391f9eb805bcd67/pytest-9.2.0-py3-none-any.whl", hash = "sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588", size = 411776, upload-time = "2026-10-27T21:30:19.131Z" },
83
+ ]
84
+
85
+ [[package]]
86
+ name = "ruff"
87
+ version = "0.17.6"
88
+ source = { registry = "https://pypi.org/simple" }
89
+ sdist = { url = "https://files.pythonhosted.org/packages/df/8e/6929d337aa5380aafc7355f3149f3ccfe55cba5fdd34a045697ebaceb5a0/ruff-0.17.6.tar.gz", hash = "sha256:2b04276561331300325040bdca21460770029ec574d4c479099e39e8ad1ed43c", size = 5374388, upload-time = "2026-11-19T15:56:27.106Z" }
90
+ wheels = [
91
+ { url = "https://files.pythonhosted.org/packages/12/5d/38ef6310c22cacb094e9ae0ff7964062e04ffeecb45ee296894c2b1acc54/ruff-0.17.6-py3-none-linux_armv6l.whl", hash = "sha256:084d9c8f5ec718e7eba007dba339e7cb4f7571d2f267558ae080bf428fb6a69b", size = 10174693, upload-time = "2026-11-19T15:55:52.414Z" },
92
+ { url = "https://files.pythonhosted.org/packages/a2/ed/fd35261049920a4888ef7c787a5c27089502077a4910f6ca8f1213157d6d/ruff-0.17.6-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:9d44ef2140402043fd6f689ef541858b80883a8b0a02e38539ef0614ebe57d0c", size = 10221650, upload-time = "2026-11-19T15:55:54.962Z" },
93
+ { url = "https://files.pythonhosted.org/packages/ba/d4/c31391b36c729cd9fafa65b7a52a58850b99afb2b65da6be4263a53302f2/ruff-0.17.6-py3-none-macosx_11_0_arm64.whl", hash = "sha256:9fbddc08577592e283c265d865e0182de6e33db185494db7b06290d989d888e5", size = 9580986, upload-time = "2026-11-19T15:55:57.391Z" },
94
+ { url = "https://files.pythonhosted.org/packages/eb/11/f3032684dcb3a676d7924545153d76fb56f76753e038f2ea650b99c71bdf/ruff-0.17.6-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:435241c61af5909a022f76219d3d1bf24730dc1bf0acabb5ddf4b569ab3cbb30", size = 10271368, upload-time = "2026-11-19T15:55:59.654Z" },
95
+ { url = "https://files.pythonhosted.org/packages/08/30/c1e024eeb5bae99ae78c6b896ed108f64c9c845a03b56eaeff098e99b6e6/ruff-0.17.6-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d006bbb2945edb17b0ce6a0c1b5f5a8d81ba11dbac294a0a925effa22ce34feb", size = 9981564, upload-time = "2026-11-19T15:56:01.807Z" },
96
+ { url = "https://files.pythonhosted.org/packages/7d/a5/da3e0c2d4bf02b3ca6c1d7fa4bb04d0081e340b1dd03c4f83b1bec3e15c1/ruff-0.17.6-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:fd661702202a89c00a4c9d0339008805fa5876bfa1c57e165495c2e62230dfbf", size = 10641991, upload-time = "2026-11-19T15:56:03.981Z" },
97
+ { url = "https://files.pythonhosted.org/packages/4d/c1/6d7f981e86201c9db457cca99fd2c09b77574ebab37dff3e9239b218603c/ruff-0.17.6-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6a12c50a33936dc00db2be21ba25fb168a8b95c55eda2a3ac85005af69885e4b", size = 11403484, upload-time = "2026-11-19T15:56:05.778Z" },
98
+ { url = "https://files.pythonhosted.org/packages/c3/92/8182f07b94998541d5f8f38f53da465aa28062afce24ecc398f45bfc62f1/ruff-0.17.6-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b5aba93b3db4b70c5697e4fee6e0d5b9c8452a9a3a03679611cadc25915a2173", size = 10892316, upload-time = "2026-11-19T15:56:08.016Z" },
99
+ { url = "https://files.pythonhosted.org/packages/be/48/3df7d81249fd69ee6a49519b149fb5d11e13118fd7d0e8d65329a237087b/ruff-0.17.6-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aa3b08254a732acba246891089a152c47c5733dc36b8ecb76ce8602f8326e5e4", size = 10645279, upload-time = "2026-11-19T15:56:09.785Z" },
100
+ { url = "https://files.pythonhosted.org/packages/71/80/4d232281544345d7beb98d1d32c24dae804ed360780a6f7753738b81225e/ruff-0.17.6-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:0692088e6b33455572fb18465e891b443f196e98dc1986825685c77ff6f4c5ac", size = 10534501, upload-time = "2026-11-19T15:56:11.718Z" },
101
+ { url = "https://files.pythonhosted.org/packages/98/0a/b477f075a4a94eb541bf1c759a3e72b2a3d6390af7a13a5be0887229f67c/ruff-0.17.6-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:fb589e032806bb942e4fb526f30b80a1a64112147ed9f1d38cc3de2e255b6f45", size = 10136036, upload-time = "2026-11-19T15:56:13.779Z" },
102
+ { url = "https://files.pythonhosted.org/packages/f1/d8/cf32fbfeb1fcda1470fb5c3bee50c69ee6bca257d487ec1eb17a0387edb4/ruff-0.17.6-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:1939b3d701c7b6981b7cf93473de5bf88b129b9ba84efaed5154cc517c44634d", size = 9969640, upload-time = "2026-11-19T15:56:15.738Z" },
103
+ { url = "https://files.pythonhosted.org/packages/a7/22/bb9f9752f7fcdfdc8b9c51576cc142bb377ade745290e35085173963c7be/ruff-0.17.6-py3-none-musllinux_1_2_i686.whl", hash = "sha256:1a0bea6aa1216e0ec4cd35d3dbccec0d772a7c2aad28ec9c6e82571dff2c20b0", size = 10389427, upload-time = "2026-11-19T15:56:17.617Z" },
104
+ { url = "https://files.pythonhosted.org/packages/81/c7/e09d220818ab146b736d62e0676dad215215d7de0884bbdad9fa075dc7d2/ruff-0.17.6-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:3db61f5015600543a581b07fa7f6f64afa0eeedefe16034cadd88c4074087582", size = 10760296, upload-time = "2026-11-19T15:56:19.463Z" },
105
+ { url = "https://files.pythonhosted.org/packages/2e/09/28329441dfa2c463e2d377a69d4ebbe4d51665e9dbd49fb421f3bc80d775/ruff-0.17.6-py3-none-win32.whl", hash = "sha256:c2f4af6670b7a0501904e881bb3f1f24bd0d964dec1eedbd85f0eb73786e1128", size = 9966266, upload-time = "2026-11-19T15:56:21.581Z" },
106
+ { url = "https://files.pythonhosted.org/packages/4b/9d/18ba9730addfc7554c70d6f171fb8dc2c08e774d9fb2b98e7946ef845c59/ruff-0.17.6-py3-none-win_amd64.whl", hash = "sha256:9cd2fd9923e9806b8b6b67a3469e2258e84bd4d21e45d5a1a690afdfb9c8e57d", size = 10365847, upload-time = "2026-11-19T15:56:23.582Z" },
107
+ { url = "https://files.pythonhosted.org/packages/70/8a/59c33e2a64a4f9672f7f842a0dc522915cfbbaffd13d37d0cec57d1c5c5d/ruff-0.17.6-py3-none-win_arm64.whl", hash = "sha256:d8b14e1473dc86ab9069cf7a2ba5041dc012f59110201844ed04cfddf07055a0", size = 9926224, upload-time = "2026-11-19T15:56:25.269Z" },
108
+ ]