mirror of
https://github.com/OpenBB-finance/OpenBB.git
synced 2026-11-04 00:12:29 +00:00
* Drop Python 3.10 support
Python 3.10 reached end of life on 2026-10-01, and the patched releases of
Pillow (13.0.0) and filelock (>=4.2.1) require Python >=3.11, so the 3.10
resolution fork kept vulnerable versions in every lockfile.
- requires-python = ">=3.11,<4" in all pyproject.toml files, the
cookiecutter template, and the CLI codegen project template
- CI: drop the ubuntu 3.10 matrix rows, move the macOS/Windows minimum
rows and the lint jobs to 3.11, drop 3.10 from the nox sessions
- READMEs: state 3.11 as the minimum supported version
* Relock with patched certifi, filelock, virtualenv, Pillow, and fastmcp
Regenerate all 38 uv.lock files against requires-python >=3.11 and upgrade
only the packages with open Dependabot advisories:
- certifi 2026.7.22 -> 2026.10.23 (GHSA-6q48-6c7w-9gw2, compromised emSign CAs)
- virtualenv 21.14.7 -> 21.14.13
- filelock 4.1.0/4.2.0 -> 4.2.4
- Pillow 12.3.0 -> 13.0.0
- fastmcp / fastmcp-slim 4.1.0 -> 4.1.3
All other changes are removed Python 3.10-only resolution forks; no other
package changes version for Python 3.11+.
* desktop: bump zod, @hookform/resolvers, and vitest
- zod ^3.25.76 -> ^4.6.7 (GHSA-mrhx-c7xc-m3w5; no patched 3.x exists)
- @hookform/resolvers ^3.10.0 -> ^5.9.2 for zod 4 support
- vitest ^4.1.11 -> ^4.1.12 (@vitest/mocker GHSA-qxg6-89mg-rqv8,
GHSA-xp26-3454-mjgp)
- override zod to the root version so @openbb/ui-pro, which declares
zod ^3 but never imports it, does not pull in a second, vulnerable copy
* desktop: remove Python 3.10 from environment pickers
- version pickers in InstallComponents and AddExtensionSelector start at 3.11
- create_environment_from_requirements accepts 3.11 through 3.14 and falls
back to 3.12 otherwise (previously 3.10 through 3.13)
- component tests select 3.11 instead of 3.10
* Remove Python 3.10 tomli fallbacks
With requires-python >=3.11, tomllib is always available, so the
version-conditional tomli imports are dead code.
- import tomllib directly in the cli and core config loaders, the
mcp_server and platform_api config validators, dev_install.py, and
the cli and cookiecutter tests; dev_install.py no longer pip-installs
tomli on the fly
- drop the tomli>=2.0; python_version<'3.11' dependency from cli, core,
mcp_server, and platform_api, plus platform_api's backport comment
- raise the fake-extension fixtures in cli/conftest.py,
core/integration/conftest.py, and the charting test metadata to
>=3.11
- relock cli, core, mcp_server, and platform_api; only the tomli
requires-dist entry is removed and resolution markers are reordered,
no package versions change
* Target Python 3.11 in ruff and ty for cli, core, mcp_server, platform_api, cookiecutter
With ruff target-version py310 and ty python-version 3.10, both tools
reject an unconditional `import tomllib`: ty reports it as unresolved
(exit 1) and ruff's isort classifies it as third-party. Raise the targets
in the projects that now import tomllib directly, and in the root
ruff.toml that governs dev_install.py.
- ruff target-version = "py311" and ty python-version = "3.11" in cli,
core, mcp_server, platform_api, and cookiecutter; root ruff.toml
target-version = "py311"
- UP042: OutputMode, ChartLifecycle, MCPType, and HTTPMethod become
StrEnum; every consumer uses .value or == comparisons, so only str()
and format() output change
- UP017: datetime.timezone.utc -> datetime.UTC (ruff autofix) in the cli
dispatchers, the cli test generator, and a core test
* Fix ruff and ty failures in packages this PR touches
CI installs unpinned dependencies, so the lint jobs ran against
pandas 3.1.0, ruff 0.17.2, and ty 0.0.91.
- cli/conftest.py: guard the find_spec("openbb") lookup so ty no longer
reports an Optional ModuleSpec/origin (failing Lint openbb-cli)
- quantitative: pandas 3.1 types Index.max() as object; cast max_date to
Timestamp before period_start in attribution, factors, and
risk_decomposition (failing ty)
- federal_reserve: use Series(...).dt.date instead of
DatetimeIndex.date so neither pandas 3.0 nor 3.1 needs a ty: ignore
(pandas 3.1 made the existing ignores unused, failing ty)
- core tests: type the filter_by_dates doubles as Data subclasses and
cast the deliberate bad arguments in test_helpers.py; apply ruff format
to test_docstring_generator_helpers.py
- platform_api README: apply ruff format to the Python code blocks
* Fix pandas 3.1 deprecations failing fred, sec, and eia tests
These suites turn warnings into errors, and pandas 3.1.0 adds
Pandas4Warning deprecations for several patterns they use. Every change
also passes with the locked pandas 3.0.6.
- fred, sec: replace inplace=True sort_values/reset_index/rename/
set_index/drop with reassignment
- fred balance_of_payments, sec as_filed_widget: replace fillna with a
string on float columns by astype(object).where(notna, ...)
- sec: build quarter start dates from ISO strings instead of parsing
"2024Q2"-style strings; use the DataFrame constructor instead of
DataFrame.from_records for column dicts; pad CIK lookup rows to two
fields instead of constructing a ragged DataFrame
- eia: read EIA workbooks with the calamine engine (xlrd is deprecated);
replace the xlrd dependency with python-calamine and relock; calamine
workbooks are not safe for concurrent reads, so the petroleum status
report serializes its sheet reads with a lock
* imf: fall back to the published catalog when the IMF API is unreachable
imf_cache.json.xz is generated at build time and is not committed, so
every CI build of openbb-imf needed a live api.imf.org. The only fallback
was actions/cache, and caches saved by pull_request runs are scoped to
that PR, so a new PR never had one. With api.imf.org returning
"503 no healthy upstream" during IMF's data portal maintenance window,
the build failed.
When live generation fails on a non-forced build, the hook now copies
imf_cache.json.xz from the latest openbb-imf wheel on PyPI, after
checking the wheel's sha256 against the digest PyPI publishes. Builds
with OPENBB_IMF_FORCE_CACHE_REBUILD=1, which the publish workflow sets,
still fail hard, so a release never ships a stale catalog.
---------
Co-authored-by: dlee-bq <325002271+dlee-bq@users.noreply.github.com>
153 lines
5.4 KiB
Python
153 lines
5.4 KiB
Python
"""Quantitative return-attribution commands."""
|
|
|
|
from typing import TYPE_CHECKING, cast
|
|
|
|
from openbb_core.app.model.example import APIEx
|
|
from openbb_core.app.model.obbject import OBBject
|
|
from openbb_core.app.router import Router
|
|
from openbb_core.provider.abstract.data import Data
|
|
from openbb_core.provider.abstract.query_params import QueryParams
|
|
from pydantic import Field
|
|
|
|
from openbb_quantitative._factor_helpers import (
|
|
_DEFAULT_PERIODS,
|
|
align_inputs,
|
|
period_start,
|
|
)
|
|
|
|
if TYPE_CHECKING:
|
|
from pandas import Timestamp
|
|
|
|
router = Router(prefix="", description="Return-attribution commands.")
|
|
|
|
_ALPHA_LABEL = "Alpha"
|
|
_RESIDUAL_LABEL = "Residual"
|
|
|
|
|
|
class ReturnAttributionQueryParams(QueryParams):
|
|
"""Query parameters for the attribution endpoint."""
|
|
|
|
__category__ = "quantitative"
|
|
__output_columns__ = ("period", "factor", "contribution", "share")
|
|
|
|
data: list[Data] = Field(
|
|
description="Target periodic return series (index column plus the target column)."
|
|
)
|
|
factors_data: list[Data] = Field(
|
|
description="Factor return matrix (index column plus one column per factor),"
|
|
" in the same units as the target."
|
|
)
|
|
target: str = Field(
|
|
default="close",
|
|
description="Name of the return column in `data` to attribute across the factors.",
|
|
)
|
|
index: str = Field(
|
|
default="date",
|
|
description="Name of the index column shared by `data` and `factors_data`.",
|
|
)
|
|
risk_free_column: str | None = Field(
|
|
default=None,
|
|
description="Optional name of the risk-free rate column in `factors_data`."
|
|
" When provided, the target is converted to excess returns before"
|
|
" attribution and the column is dropped from the factor set.",
|
|
)
|
|
periods: list[str] = Field(
|
|
default_factory=lambda: list(_DEFAULT_PERIODS),
|
|
description="Named look-back periods to attribute over, anchored to the"
|
|
" latest factor observation.",
|
|
)
|
|
|
|
|
|
class ReturnAttributionData(Data):
|
|
"""One return-contribution observation for a given look-back period."""
|
|
|
|
period: str = Field(description="Look-back period the attribution was run over.")
|
|
factor: str = Field(
|
|
description="Factor name, 'Alpha' for the intercept contribution, or"
|
|
" 'Residual' for the unexplained residual."
|
|
)
|
|
contribution: float = Field(
|
|
description="Component's contribution to the period's total target return:"
|
|
" for a factor, beta_i * sum_t factor_i; for 'Alpha', alpha * n; for"
|
|
" 'Residual', sum of regression residuals. The three sum to the period's"
|
|
" total target return."
|
|
)
|
|
share: float = Field(
|
|
description="Component's contribution divided by the total target return"
|
|
" over the period. Shares sum to 1.0 unless the total return is zero."
|
|
)
|
|
|
|
|
|
@router.command(
|
|
methods=["POST"],
|
|
examples=[
|
|
APIEx(
|
|
parameters={
|
|
"target": "close",
|
|
"data": APIEx.mock_data("timeseries", 800),
|
|
"factors_data": APIEx.mock_data("timeseries", 800),
|
|
}
|
|
)
|
|
],
|
|
)
|
|
def attribution(
|
|
params: ReturnAttributionQueryParams,
|
|
) -> OBBject[list[ReturnAttributionData]]:
|
|
"""Decompose the target's total return into per-factor contributions plus alpha
|
|
and residual.
|
|
|
|
For each look-back period, runs OLS of the target on the factor matrix and
|
|
splits the period's cumulative target return via the identity
|
|
`sum_t y_t = alpha * n + sum_i beta_i * sum_t f_{i,t} + sum_t residual_t`.
|
|
The three components are returned as rows: one per factor, one `Alpha`, and one
|
|
`Residual`. Use with arithmetic (additive) returns; for geometric compounding,
|
|
convert returns to log-returns before passing in.
|
|
"""
|
|
import statsmodels.api as sm
|
|
|
|
factor_matrix, target_series, factor_cols = align_inputs(
|
|
params.data,
|
|
params.factors_data,
|
|
target=params.target,
|
|
index=params.index,
|
|
risk_free_column=params.risk_free_column,
|
|
)
|
|
aligned = factor_matrix.assign(**{params.target: target_series})
|
|
max_date = cast("Timestamp", aligned.index.max())
|
|
out: list[ReturnAttributionData] = []
|
|
|
|
for period in params.periods:
|
|
start = period_start(max_date, period)
|
|
window = aligned if start is None else aligned[aligned.index >= start]
|
|
if len(window) <= len(factor_cols) + 1:
|
|
continue
|
|
|
|
y = window[params.target]
|
|
total_return = float(y.sum())
|
|
x = sm.add_constant(window[factor_cols])
|
|
model = sm.OLS(y, x).fit()
|
|
n = len(window)
|
|
|
|
alpha_contribution = float(model.params["const"]) * n
|
|
residual_contribution = float(model.resid.sum())
|
|
components: list[tuple[str, float]] = []
|
|
for name in factor_cols:
|
|
beta = float(model.params[name])
|
|
factor_sum = float(window[name].sum())
|
|
components.append((name, beta * factor_sum))
|
|
components.append((_ALPHA_LABEL, alpha_contribution))
|
|
components.append((_RESIDUAL_LABEL, residual_contribution))
|
|
|
|
denom = total_return if total_return != 0.0 else float("nan")
|
|
for name, contribution in components:
|
|
out.append(
|
|
ReturnAttributionData(
|
|
period=period,
|
|
factor=name,
|
|
contribution=contribution,
|
|
share=contribution / denom,
|
|
)
|
|
)
|
|
|
|
return OBBject(results=out)
|