fincore 0.1.0__py3-none-any.whl
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.
- fincore/__init__.py +105 -0
- fincore/_registry.py +256 -0
- fincore/_types.py +55 -0
- fincore/constants/__init__.py +68 -0
- fincore/constants/color.py +22 -0
- fincore/constants/interesting_periods.py +68 -0
- fincore/constants/periods.py +44 -0
- fincore/constants/style.py +158 -0
- fincore/core/__init__.py +5 -0
- fincore/core/context.py +356 -0
- fincore/core/engine.py +148 -0
- fincore/empyrical.py +669 -0
- fincore/metrics/__init__.py +57 -0
- fincore/metrics/alpha_beta.py +658 -0
- fincore/metrics/basic.py +232 -0
- fincore/metrics/bayesian.py +449 -0
- fincore/metrics/consecutive.py +485 -0
- fincore/metrics/drawdown.py +726 -0
- fincore/metrics/perf_attrib.py +395 -0
- fincore/metrics/perf_stats.py +267 -0
- fincore/metrics/positions.py +359 -0
- fincore/metrics/ratios.py +1007 -0
- fincore/metrics/returns.py +305 -0
- fincore/metrics/risk.py +630 -0
- fincore/metrics/rolling.py +538 -0
- fincore/metrics/round_trips.py +397 -0
- fincore/metrics/stats.py +574 -0
- fincore/metrics/timing.py +243 -0
- fincore/metrics/transactions.py +405 -0
- fincore/metrics/yearly.py +327 -0
- fincore/pyfolio.py +1219 -0
- fincore/report.py +1113 -0
- fincore/tearsheets/__init__.py +107 -0
- fincore/tearsheets/bayesian.py +218 -0
- fincore/tearsheets/capacity.py +165 -0
- fincore/tearsheets/perf_attrib.py +232 -0
- fincore/tearsheets/positions.py +365 -0
- fincore/tearsheets/returns.py +851 -0
- fincore/tearsheets/risk.py +335 -0
- fincore/tearsheets/round_trips.py +165 -0
- fincore/tearsheets/sheets.py +1021 -0
- fincore/tearsheets/transactions.py +284 -0
- fincore/tearsheets/utils.py +90 -0
- fincore/utils/__init__.py +111 -0
- fincore/utils/common_utils.py +896 -0
- fincore/utils/data_utils.py +202 -0
- fincore/utils/date_utils.py +10 -0
- fincore/utils/deprecate.py +30 -0
- fincore/utils/math_utils.py +64 -0
- fincore/viz/__init__.py +11 -0
- fincore/viz/base.py +64 -0
- fincore/viz/html_backend.py +163 -0
- fincore/viz/matplotlib_backend.py +102 -0
- fincore-0.1.0.dist-info/METADATA +751 -0
- fincore-0.1.0.dist-info/RECORD +58 -0
- fincore-0.1.0.dist-info/WHEEL +5 -0
- fincore-0.1.0.dist-info/licenses/LICENSE +201 -0
- fincore-0.1.0.dist-info/top_level.txt +1 -0
fincore/__init__.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
2
|
+
|
|
3
|
+
# NumPy 2.0 dropped the ``np.unicode_`` alias which some optional
|
|
4
|
+
# dependencies (for example, older versions of ``numexpr`` or PyMC) still
|
|
5
|
+
# import. Provide a minimal forward-compat shim so importing fincore does
|
|
6
|
+
# not fail when those packages are present in the environment.
|
|
7
|
+
import numpy as _np
|
|
8
|
+
|
|
9
|
+
if not hasattr(_np, "unicode_"):
|
|
10
|
+
_np.unicode_ = _np.str_
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
# Core classes
|
|
14
|
+
"Empyrical",
|
|
15
|
+
"Pyfolio",
|
|
16
|
+
"analyze",
|
|
17
|
+
"create_strategy_report",
|
|
18
|
+
# Commonly-used metric functions (flat API)
|
|
19
|
+
"sharpe_ratio",
|
|
20
|
+
"sortino_ratio",
|
|
21
|
+
"max_drawdown",
|
|
22
|
+
"annual_return",
|
|
23
|
+
"annual_volatility",
|
|
24
|
+
"cum_returns",
|
|
25
|
+
"cum_returns_final",
|
|
26
|
+
"alpha",
|
|
27
|
+
"beta",
|
|
28
|
+
"alpha_beta",
|
|
29
|
+
"calmar_ratio",
|
|
30
|
+
"omega_ratio",
|
|
31
|
+
"information_ratio",
|
|
32
|
+
"stability_of_timeseries",
|
|
33
|
+
"tail_ratio",
|
|
34
|
+
"value_at_risk",
|
|
35
|
+
"capture",
|
|
36
|
+
"downside_risk",
|
|
37
|
+
"simple_returns",
|
|
38
|
+
"aggregate_returns",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
# ---------------------------------------------------------------------------
|
|
42
|
+
# Lazy imports — defer heavy submodules until first attribute access.
|
|
43
|
+
# ``from fincore import empyrical`` still works because Python resolves
|
|
44
|
+
# sub-module names before calling ``__getattr__``.
|
|
45
|
+
# ---------------------------------------------------------------------------
|
|
46
|
+
|
|
47
|
+
# Maps commonly-used function names to (module_path, attr_name)
|
|
48
|
+
_FLAT_API = {
|
|
49
|
+
"sharpe_ratio": ("fincore.metrics.ratios", "sharpe_ratio"),
|
|
50
|
+
"sortino_ratio": ("fincore.metrics.ratios", "sortino_ratio"),
|
|
51
|
+
"calmar_ratio": ("fincore.metrics.ratios", "calmar_ratio"),
|
|
52
|
+
"omega_ratio": ("fincore.metrics.ratios", "omega_ratio"),
|
|
53
|
+
"information_ratio": ("fincore.metrics.ratios", "information_ratio"),
|
|
54
|
+
"stability_of_timeseries": ("fincore.metrics.ratios", "stability_of_timeseries"),
|
|
55
|
+
"capture": ("fincore.metrics.ratios", "capture"),
|
|
56
|
+
"max_drawdown": ("fincore.metrics.drawdown", "max_drawdown"),
|
|
57
|
+
"annual_return": ("fincore.metrics.yearly", "annual_return"),
|
|
58
|
+
"annual_volatility": ("fincore.metrics.risk", "annual_volatility"),
|
|
59
|
+
"downside_risk": ("fincore.metrics.risk", "downside_risk"),
|
|
60
|
+
"value_at_risk": ("fincore.metrics.risk", "value_at_risk"),
|
|
61
|
+
"tail_ratio": ("fincore.metrics.risk", "tail_ratio"),
|
|
62
|
+
"cum_returns": ("fincore.metrics.returns", "cum_returns"),
|
|
63
|
+
"cum_returns_final": ("fincore.metrics.returns", "cum_returns_final"),
|
|
64
|
+
"simple_returns": ("fincore.metrics.returns", "simple_returns"),
|
|
65
|
+
"aggregate_returns": ("fincore.metrics.returns", "aggregate_returns"),
|
|
66
|
+
"alpha": ("fincore.metrics.alpha_beta", "alpha"),
|
|
67
|
+
"beta": ("fincore.metrics.alpha_beta", "beta"),
|
|
68
|
+
"alpha_beta": ("fincore.metrics.alpha_beta", "alpha_beta"),
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def __getattr__(name: str):
|
|
73
|
+
if name == "Empyrical":
|
|
74
|
+
from .empyrical import Empyrical
|
|
75
|
+
|
|
76
|
+
globals()["Empyrical"] = Empyrical
|
|
77
|
+
return Empyrical
|
|
78
|
+
if name == "Pyfolio":
|
|
79
|
+
from .pyfolio import Pyfolio
|
|
80
|
+
|
|
81
|
+
globals()["Pyfolio"] = Pyfolio
|
|
82
|
+
return Pyfolio
|
|
83
|
+
if name == "analyze":
|
|
84
|
+
from .core.context import analyze
|
|
85
|
+
|
|
86
|
+
globals()["analyze"] = analyze
|
|
87
|
+
return analyze
|
|
88
|
+
if name == "create_strategy_report":
|
|
89
|
+
from .report import create_strategy_report
|
|
90
|
+
|
|
91
|
+
globals()["create_strategy_report"] = create_strategy_report
|
|
92
|
+
return create_strategy_report
|
|
93
|
+
|
|
94
|
+
# Flat metric function API
|
|
95
|
+
entry = _FLAT_API.get(name)
|
|
96
|
+
if entry is not None:
|
|
97
|
+
import importlib
|
|
98
|
+
|
|
99
|
+
mod_path, attr_name = entry
|
|
100
|
+
mod = importlib.import_module(mod_path)
|
|
101
|
+
func = getattr(mod, attr_name)
|
|
102
|
+
globals()[name] = func
|
|
103
|
+
return func
|
|
104
|
+
|
|
105
|
+
raise AttributeError(f"module 'fincore' has no attribute {name!r}")
|
fincore/_registry.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""Function registry for auto-generating Empyrical class methods.
|
|
2
|
+
|
|
3
|
+
This module defines the mapping from Empyrical method names to their
|
|
4
|
+
underlying metric functions. The registry is consumed by empyrical.py
|
|
5
|
+
to auto-generate class methods, eliminating ~1000 lines of hand-written
|
|
6
|
+
boilerplate delegation code.
|
|
7
|
+
|
|
8
|
+
Each entry is a tuple of:
|
|
9
|
+
(method_name, module_alias, function_name, method_type)
|
|
10
|
+
|
|
11
|
+
Method types:
|
|
12
|
+
'static' — exposed as staticmethod (utility helpers)
|
|
13
|
+
'class' — exposed as classmethod-like static forwarding
|
|
14
|
+
'dual_r' — _dual_method that auto-fills ``returns`` from instance
|
|
15
|
+
'dual_rf' — _dual_method that auto-fills ``returns`` and ``factor_returns``
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
# ---------------------------------------------------------------------------
|
|
19
|
+
# Static methods (module_alias, func_name)
|
|
20
|
+
# ---------------------------------------------------------------------------
|
|
21
|
+
STATIC_METHODS = {
|
|
22
|
+
"_ensure_datetime_index_series": ("_basic", "ensure_datetime_index_series"),
|
|
23
|
+
"_flatten": ("_basic", "flatten"),
|
|
24
|
+
"_adjust_returns": ("_basic", "adjust_returns"),
|
|
25
|
+
"annualization_factor": ("_basic", "annualization_factor"),
|
|
26
|
+
"_to_pandas": ("_basic", "to_pandas"),
|
|
27
|
+
"_aligned_series": ("_basic", "aligned_series"),
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
# ---------------------------------------------------------------------------
|
|
31
|
+
# Class methods — simple forwarding to module function
|
|
32
|
+
# (method_name, module_alias, func_name)
|
|
33
|
+
# ---------------------------------------------------------------------------
|
|
34
|
+
CLASSMETHOD_REGISTRY = {
|
|
35
|
+
# returns
|
|
36
|
+
"simple_returns": ("_returns", "simple_returns"),
|
|
37
|
+
"cum_returns": ("_returns", "cum_returns"),
|
|
38
|
+
"cum_returns_final": ("_returns", "cum_returns_final"),
|
|
39
|
+
"aggregate_returns": ("_returns", "aggregate_returns"),
|
|
40
|
+
"normalize": ("_returns", "normalize"),
|
|
41
|
+
# drawdown
|
|
42
|
+
"max_drawdown": ("_drawdown", "max_drawdown"),
|
|
43
|
+
"_get_all_drawdowns": ("_drawdown", "get_all_drawdowns"),
|
|
44
|
+
"_get_all_drawdowns_detailed": ("_drawdown", "get_all_drawdowns_detailed"),
|
|
45
|
+
"get_max_drawdown": ("_drawdown", "get_max_drawdown"),
|
|
46
|
+
"get_max_drawdown_underwater": ("_drawdown", "get_max_drawdown_underwater"),
|
|
47
|
+
"get_top_drawdowns": ("_drawdown", "get_top_drawdowns"),
|
|
48
|
+
"gen_drawdown_table": ("_drawdown", "gen_drawdown_table"),
|
|
49
|
+
# risk
|
|
50
|
+
"annual_volatility": ("_risk", "annual_volatility"),
|
|
51
|
+
"downside_risk": ("_risk", "downside_risk"),
|
|
52
|
+
"value_at_risk": ("_risk", "value_at_risk"),
|
|
53
|
+
"conditional_value_at_risk": ("_risk", "conditional_value_at_risk"),
|
|
54
|
+
"tail_ratio": ("_risk", "tail_ratio"),
|
|
55
|
+
"tracking_error": ("_risk", "tracking_error"),
|
|
56
|
+
"trading_value_at_risk": ("_risk", "trading_value_at_risk"),
|
|
57
|
+
# ratios
|
|
58
|
+
"sharpe_ratio": ("_ratios", "sharpe_ratio"),
|
|
59
|
+
"sortino_ratio": ("_ratios", "sortino_ratio"),
|
|
60
|
+
"excess_sharpe": ("_ratios", "excess_sharpe"),
|
|
61
|
+
"calmar_ratio": ("_ratios", "calmar_ratio"),
|
|
62
|
+
"omega_ratio": ("_ratios", "omega_ratio"),
|
|
63
|
+
"information_ratio": ("_ratios", "information_ratio"),
|
|
64
|
+
"stability_of_timeseries": ("_ratios", "stability_of_timeseries"),
|
|
65
|
+
"capture": ("_ratios", "capture"),
|
|
66
|
+
"up_capture": ("_ratios", "up_capture"),
|
|
67
|
+
"down_capture": ("_ratios", "down_capture"),
|
|
68
|
+
"up_down_capture": ("_ratios", "up_down_capture"),
|
|
69
|
+
"adjusted_sharpe_ratio": ("_ratios", "adjusted_sharpe_ratio"),
|
|
70
|
+
"conditional_sharpe_ratio": ("_ratios", "conditional_sharpe_ratio"),
|
|
71
|
+
# alpha_beta
|
|
72
|
+
"alpha": ("_alpha_beta", "alpha"),
|
|
73
|
+
"alpha_aligned": ("_alpha_beta", "alpha_aligned"),
|
|
74
|
+
"beta": ("_alpha_beta", "beta"),
|
|
75
|
+
"beta_aligned": ("_alpha_beta", "beta_aligned"),
|
|
76
|
+
"alpha_beta": ("_alpha_beta", "alpha_beta"),
|
|
77
|
+
"alpha_beta_aligned": ("_alpha_beta", "alpha_beta_aligned"),
|
|
78
|
+
"up_alpha_beta": ("_alpha_beta", "up_alpha_beta"),
|
|
79
|
+
"down_alpha_beta": ("_alpha_beta", "down_alpha_beta"),
|
|
80
|
+
"annual_alpha": ("_alpha_beta", "annual_alpha"),
|
|
81
|
+
"annual_beta": ("_alpha_beta", "annual_beta"),
|
|
82
|
+
"alpha_percentile_rank": ("_alpha_beta", "alpha_percentile_rank"),
|
|
83
|
+
# stats
|
|
84
|
+
"skewness": ("_stats", "skewness"),
|
|
85
|
+
"kurtosis": ("_stats", "kurtosis"),
|
|
86
|
+
"hurst_exponent": ("_stats", "hurst_exponent"),
|
|
87
|
+
"stutzer_index": ("_stats", "stutzer_index"),
|
|
88
|
+
"stock_market_correlation": ("_stats", "stock_market_correlation"),
|
|
89
|
+
"bond_market_correlation": ("_stats", "bond_market_correlation"),
|
|
90
|
+
"var_cov_var_normal": ("_stats", "var_cov_var_normal"),
|
|
91
|
+
# consecutive
|
|
92
|
+
"max_consecutive_up_days": ("_consecutive", "max_consecutive_up_days"),
|
|
93
|
+
"max_consecutive_down_days": ("_consecutive", "max_consecutive_down_days"),
|
|
94
|
+
"max_consecutive_gain": ("_consecutive", "max_consecutive_gain"),
|
|
95
|
+
"max_consecutive_loss": ("_consecutive", "max_consecutive_loss"),
|
|
96
|
+
"max_single_day_gain": ("_consecutive", "max_single_day_gain"),
|
|
97
|
+
"max_single_day_loss": ("_consecutive", "max_single_day_loss"),
|
|
98
|
+
# timing
|
|
99
|
+
"treynor_mazuy_timing": ("_timing", "treynor_mazuy_timing"),
|
|
100
|
+
"henriksson_merton_timing": ("_timing", "henriksson_merton_timing"),
|
|
101
|
+
"market_timing_return": ("_timing", "market_timing_return"),
|
|
102
|
+
"cornell_timing": ("_timing", "cornell_timing"),
|
|
103
|
+
# yearly
|
|
104
|
+
"annual_return": ("_yearly", "annual_return"),
|
|
105
|
+
"annual_return_by_year": ("_yearly", "annual_return_by_year"),
|
|
106
|
+
"sharpe_ratio_by_year": ("_yearly", "sharpe_ratio_by_year"),
|
|
107
|
+
"max_drawdown_by_year": ("_yearly", "max_drawdown_by_year"),
|
|
108
|
+
# rolling
|
|
109
|
+
"rolling_volatility": ("_rolling", "rolling_volatility"),
|
|
110
|
+
"rolling_sharpe": ("_rolling", "rolling_sharpe"),
|
|
111
|
+
"rolling_beta": ("_rolling", "rolling_beta"),
|
|
112
|
+
"rolling_regression": ("_rolling", "rolling_regression"),
|
|
113
|
+
# positions
|
|
114
|
+
"get_percent_alloc": ("_positions", "get_percent_alloc"),
|
|
115
|
+
"get_top_long_short_abs": ("_positions", "get_top_long_short_abs"),
|
|
116
|
+
"get_long_short_pos": ("_positions", "get_long_short_pos"),
|
|
117
|
+
"gross_lev": ("_positions", "gross_lev"),
|
|
118
|
+
"get_max_median_position_concentration": ("_positions", "get_max_median_position_concentration"),
|
|
119
|
+
"extract_pos": ("_positions", "extract_pos"),
|
|
120
|
+
"get_sector_exposures": ("_positions", "get_sector_exposures"),
|
|
121
|
+
"compute_style_factor_exposures": ("_positions", "compute_style_factor_exposures"),
|
|
122
|
+
"compute_sector_exposures": ("_positions", "compute_sector_exposures"),
|
|
123
|
+
"compute_cap_exposures": ("_positions", "compute_cap_exposures"),
|
|
124
|
+
"compute_volume_exposures": ("_positions", "compute_volume_exposures"),
|
|
125
|
+
"stack_positions": ("_positions", "stack_positions"),
|
|
126
|
+
# transactions
|
|
127
|
+
"get_txn_vol": ("_transactions", "get_txn_vol"),
|
|
128
|
+
"get_turnover": ("_transactions", "get_turnover"),
|
|
129
|
+
"make_transaction_frame": ("_transactions", "make_transaction_frame"),
|
|
130
|
+
"daily_txns_with_bar_data": ("_transactions", "daily_txns_with_bar_data"),
|
|
131
|
+
"days_to_liquidate_positions": ("_transactions", "days_to_liquidate_positions"),
|
|
132
|
+
"get_max_days_to_liquidate_by_ticker": ("_transactions", "get_max_days_to_liquidate_by_ticker"),
|
|
133
|
+
"get_low_liquidity_transactions": ("_transactions", "get_low_liquidity_transactions"),
|
|
134
|
+
"apply_slippage_penalty": ("_transactions", "apply_slippage_penalty"),
|
|
135
|
+
"map_transaction": ("_transactions", "map_transaction"),
|
|
136
|
+
"adjust_returns_for_slippage": ("_transactions", "adjust_returns_for_slippage"),
|
|
137
|
+
# round_trips
|
|
138
|
+
"extract_round_trips": ("_round_trips", "extract_round_trips"),
|
|
139
|
+
"gen_round_trip_stats": ("_round_trips", "gen_round_trip_stats"),
|
|
140
|
+
"agg_all_long_short": ("_round_trips", "agg_all_long_short"),
|
|
141
|
+
"add_closing_transactions": ("_round_trips", "add_closing_transactions"),
|
|
142
|
+
"apply_sector_mappings_to_round_trips": ("_round_trips", "apply_sector_mappings_to_round_trips"),
|
|
143
|
+
# perf_attrib
|
|
144
|
+
"compute_exposures": ("_perf_attrib", "compute_exposures"),
|
|
145
|
+
"create_perf_attrib_stats": ("_perf_attrib", "create_perf_attrib_stats"),
|
|
146
|
+
"_cumulative_returns_less_costs": ("_perf_attrib", "cumulative_returns_less_costs"),
|
|
147
|
+
# perf_stats
|
|
148
|
+
"perf_stats": ("_perf_stats", "perf_stats"),
|
|
149
|
+
"calc_bootstrap": ("_perf_stats", "calc_bootstrap"),
|
|
150
|
+
"perf_stats_bootstrap": ("_perf_stats", "perf_stats_bootstrap"),
|
|
151
|
+
"calc_distribution_stats": ("_perf_stats", "calc_distribution_stats"),
|
|
152
|
+
# bayesian
|
|
153
|
+
"model_returns_t_alpha_beta": ("_bayesian", "model_returns_t_alpha_beta"),
|
|
154
|
+
"model_returns_normal": ("_bayesian", "model_returns_normal"),
|
|
155
|
+
"model_returns_t": ("_bayesian", "model_returns_t"),
|
|
156
|
+
"model_best": ("_bayesian", "model_best"),
|
|
157
|
+
"model_stoch_vol": ("_bayesian", "model_stoch_vol"),
|
|
158
|
+
"compute_bayes_cone": ("_bayesian", "compute_bayes_cone"),
|
|
159
|
+
"compute_consistency_score": ("_bayesian", "compute_consistency_score"),
|
|
160
|
+
"run_model": ("_bayesian", "run_model"),
|
|
161
|
+
"simulate_paths": ("_bayesian", "simulate_paths"),
|
|
162
|
+
"summarize_paths": ("_bayesian", "summarize_paths"),
|
|
163
|
+
"forecast_cone_bootstrap": ("_bayesian", "forecast_cone_bootstrap"),
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
# ---------------------------------------------------------------------------
|
|
167
|
+
# Dual methods — auto-fill ``returns`` from instance state
|
|
168
|
+
# (method_name, module_alias, func_name)
|
|
169
|
+
# ---------------------------------------------------------------------------
|
|
170
|
+
DUAL_RETURNS_REGISTRY = {
|
|
171
|
+
"get_max_drawdown_period": ("_drawdown", "get_max_drawdown_period"),
|
|
172
|
+
"max_drawdown_days": ("_drawdown", "max_drawdown_days"),
|
|
173
|
+
"second_max_drawdown": ("_drawdown", "second_max_drawdown"),
|
|
174
|
+
"third_max_drawdown": ("_drawdown", "third_max_drawdown"),
|
|
175
|
+
"second_max_drawdown_days": ("_drawdown", "second_max_drawdown_days"),
|
|
176
|
+
"second_max_drawdown_recovery_days": ("_drawdown", "second_max_drawdown_recovery_days"),
|
|
177
|
+
"third_max_drawdown_days": ("_drawdown", "third_max_drawdown_days"),
|
|
178
|
+
"third_max_drawdown_recovery_days": ("_drawdown", "third_max_drawdown_recovery_days"),
|
|
179
|
+
"max_drawdown_weeks": ("_drawdown", "max_drawdown_weeks"),
|
|
180
|
+
"max_drawdown_months": ("_drawdown", "max_drawdown_months"),
|
|
181
|
+
"max_drawdown_recovery_days": ("_drawdown", "max_drawdown_recovery_days"),
|
|
182
|
+
"max_drawdown_recovery_weeks": ("_drawdown", "max_drawdown_recovery_weeks"),
|
|
183
|
+
"max_drawdown_recovery_months": ("_drawdown", "max_drawdown_recovery_months"),
|
|
184
|
+
"serial_correlation": ("_stats", "serial_correlation"),
|
|
185
|
+
"win_rate": ("_stats", "win_rate"),
|
|
186
|
+
"loss_rate": ("_stats", "loss_rate"),
|
|
187
|
+
"max_consecutive_up_weeks": ("_consecutive", "max_consecutive_up_weeks"),
|
|
188
|
+
"max_consecutive_down_weeks": ("_consecutive", "max_consecutive_down_weeks"),
|
|
189
|
+
"max_consecutive_up_months": ("_consecutive", "max_consecutive_up_months"),
|
|
190
|
+
"max_consecutive_down_months": ("_consecutive", "max_consecutive_down_months"),
|
|
191
|
+
"max_single_day_gain_date": ("_consecutive", "max_single_day_gain_date"),
|
|
192
|
+
"max_single_day_loss_date": ("_consecutive", "max_single_day_loss_date"),
|
|
193
|
+
"max_consecutive_up_start_date": ("_consecutive", "max_consecutive_up_start_date"),
|
|
194
|
+
"max_consecutive_up_end_date": ("_consecutive", "max_consecutive_up_end_date"),
|
|
195
|
+
"max_consecutive_down_start_date": ("_consecutive", "max_consecutive_down_start_date"),
|
|
196
|
+
"max_consecutive_down_end_date": ("_consecutive", "max_consecutive_down_end_date"),
|
|
197
|
+
"extract_interesting_date_ranges": ("_timing", "extract_interesting_date_ranges"),
|
|
198
|
+
"common_sense_ratio": ("_ratios", "common_sense_ratio"),
|
|
199
|
+
"gpd_risk_estimates": ("_risk", "gpd_risk_estimates"),
|
|
200
|
+
"gpd_risk_estimates_aligned": ("_risk", "gpd_risk_estimates_aligned"),
|
|
201
|
+
"var_excess_return": ("_risk", "var_excess_return"),
|
|
202
|
+
"annualized_cumulative_return": ("_yearly", "annual_return"),
|
|
203
|
+
"roll_sharpe_ratio": ("_rolling", "roll_sharpe_ratio"),
|
|
204
|
+
"roll_max_drawdown": ("_rolling", "roll_max_drawdown"),
|
|
205
|
+
"sterling_ratio": ("_ratios", "sterling_ratio"),
|
|
206
|
+
"burke_ratio": ("_ratios", "burke_ratio"),
|
|
207
|
+
"kappa_three_ratio": ("_ratios", "kappa_three_ratio"),
|
|
208
|
+
"annual_volatility_by_year": ("_yearly", "annual_volatility_by_year"),
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
# ---------------------------------------------------------------------------
|
|
212
|
+
# Dual methods — auto-fill ``returns`` AND ``factor_returns`` from instance
|
|
213
|
+
# (method_name, module_alias, func_name)
|
|
214
|
+
# ---------------------------------------------------------------------------
|
|
215
|
+
DUAL_RETURNS_FACTOR_REGISTRY = {
|
|
216
|
+
"futures_market_correlation": ("_stats", "futures_market_correlation"),
|
|
217
|
+
"r_cubed": ("_stats", "r_cubed"),
|
|
218
|
+
"tracking_difference": ("_stats", "tracking_difference"),
|
|
219
|
+
"beta_fragility_heuristic": ("_risk", "beta_fragility_heuristic"),
|
|
220
|
+
"beta_fragility_heuristic_aligned": ("_risk", "beta_fragility_heuristic_aligned"),
|
|
221
|
+
"treynor_ratio": ("_ratios", "treynor_ratio"),
|
|
222
|
+
"m_squared": ("_ratios", "m_squared"),
|
|
223
|
+
"residual_risk": ("_risk", "residual_risk"),
|
|
224
|
+
"roll_alpha": ("_rolling", "roll_alpha"),
|
|
225
|
+
"roll_beta": ("_rolling", "roll_beta"),
|
|
226
|
+
"roll_alpha_beta": ("_rolling", "roll_alpha_beta"),
|
|
227
|
+
"roll_up_capture": ("_rolling", "roll_up_capture"),
|
|
228
|
+
"roll_down_capture": ("_rolling", "roll_down_capture"),
|
|
229
|
+
"roll_up_down_capture": ("_rolling", "roll_up_down_capture"),
|
|
230
|
+
"annual_active_return": ("_yearly", "annual_active_return"),
|
|
231
|
+
"annual_active_return_by_year": ("_yearly", "annual_active_return_by_year"),
|
|
232
|
+
"information_ratio_by_year": ("_yearly", "information_ratio_by_year"),
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
# ---------------------------------------------------------------------------
|
|
236
|
+
# Module alias → fully qualified module path
|
|
237
|
+
# ---------------------------------------------------------------------------
|
|
238
|
+
MODULE_PATHS = {
|
|
239
|
+
"_basic": "fincore.metrics.basic",
|
|
240
|
+
"_returns": "fincore.metrics.returns",
|
|
241
|
+
"_drawdown": "fincore.metrics.drawdown",
|
|
242
|
+
"_risk": "fincore.metrics.risk",
|
|
243
|
+
"_ratios": "fincore.metrics.ratios",
|
|
244
|
+
"_alpha_beta": "fincore.metrics.alpha_beta",
|
|
245
|
+
"_stats": "fincore.metrics.stats",
|
|
246
|
+
"_consecutive": "fincore.metrics.consecutive",
|
|
247
|
+
"_rolling": "fincore.metrics.rolling",
|
|
248
|
+
"_bayesian": "fincore.metrics.bayesian",
|
|
249
|
+
"_positions": "fincore.metrics.positions",
|
|
250
|
+
"_transactions": "fincore.metrics.transactions",
|
|
251
|
+
"_round_trips": "fincore.metrics.round_trips",
|
|
252
|
+
"_perf_attrib": "fincore.metrics.perf_attrib",
|
|
253
|
+
"_perf_stats": "fincore.metrics.perf_stats",
|
|
254
|
+
"_timing": "fincore.metrics.timing",
|
|
255
|
+
"_yearly": "fincore.metrics.yearly",
|
|
256
|
+
}
|
fincore/_types.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Type definitions for fincore.
|
|
2
|
+
|
|
3
|
+
Provides type aliases and structured return types used across the library.
|
|
4
|
+
All NamedTuple types are backward-compatible with plain tuple unpacking.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from typing import NamedTuple, Optional, Union
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
import pandas as pd
|
|
14
|
+
|
|
15
|
+
# ---------------------------------------------------------------------------
|
|
16
|
+
# Input type aliases
|
|
17
|
+
# ---------------------------------------------------------------------------
|
|
18
|
+
ArrayLike = Union[pd.Series, np.ndarray, Sequence[float]]
|
|
19
|
+
ReturnSeries = Union[pd.Series, np.ndarray]
|
|
20
|
+
ReturnOrDataFrame = Union[pd.Series, pd.DataFrame, np.ndarray]
|
|
21
|
+
|
|
22
|
+
# ---------------------------------------------------------------------------
|
|
23
|
+
# Structured return types (backward-compatible with tuple unpacking)
|
|
24
|
+
# ---------------------------------------------------------------------------
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class DrawdownPeriod(NamedTuple):
|
|
28
|
+
"""A single drawdown period with peak, valley and optional recovery."""
|
|
29
|
+
|
|
30
|
+
peak: pd.Timestamp
|
|
31
|
+
valley: pd.Timestamp
|
|
32
|
+
recovery: pd.Timestamp | None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class AlphaBeta(NamedTuple):
|
|
36
|
+
"""Alpha and beta from a regression of returns on a factor."""
|
|
37
|
+
|
|
38
|
+
alpha: float
|
|
39
|
+
beta: float
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class BootstrapResult(NamedTuple):
|
|
43
|
+
"""Result of a bootstrap analysis."""
|
|
44
|
+
|
|
45
|
+
samples: np.ndarray
|
|
46
|
+
mean: float
|
|
47
|
+
median: float
|
|
48
|
+
ci_lower: float
|
|
49
|
+
ci_upper: float
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# ---------------------------------------------------------------------------
|
|
53
|
+
# Constant type aliases
|
|
54
|
+
# ---------------------------------------------------------------------------
|
|
55
|
+
Period = str # 'daily', 'weekly', 'monthly', 'yearly'
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Top-level constants exposed by fincore."""
|
|
2
|
+
|
|
3
|
+
from .color import COLORMAP, COLORS
|
|
4
|
+
from .interesting_periods import PERIODS
|
|
5
|
+
from .periods import (
|
|
6
|
+
ANNUALIZATION_FACTORS,
|
|
7
|
+
APPROX_BDAYS_PER_MONTH,
|
|
8
|
+
APPROX_BDAYS_PER_YEAR,
|
|
9
|
+
DAILY,
|
|
10
|
+
MONTHLY,
|
|
11
|
+
MONTHS_PER_YEAR,
|
|
12
|
+
PERIOD_TO_FREQ,
|
|
13
|
+
QTRS_PER_YEAR,
|
|
14
|
+
QUARTERLY,
|
|
15
|
+
WEEKLY,
|
|
16
|
+
WEEKS_PER_YEAR,
|
|
17
|
+
YEARLY,
|
|
18
|
+
)
|
|
19
|
+
from .style import (
|
|
20
|
+
CAP_BUCKETS,
|
|
21
|
+
DURATION_STATS,
|
|
22
|
+
FACTOR_PARTITIONS,
|
|
23
|
+
FACTOR_STAT_FUNCS,
|
|
24
|
+
MM_DISPLAY_UNIT,
|
|
25
|
+
PERF_ATTRIB_TURNOVER_THRESHOLD,
|
|
26
|
+
PNL_STATS,
|
|
27
|
+
RETURN_STATS,
|
|
28
|
+
SECTORS,
|
|
29
|
+
SIMPLE_STAT_FUNCS,
|
|
30
|
+
STAT_FUNC_NAMES,
|
|
31
|
+
STAT_FUNCS_PCT,
|
|
32
|
+
SUMMARY_STATS,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
# periods
|
|
37
|
+
"APPROX_BDAYS_PER_MONTH",
|
|
38
|
+
"APPROX_BDAYS_PER_YEAR",
|
|
39
|
+
"MONTHS_PER_YEAR",
|
|
40
|
+
"WEEKS_PER_YEAR",
|
|
41
|
+
"QTRS_PER_YEAR",
|
|
42
|
+
"DAILY",
|
|
43
|
+
"WEEKLY",
|
|
44
|
+
"MONTHLY",
|
|
45
|
+
"QUARTERLY",
|
|
46
|
+
"YEARLY",
|
|
47
|
+
"ANNUALIZATION_FACTORS",
|
|
48
|
+
"PERIOD_TO_FREQ",
|
|
49
|
+
# interesting_periods
|
|
50
|
+
"PERIODS",
|
|
51
|
+
# style
|
|
52
|
+
"PERF_ATTRIB_TURNOVER_THRESHOLD",
|
|
53
|
+
"SECTORS",
|
|
54
|
+
"CAP_BUCKETS",
|
|
55
|
+
"SIMPLE_STAT_FUNCS",
|
|
56
|
+
"FACTOR_STAT_FUNCS",
|
|
57
|
+
"STAT_FUNC_NAMES",
|
|
58
|
+
"FACTOR_PARTITIONS",
|
|
59
|
+
"STAT_FUNCS_PCT",
|
|
60
|
+
"PNL_STATS",
|
|
61
|
+
"SUMMARY_STATS",
|
|
62
|
+
"RETURN_STATS",
|
|
63
|
+
"DURATION_STATS",
|
|
64
|
+
"MM_DISPLAY_UNIT",
|
|
65
|
+
# color
|
|
66
|
+
"COLORMAP",
|
|
67
|
+
"COLORS",
|
|
68
|
+
]
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
COLORMAP = "Paired"
|
|
2
|
+
COLORS = [
|
|
3
|
+
"#e6194b",
|
|
4
|
+
"#3cb44b",
|
|
5
|
+
"#ffe119",
|
|
6
|
+
"#0082c8",
|
|
7
|
+
"#f58231",
|
|
8
|
+
"#911eb4",
|
|
9
|
+
"#46f0f0",
|
|
10
|
+
"#f032e6",
|
|
11
|
+
"#d2f53c",
|
|
12
|
+
"#fabebe",
|
|
13
|
+
"#008080",
|
|
14
|
+
"#e6beff",
|
|
15
|
+
"#aa6e28",
|
|
16
|
+
"#800000",
|
|
17
|
+
"#aaffc3",
|
|
18
|
+
"#808000",
|
|
19
|
+
"#ffd8b1",
|
|
20
|
+
"#000080",
|
|
21
|
+
"#808080",
|
|
22
|
+
]
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# Copyright 2016 Quantopian, Inc.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Generates a list of historical event dates that may have had
|
|
16
|
+
significant impact on markets. See extract_interesting_date_ranges."""
|
|
17
|
+
|
|
18
|
+
from collections import OrderedDict
|
|
19
|
+
|
|
20
|
+
import pandas as pd
|
|
21
|
+
|
|
22
|
+
PERIODS = OrderedDict()
|
|
23
|
+
# Dotcom bubble
|
|
24
|
+
PERIODS["Dotcom"] = (pd.Timestamp("20000310"), pd.Timestamp("20000910"))
|
|
25
|
+
|
|
26
|
+
# Lehman Brothers
|
|
27
|
+
PERIODS["Lehman"] = (pd.Timestamp("20080801"), pd.Timestamp("20081001"))
|
|
28
|
+
|
|
29
|
+
# 9/11
|
|
30
|
+
PERIODS["9/11"] = (pd.Timestamp("20010911"), pd.Timestamp("20011011"))
|
|
31
|
+
|
|
32
|
+
# 05/08/11 US down grade and European Debt Crisis 2011
|
|
33
|
+
PERIODS["US downgrade/European Debt Crisis"] = (pd.Timestamp("20110805"), pd.Timestamp("20110905"))
|
|
34
|
+
|
|
35
|
+
# 16/03/11 Fukushima melt down 2011
|
|
36
|
+
PERIODS["Fukushima"] = (pd.Timestamp("20110316"), pd.Timestamp("20110416"))
|
|
37
|
+
|
|
38
|
+
# 01/08/03 US Housing Bubble 2003
|
|
39
|
+
PERIODS["US Housing"] = (pd.Timestamp("20030108"), pd.Timestamp("20030208"))
|
|
40
|
+
|
|
41
|
+
# 06/09/12 EZB IR Event 2012
|
|
42
|
+
PERIODS["EZB IR Event"] = (pd.Timestamp("20120910"), pd.Timestamp("20121010"))
|
|
43
|
+
|
|
44
|
+
# August 2007, March and September 2008, Q1 & Q2 2009,
|
|
45
|
+
PERIODS["Aug07"] = (pd.Timestamp("20070801"), pd.Timestamp("20070901"))
|
|
46
|
+
PERIODS["Mar08"] = (pd.Timestamp("20080301"), pd.Timestamp("20080401"))
|
|
47
|
+
PERIODS["Sept08"] = (pd.Timestamp("20080901"), pd.Timestamp("20081001"))
|
|
48
|
+
PERIODS["2009Q1"] = (pd.Timestamp("20090101"), pd.Timestamp("20090301"))
|
|
49
|
+
PERIODS["2009Q2"] = (pd.Timestamp("20090301"), pd.Timestamp("20090601"))
|
|
50
|
+
|
|
51
|
+
# Flash Crash (May 6, 2010 + 1-week post),
|
|
52
|
+
PERIODS["Flash Crash"] = (pd.Timestamp("20100505"), pd.Timestamp("20100510"))
|
|
53
|
+
|
|
54
|
+
# April and October 2014
|
|
55
|
+
PERIODS["Apr14"] = (pd.Timestamp("20140401"), pd.Timestamp("20140501"))
|
|
56
|
+
PERIODS["Oct14"] = (pd.Timestamp("20141001"), pd.Timestamp("20141101"))
|
|
57
|
+
|
|
58
|
+
# Market down-turn in August/Sept 2015
|
|
59
|
+
PERIODS["Fall2015"] = (pd.Timestamp("20150815"), pd.Timestamp("20150930"))
|
|
60
|
+
|
|
61
|
+
# Market regimes
|
|
62
|
+
PERIODS["Low Volatility Bull Market"] = (pd.Timestamp("20050101"), pd.Timestamp("20070801"))
|
|
63
|
+
|
|
64
|
+
PERIODS["GFC Crash"] = (pd.Timestamp("20070801"), pd.Timestamp("20090401"))
|
|
65
|
+
|
|
66
|
+
PERIODS["Recovery"] = (pd.Timestamp("20090401"), pd.Timestamp("20130101"))
|
|
67
|
+
|
|
68
|
+
PERIODS["New Normal"] = (pd.Timestamp("20130101"), pd.Timestamp("20251231"))
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Project-wide period constants and annualization factors."""
|
|
2
|
+
|
|
3
|
+
import pandas as pd
|
|
4
|
+
from packaging import version as _pkg_version
|
|
5
|
+
|
|
6
|
+
APPROX_BDAYS_PER_MONTH = 21
|
|
7
|
+
APPROX_BDAYS_PER_YEAR = 252
|
|
8
|
+
|
|
9
|
+
MONTHS_PER_YEAR = 12
|
|
10
|
+
WEEKS_PER_YEAR = 52
|
|
11
|
+
QTRS_PER_YEAR = 4
|
|
12
|
+
|
|
13
|
+
DAILY = "daily"
|
|
14
|
+
WEEKLY = "weekly"
|
|
15
|
+
MONTHLY = "monthly"
|
|
16
|
+
QUARTERLY = "quarterly"
|
|
17
|
+
YEARLY = "yearly"
|
|
18
|
+
|
|
19
|
+
ANNUALIZATION_FACTORS = {
|
|
20
|
+
DAILY: APPROX_BDAYS_PER_YEAR,
|
|
21
|
+
WEEKLY: WEEKS_PER_YEAR,
|
|
22
|
+
MONTHLY: MONTHS_PER_YEAR,
|
|
23
|
+
QUARTERLY: QTRS_PER_YEAR,
|
|
24
|
+
YEARLY: 1,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# Period to frequency mapping (version-aware for pandas 2.2+)
|
|
29
|
+
if _pkg_version.parse(pd.__version__) >= _pkg_version.parse("2.2.0"):
|
|
30
|
+
PERIOD_TO_FREQ = {
|
|
31
|
+
DAILY: "D",
|
|
32
|
+
WEEKLY: "W",
|
|
33
|
+
MONTHLY: "ME",
|
|
34
|
+
QUARTERLY: "QE",
|
|
35
|
+
YEARLY: "YE",
|
|
36
|
+
}
|
|
37
|
+
else:
|
|
38
|
+
PERIOD_TO_FREQ = {
|
|
39
|
+
DAILY: "D",
|
|
40
|
+
WEEKLY: "W",
|
|
41
|
+
MONTHLY: "M",
|
|
42
|
+
QUARTERLY: "Q",
|
|
43
|
+
YEARLY: "A",
|
|
44
|
+
}
|