跳转至

AnalysisContext

The AnalysisContext provides lazy, cached metric computation with export capabilities.

Basic Usage

import pandas as pd

import fincore

index = pd.date_range("2024-01-02", periods=5, freq="B")
returns = pd.Series([0.01, -0.005, 0.002, 0.004, -0.001], index=index)
benchmark = pd.Series([0.008, -0.003, 0.001, 0.002, 0.0], index=index)

ctx = fincore.analyze(returns, factor_returns=benchmark)

# Metrics computed on first access, then cached
print(ctx.sharpe_ratio)
print(ctx.max_drawdown)
print(ctx.annual_return)
print(ctx.alpha)
print(ctx.beta)

Performance Stats

stats = ctx.perf_stats()  # pandas Series with all key metrics
print(stats)

Export

# JSON text
json_str = ctx.to_json()

# JSON file
ctx.to_json(path="report.json")

# Dictionary
d = ctx.to_dict()

# HTML report (self-contained, no extra dependencies)
ctx.to_html(path="report.html")

# Plot -> ReportArtifacts (requires fincore[viz] for matplotlib)
artifacts = ctx.plot(backend="matplotlib")

Snapshot semantics and cache invalidation

Inputs are defensively snapshotted: mutating the caller's series after analyze() does not change cached results. replace_data() atomically swaps inputs and invalidates every cached metric:

ctx.replace_data(returns=returns + 0.001)

API Reference

fincore.core.context.AnalysisContext(returns, *, factor_returns=None, positions=None, transactions=None, period=DAILY, normalize_tz=None)

Lazy, cached container for performance analytics.

All metrics are computed on first access and cached via :func:functools.cached_property. Call :meth:invalidate to clear all cached values (e.g. after replacing the underlying data).

参数:

名称 类型 描述 默认
returns Series

Non-cumulative simple returns with a DatetimeIndex.

必需
factor_returns Series

Benchmark / factor returns aligned to the same dates.

None
positions DataFrame

Daily net position values.

None
transactions DataFrame

Executed trades.

None
period str

Data frequency. Default DAILY.

DAILY

Initialize the analysis context.

参数:

名称 类型 描述 默认
returns Series

Portfolio returns.

必需
factor_returns Series

Benchmark or factor returns.

None
positions DataFrame

Portfolio positions.

None
transactions DataFrame

Executed trades.

None
period str

Data frequency.

DAILY
normalize_tz (None, 'UTC')

Explicit timezone normalization for datetime-indexed inputs. Mixed timezones are rejected unless UTC normalization is requested.

None

annual_return cached property

Annualized return.

cumulative_returns cached property

Total cumulative return.

annual_volatility cached property

Annualized volatility.

sharpe_ratio cached property

Sharpe ratio (annualized).

calmar_ratio cached property

Calmar ratio (annual return / max drawdown).

stability cached property

R-squared of linear fit to cumulative returns.

max_drawdown cached property

Maximum drawdown.

omega_ratio cached property

Omega ratio.

sortino_ratio cached property

Sortino ratio (annualized).

skew cached property

Return skewness.

kurtosis cached property

Return kurtosis.

tail_ratio cached property

Tail ratio (95th percentile / 5th percentile).

daily_value_at_risk cached property

Daily Value at Risk.

alpha cached property

Alpha (excess return over factor returns).

beta cached property

Beta (sensitivity to factor returns).

gross_leverage cached property

Gross leverage series for the stored positions snapshot.

turnover cached property

Turnover series for the stored portfolio and transaction snapshots.

compute(name, *args, **kwargs)

Compute an extension-registered metric by name on the stored returns.

Resolves metrics registered through :func:fincore.plugin.register_metric (default family). The metric receives the stored returns as its first argument, followed by any positional/keyword arguments given here.

引发:

类型 描述
ValueError

If no extension metric with this name is registered.

perf_stats()

Return a :class:pd.Series of key performance metrics.

This method assembles the cached sub-metrics so that repeated calls are essentially free after the first computation.

to_dict()

Return metrics as a plain dict (JSON-friendly values).

to_json(path=None, **kwargs)

Serialize metrics and optionally write the exact payload to path.

plot(backend='matplotlib', **kwargs)

Plot key performance charts using the specified backend.

参数:

名称 类型 描述 默认
backend str

Visualization backend name ('matplotlib' or 'html', or a backend registered through :func:fincore.plugin.register_viz_backend).

'matplotlib'

返回:

类型 描述
Depends on the backend (e.g. matplotlib Figure or HTML string).
Custom backends that define ``render(model, **kwargs)`` receive a
class:`~fincore.viz.base.RenderModel` and control the returned
artifacts.

to_html(path=None)

Generate a self-contained HTML performance report.

参数:

名称 类型 描述 默认
path str

If given, write the HTML to this file path.

None

返回:

类型 描述
str

The HTML report as a string.

invalidate()

Clear all cached metric values.

replace_data(*, returns=_UNSET, factor_returns=_UNSET, positions=_UNSET, transactions=_UNSET, period=_UNSET, normalize_tz=_UNSET)

Atomically replace snapshot inputs and invalidate every cached metric.