AssayingAnomalies 0.9.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.
Files changed (69) hide show
  1. assayinganomalies/__init__.py +172 -0
  2. assayinganomalies/analytics/__init__.py +137 -0
  3. assayinganomalies/analytics/anomaly_decay.py +255 -0
  4. assayinganomalies/analytics/costs.py +436 -0
  5. assayinganomalies/analytics/gen_alpha.py +768 -0
  6. assayinganomalies/analytics/held.py +924 -0
  7. assayinganomalies/analytics/ols.py +76 -0
  8. assayinganomalies/analytics/plots.py +83 -0
  9. assayinganomalies/analytics/protocol.py +1806 -0
  10. assayinganomalies/analytics/regressions.py +723 -0
  11. assayinganomalies/analytics/res_to_print.py +1613 -0
  12. assayinganomalies/analytics/results.py +5987 -0
  13. assayinganomalies/analytics/sorts.py +2918 -0
  14. assayinganomalies/analytics/subsamples.py +80 -0
  15. assayinganomalies/cli.py +800 -0
  16. assayinganomalies/client.py +48 -0
  17. assayinganomalies/compustat_extras.py +390 -0
  18. assayinganomalies/config.py +1073 -0
  19. assayinganomalies/data_access.py +603 -0
  20. assayinganomalies/db/__init__.py +9 -0
  21. assayinganomalies/db/cache.py +38 -0
  22. assayinganomalies/db/manager.py +47 -0
  23. assayinganomalies/db/migrations.py +62 -0
  24. assayinganomalies/db/reader.py +123 -0
  25. assayinganomalies/db/writer.py +111 -0
  26. assayinganomalies/ingest/__init__.py +11 -0
  27. assayinganomalies/ingest/compustat.py +592 -0
  28. assayinganomalies/ingest/crsp.py +123 -0
  29. assayinganomalies/ingest/crsp_daily.py +616 -0
  30. assayinganomalies/ingest/crsp_source.py +935 -0
  31. assayinganomalies/ingest/cz_anomalies.py +1091 -0
  32. assayinganomalies/ingest/cz_release.py +651 -0
  33. assayinganomalies/ingest/data/compustat_variables.csv +83 -0
  34. assayinganomalies/ingest/ff_factors.py +136 -0
  35. assayinganomalies/ingest/gibbs.py +268 -0
  36. assayinganomalies/ingest/ken_french.py +77 -0
  37. assayinganomalies/ingest/sample_end.py +147 -0
  38. assayinganomalies/ingest/wrds_client.py +401 -0
  39. assayinganomalies/logging_utils.py +40 -0
  40. assayinganomalies/ops.py +26 -0
  41. assayinganomalies/pipeline.py +3557 -0
  42. assayinganomalies/plotting.py +96 -0
  43. assayinganomalies/provenance.py +305 -0
  44. assayinganomalies/py.typed +2 -0
  45. assayinganomalies/reporting/__init__.py +56 -0
  46. assayinganomalies/reporting/bib/newSignalTestBib.bib +136 -0
  47. assayinganomalies/reporting/figures.py +865 -0
  48. assayinganomalies/reporting/latex.py +1723 -0
  49. assayinganomalies/reporting/tables.py +1129 -0
  50. assayinganomalies/run_manifest.py +749 -0
  51. assayinganomalies/session_cache.py +312 -0
  52. assayinganomalies/signal_io.py +339 -0
  53. assayinganomalies/signal_tester.py +47 -0
  54. assayinganomalies/stage_registry.py +360 -0
  55. assayinganomalies/tiebreak.py +36 -0
  56. assayinganomalies/transforms/__init__.py +20 -0
  57. assayinganomalies/transforms/anomaly_fill.py +141 -0
  58. assayinganomalies/transforms/betas.py +1283 -0
  59. assayinganomalies/transforms/compustat.py +1719 -0
  60. assayinganomalies/transforms/crsp_daily.py +1221 -0
  61. assayinganomalies/transforms/crsp_monthly.py +1118 -0
  62. assayinganomalies/transforms/nmv_anomalies.py +842 -0
  63. assayinganomalies/transforms/tcosts.py +1880 -0
  64. assayinganomalies-0.9.0.dist-info/METADATA +596 -0
  65. assayinganomalies-0.9.0.dist-info/RECORD +69 -0
  66. assayinganomalies-0.9.0.dist-info/WHEEL +5 -0
  67. assayinganomalies-0.9.0.dist-info/entry_points.txt +2 -0
  68. assayinganomalies-0.9.0.dist-info/licenses/LICENSE +23 -0
  69. assayinganomalies-0.9.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,172 @@
1
+ """
2
+ Public entry points for the Assaying Anomalies Python toolkit.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from importlib import metadata as _metadata
8
+ from pathlib import Path
9
+ from typing import Iterable, Mapping
10
+
11
+ # The installed distribution's version (pyproject.toml is the one place it is
12
+ # written). "unknown" when the package is imported from a source tree that was
13
+ # never installed; run manifests record the same string (run_manifest.UNKNOWN).
14
+ try:
15
+ __version__ = _metadata.version("assayinganomalies")
16
+ except _metadata.PackageNotFoundError: # pragma: no cover - uninstalled source tree
17
+ __version__ = "unknown"
18
+
19
+ # First, and on purpose: importing .plotting pins matplotlib to Agg before
20
+ # anything below can pull in pyplot. Nothing here wants an
21
+ # interactive window, and choosing a GUI backend on a headless node is at best
22
+ # a warning. MPLBACKEND remains the escape hatch.
23
+ from .plotting import maybe_show, use_headless_backend
24
+ from .client import AssayClient
25
+ from .config import (
26
+ AssayConfig,
27
+ load_config,
28
+ save_config,
29
+ set_params,
30
+ set_project_dir,
31
+ resolve_project_dir,
32
+ resolve_protocol_n_jobs,
33
+ default_protocol_n_jobs,
34
+ )
35
+ from .data_access import (
36
+ AnnualLayoutError,
37
+ load,
38
+ load_cz_anomalies,
39
+ load_nmv_anomalies,
40
+ list_cz_signals,
41
+ get_cz_signal_info,
42
+ describe_cz_signal,
43
+ )
44
+ from .analytics import (
45
+ calc_held_ptfs,
46
+ calc_ptf_rets,
47
+ calc_tcosts,
48
+ est_factor_regs,
49
+ fill_months,
50
+ held_legs,
51
+ held_long_short,
52
+ held_composite_long_short,
53
+ ibbots,
54
+ load_factors,
55
+ make_ff_tcosts,
56
+ moving,
57
+ nanols,
58
+ plot_anomaly_decay,
59
+ prt,
60
+ run_anomaly_decay,
61
+ run_bivariate_sort,
62
+ run_fama_macbeth,
63
+ run_univariate_sort,
64
+ )
65
+ from .ingest import load_ff25
66
+ from .transforms import (
67
+ CCM_LINK_COLUMNS,
68
+ check_fill_anomalies,
69
+ clean_ccm_link,
70
+ fill_var,
71
+ merge_on_link,
72
+ )
73
+ from .ops import log
74
+ from .pipeline import setup_database
75
+ from .compustat_extras import add_compustat_vars
76
+ from .session_cache import cache_info, clear_session_cache
77
+ from .analytics.protocol import FactorCostsError, ProtocolResult, run_test_signal, test_signal
78
+ from .analytics.res_to_print import PrintResults, make_res_to_print
79
+ from .signal_io import (
80
+ default_mpe_signal_info,
81
+ get_anomaly_signals,
82
+ get_signal_info,
83
+ load_signal_csv,
84
+ )
85
+ from .signal_tester import SignalInfo, SignalTester
86
+ from .reporting import print_tex_file, semantic_tex_diff
87
+
88
+ __all__ = [
89
+ "__version__",
90
+ "maybe_show",
91
+ "use_headless_backend",
92
+ "AssayClient",
93
+ "AssayConfig",
94
+ "SignalTester",
95
+ "SignalInfo",
96
+ "ProtocolResult",
97
+ "PrintResults",
98
+ "run_test_signal",
99
+ "test_signal",
100
+ "make_res_to_print",
101
+ "print_tex_file",
102
+ "semantic_tex_diff",
103
+ "get_anomaly_signals",
104
+ "load_signal_csv",
105
+ "get_signal_info",
106
+ "default_mpe_signal_info",
107
+ "log",
108
+ "AnnualLayoutError",
109
+ "FactorCostsError",
110
+ "load",
111
+ "load_cz_anomalies",
112
+ "load_nmv_anomalies",
113
+ "list_cz_signals",
114
+ "get_cz_signal_info",
115
+ "describe_cz_signal",
116
+ "load_config",
117
+ "save_config",
118
+ "set_params",
119
+ "set_project_dir",
120
+ "resolve_project_dir",
121
+ "resolve_protocol_n_jobs",
122
+ "default_protocol_n_jobs",
123
+ "setup_database",
124
+ "add_compustat_vars",
125
+ "clear_session_cache",
126
+ "cache_info",
127
+ "run_univariate_sort",
128
+ "run_bivariate_sort",
129
+ "run_fama_macbeth",
130
+ "load_factors",
131
+ "calc_ptf_rets",
132
+ "calc_held_ptfs",
133
+ "fill_months",
134
+ "held_legs",
135
+ "held_long_short",
136
+ "held_composite_long_short",
137
+ "est_factor_regs",
138
+ "calc_tcosts",
139
+ "make_ff_tcosts",
140
+ "nanols",
141
+ "prt",
142
+ "ibbots",
143
+ "moving",
144
+ "fill_var",
145
+ "check_fill_anomalies",
146
+ "CCM_LINK_COLUMNS",
147
+ "clean_ccm_link",
148
+ "merge_on_link",
149
+ "load_ff25",
150
+ "run_anomaly_decay",
151
+ "plot_anomaly_decay",
152
+ ]
153
+
154
+
155
+ def set_params_cli(**kwargs: object) -> AssayConfig:
156
+ """
157
+ Convenience wrapper used by the CLI to update parameters.
158
+ """
159
+ return set_params(**kwargs)
160
+
161
+
162
+ def load_fields(
163
+ fields: Iterable[str] | Mapping[str, str],
164
+ *,
165
+ path: str | Path | None = None,
166
+ **kwargs: object,
167
+ ):
168
+ """
169
+ Thin wrapper around :func:`load` for parity with MATLAB-style scripts.
170
+ """
171
+ return load(path=path, fields=fields, **kwargs)
172
+
@@ -0,0 +1,137 @@
1
+ """
2
+ Analytical routines for the Assaying Anomalies toolkit.
3
+ """
4
+
5
+ from .sorts import (
6
+ BivariateSortResult,
7
+ HeldSort,
8
+ SortResult,
9
+ calc_held_ptfs,
10
+ calc_ptf_rets,
11
+ est_factor_regs,
12
+ fill_months,
13
+ load_factors,
14
+ run_bivariate_sort,
15
+ run_univariate_sort,
16
+ )
17
+ from .anomaly_decay import plot_anomaly_decay, run_anomaly_decay
18
+ from .costs import calc_tcosts, make_ff_tcosts
19
+ from .held import (
20
+ HeldCompositeLongShort,
21
+ HeldLegs,
22
+ HeldLongShort,
23
+ held_composite_long_short,
24
+ held_legs,
25
+ held_long_short,
26
+ )
27
+ from .gen_alpha import calc_gen_alpha, calc_mve, calc_net_mve
28
+ from .ols import OlsRes, nanols, prt
29
+ from .plots import ibbots, moving
30
+ from .regressions import run_fama_macbeth
31
+ from .protocol import ProtocolResult, run_test_signal, test_signal
32
+ from .results import (
33
+ BASIC_SORT_LABELS,
34
+ COMB_STRAT_DISPLAY_LABELS,
35
+ COMB_STRAT_EXPLANATIONS,
36
+ COMB_STRAT_LABELS,
37
+ FACTOR_MODELS,
38
+ AnomBenchmarkResults,
39
+ AnomStratResults,
40
+ BasicSortsResults,
41
+ CloseAnomResult,
42
+ CloseAnomResults,
43
+ CombStratResult,
44
+ CombStratsResults,
45
+ DendrogramResults,
46
+ AnomalyScreenError,
47
+ DendrogramSignalError,
48
+ FMBRes,
49
+ IPCARes,
50
+ LassoRes,
51
+ PLSRes,
52
+ make_anom_benchmark_results,
53
+ make_anom_strat_results,
54
+ make_avg_rank,
55
+ make_basic_sorts_results,
56
+ make_close_anom_results,
57
+ make_comb_strats,
58
+ dendrogram_signal_window,
59
+ make_dendrogram_results,
60
+ make_fmb_res,
61
+ make_ipca_res,
62
+ make_lasso_res,
63
+ make_pls_res,
64
+ make_weighted_avg_rank,
65
+ )
66
+ from .res_to_print import PrintResults, PrintText, make_res_to_print
67
+
68
+ __all__ = [
69
+ "run_univariate_sort",
70
+ "run_bivariate_sort",
71
+ "run_fama_macbeth",
72
+ "run_test_signal",
73
+ "test_signal",
74
+ "ProtocolResult",
75
+ "PrintResults",
76
+ "PrintText",
77
+ "make_res_to_print",
78
+ "SortResult",
79
+ "BivariateSortResult",
80
+ "calc_ptf_rets",
81
+ "calc_held_ptfs",
82
+ "fill_months",
83
+ "HeldSort",
84
+ "held_legs",
85
+ "held_long_short",
86
+ "held_composite_long_short",
87
+ "HeldCompositeLongShort",
88
+ "HeldLegs",
89
+ "HeldLongShort",
90
+ "est_factor_regs",
91
+ "load_factors",
92
+ "calc_tcosts",
93
+ "make_ff_tcosts",
94
+ "calc_mve",
95
+ "calc_net_mve",
96
+ "calc_gen_alpha",
97
+ "OlsRes",
98
+ "nanols",
99
+ "prt",
100
+ "ibbots",
101
+ "moving",
102
+ "run_anomaly_decay",
103
+ "plot_anomaly_decay",
104
+ "make_basic_sorts_results",
105
+ "make_anom_benchmark_results",
106
+ "make_anom_strat_results",
107
+ "make_avg_rank",
108
+ "make_weighted_avg_rank",
109
+ "make_fmb_res",
110
+ "make_lasso_res",
111
+ "make_pls_res",
112
+ "make_ipca_res",
113
+ "make_close_anom_results",
114
+ "make_dendrogram_results",
115
+ "make_comb_strats",
116
+ "BasicSortsResults",
117
+ "AnomBenchmarkResults",
118
+ "AnomStratResults",
119
+ "FMBRes",
120
+ "LassoRes",
121
+ "PLSRes",
122
+ "IPCARes",
123
+ "CloseAnomResult",
124
+ "CloseAnomResults",
125
+ "DendrogramResults",
126
+ "AnomalyScreenError",
127
+ "DendrogramSignalError",
128
+ "dendrogram_signal_window",
129
+ "CombStratResult",
130
+ "CombStratsResults",
131
+ "BASIC_SORT_LABELS",
132
+ "FACTOR_MODELS",
133
+ "COMB_STRAT_LABELS",
134
+ "COMB_STRAT_DISPLAY_LABELS",
135
+ "COMB_STRAT_EXPLANATIONS",
136
+ ]
137
+
@@ -0,0 +1,255 @@
1
+ """
2
+ Anomaly-decay analysis (McLean and Pontiff, 2016; Chen and Velikov, 2022).
3
+
4
+ Python port of the anomaly-decay loop in ``use_library.m`` section 11: run
5
+ each documented Chen-Zimmerman signal through its own rebalancing frequency,
6
+ screens, sample window and weighting, then line the long/short strategies up
7
+ on their publication dates.
8
+
9
+ All sorts are expressed on :func:`run_univariate_sort`:
10
+
11
+ - quantile strategies keep only the extreme legs via percentile ``n_bins``
12
+ (e.g. deciles -> ``[10, 90]``: the long/short return is the top bin minus
13
+ the bottom bin and the inert middle bin does not affect either leg);
14
+ - categorical strategies (discrete signals, zero-vs-positive splits) map the
15
+ legs onto a synthetic {1, 2} signal sorted with a breakpoint filter pinned
16
+ to the long leg, which places the breakpoint at exactly 2.0;
17
+ - the ``me > me_nyse20`` screen drops stocks in the bottom quintile of a
18
+ NYSE-break size sort (MATLAB ``makeUnivSortInd(me, 5, NYSE) == 1``).
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import time
24
+ from typing import Any
25
+
26
+ import numpy as np
27
+ import pandas as pd
28
+
29
+ from .sorts import (
30
+ SortResult,
31
+ _bin_by_cross_section,
32
+ _to_month_end,
33
+ run_univariate_sort,
34
+ )
35
+
36
+ __all__ = ["run_anomaly_decay", "plot_anomaly_decay"]
37
+
38
+
39
+ def _two_leg_sort(
40
+ returns: pd.Series,
41
+ leg: pd.Series,
42
+ mcap: pd.Series,
43
+ *,
44
+ weighting: str,
45
+ time_period: Any,
46
+ ) -> SortResult:
47
+ """Sort on a synthetic {1, 2} leg signal (1 = short, 2 = long, NaN = out).
48
+
49
+ Uses ``breaks='nyse'`` with the flag pinned to the long leg so the single
50
+ breakpoint is exactly 2.0: bin 1 collects the 1s, bin 2 the 2s.
51
+ """
52
+ return run_univariate_sort(
53
+ returns=returns,
54
+ signal=leg,
55
+ mcap=mcap,
56
+ n_bins=2,
57
+ breaks="nyse",
58
+ nyse_flag=(leg == 2),
59
+ weighting=weighting,
60
+ time_period=time_period,
61
+ factor_model=4,
62
+ )
63
+
64
+
65
+ def run_anomaly_decay(
66
+ anoms_panel: pd.DataFrame,
67
+ summary: pd.DataFrame,
68
+ *,
69
+ returns: pd.Series,
70
+ mcap: pd.Series,
71
+ prc: pd.Series | None = None,
72
+ exchcd: pd.Series | None = None,
73
+ nyse_flag: pd.Series | None = None,
74
+ verbose: bool = True,
75
+ ) -> dict[str, SortResult]:
76
+ """Port of the MATLAB anomaly-decay loop over the Chen-Zimmerman signals.
77
+
78
+ Parameters
79
+ ----------
80
+ anoms_panel : pd.DataFrame
81
+ (date, permno)-indexed panel with one column per anomaly signal.
82
+ summary : pd.DataFrame
83
+ Chen-Zimmerman signal documentation (``aa.get_cz_signal_info()``);
84
+ matched on lowercase ``acronym``.
85
+ returns, mcap : pd.Series
86
+ Stock returns and market cap, (date, permno)-indexed.
87
+ prc, exchcd, nyse_flag : pd.Series, optional
88
+ Price, exchange code and NYSE indicator panels used by the
89
+ documentation screens; screens whose inputs are missing are skipped.
90
+ verbose : bool
91
+ Print anomalies whose sorts raise instead of failing the loop.
92
+
93
+ Returns
94
+ -------
95
+ dict[str, SortResult]
96
+ One sort result per anomaly that could be run.
97
+ """
98
+ print(f"Start at {pd.Timestamp.now():%Y-%m-%d %H:%M:%S}.")
99
+ t0 = time.time()
100
+
101
+ mths = anoms_panel.index.get_level_values("date").month
102
+ june = mths == 6
103
+ june_dec = np.isin(mths, [6, 12])
104
+ quarter_end = np.isin(mths, [3, 6, 9, 12])
105
+ all_dates = anoms_panel.index.get_level_values("date").unique().sort_values()
106
+ n_months = len(all_dates)
107
+
108
+ ind_me5 = None # lazily computed NYSE-break size quintile assignment
109
+ results: dict[str, SortResult] = {}
110
+
111
+ for label in anoms_panel.columns:
112
+ rows = summary[summary["acronym"] == label.lower()]
113
+ if rows.empty:
114
+ continue
115
+ r = rows.iloc[0]
116
+ var = anoms_panel[label].astype(float)
117
+
118
+ # Rebalancing period
119
+ period = r["PortfolioPeriod"]
120
+ if period in (12, 36):
121
+ var = var.where(june)
122
+ elif period == 6:
123
+ var = var.where(june_dec)
124
+ elif period == 3:
125
+ var = var.where(quarter_end)
126
+
127
+ # Screens
128
+ filt = "" if pd.isna(r["Filter"]) else str(r["Filter"]).replace(" ", "")
129
+ if filt:
130
+ if "abs(prc)>1" in filt and prc is not None:
131
+ var = var.where(prc.abs() > 1)
132
+ if "abs(prc)>5" in filt and prc is not None:
133
+ var = var.where(prc.abs() > 5)
134
+ if "exchcd%in%c(1,2)" in filt and exchcd is not None:
135
+ var = var.where((exchcd <= 2).fillna(False))
136
+ if "exchcd==1" in filt and exchcd is not None:
137
+ var = var.where((exchcd <= 1).fillna(False))
138
+ if "me>me_nyse20" in filt and nyse_flag is not None:
139
+ if ind_me5 is None:
140
+ ind_me5 = (
141
+ _bin_by_cross_section(
142
+ mcap, 5, breaks="nyse", nyse_flag=nyse_flag, mcap=None
143
+ )
144
+ .reindex(mcap.index)
145
+ .fillna(0)
146
+ .astype("Int64")
147
+ )
148
+ var = var.where(ind_me5 != 1)
149
+
150
+ # Sample
151
+ if pd.isna(r["SampleStartYear"]):
152
+ continue
153
+ start_month = r["StartMonth"]
154
+ sample_start = int(100 * r["SampleStartYear"]
155
+ + (6 if pd.isna(start_month) else start_month))
156
+ obs = var.groupby(level="date").count()
157
+ obs = obs[obs > 0]
158
+ if obs.empty:
159
+ continue
160
+ last_pos = all_dates.get_loc(obs.index.max())
161
+ hold = 0 if pd.isna(period) else int(period)
162
+ sample_end = all_dates[min(last_pos + hold, n_months - 1)]
163
+ dts = (sample_start, int(f"{sample_end:%Y%m}"))
164
+
165
+ # Portfolio construction
166
+ weighting = "v" if r["StockWeight"] == "VW" else "e"
167
+ leg = None
168
+ if label.lower() == "changeinrecommendation":
169
+ lo = var.groupby(level="date").transform(lambda s: s.quantile(0.20))
170
+ hi = var.groupby(level="date").transform(lambda s: s.quantile(0.80))
171
+ leg = pd.Series(np.nan, index=var.index, dtype="float64")
172
+ leg = leg.mask(var <= lo, 1.0).mask(var >= hi, 2.0)
173
+ elif label.lower() in ("numearnincrease", "rdcap"):
174
+ leg = pd.Series(np.nan, index=var.index, dtype="float64")
175
+ leg = leg.mask(var == 0, 1.0).mask(var > 0, 2.0)
176
+ elif r["Cat_Form"] == "discrete":
177
+ lo, hi = var.min(), var.max()
178
+ leg = pd.Series(np.nan, index=var.index, dtype="float64")
179
+ leg = leg.mask(var == lo, 1.0).mask(var == hi, 2.0)
180
+
181
+ try:
182
+ if leg is not None:
183
+ if leg.notna().sum() == 0:
184
+ continue
185
+ results[label] = _two_leg_sort(
186
+ returns, leg, mcap, weighting=weighting, time_period=dts
187
+ )
188
+ else:
189
+ if var.notna().sum() == 0:
190
+ continue
191
+ ls_q = r["LSQuantile"]
192
+ nptfs = 5 if pd.isna(ls_q) else int(round(1 / ls_q))
193
+ use_nyse = r["QuantileFilter"] == "NYSE" and nyse_flag is not None
194
+ if nptfs == 2:
195
+ pct = [1 * 100 / nptfs]
196
+ else:
197
+ pct = [1 * 100 / nptfs, (nptfs - 1) * 100 / nptfs]
198
+ results[label] = run_univariate_sort(
199
+ returns=returns,
200
+ signal=var,
201
+ mcap=mcap,
202
+ n_bins=pct,
203
+ breaks="nyse" if use_nyse else "name",
204
+ nyse_flag=nyse_flag if use_nyse else None,
205
+ weighting=weighting,
206
+ time_period=dts,
207
+ factor_model=4,
208
+ )
209
+ except Exception as exc:
210
+ if verbose:
211
+ print(f" {label}: {type(exc).__name__}: {exc}")
212
+
213
+ print(f"Done running sorts at {pd.Timestamp.now():%Y-%m-%d %H:%M:%S} "
214
+ f"({time.time() - t0:.0f}s, {len(results)} anomalies).")
215
+ return results
216
+
217
+
218
+ def plot_anomaly_decay(
219
+ results: dict[str, SortResult],
220
+ summary: pd.DataFrame,
221
+ all_dates: pd.Index,
222
+ ) -> np.ndarray:
223
+ """Line the strategies up on publication date and plot the average decay."""
224
+ import matplotlib.pyplot as plt
225
+
226
+ from ..plotting import maybe_show
227
+ from .plots import moving
228
+
229
+ n_months = len(all_dates)
230
+ relative = np.full((2 * n_months + 1, len(results)), np.nan)
231
+
232
+ for k, (label, res) in enumerate(results.items()):
233
+ rows = summary[summary["acronym"] == label.lower()]
234
+ if rows.empty or pd.isna(rows.iloc[0]["Year"]):
235
+ continue
236
+ pub = _to_month_end(int(100 * rows.iloc[0]["Year"] + 12))
237
+ ls = res.pret["long_short"]
238
+ if pub < ls.index.min() or pub > ls.index.max():
239
+ continue
240
+ e = int(ls.index.searchsorted(pub, side="right"))
241
+ relative[n_months - e:n_months, k] = ls.to_numpy()[:e]
242
+ relative[n_months:n_months + len(ls) - e, k] = ls.to_numpy()[e:]
243
+
244
+ avg = np.nanmean(relative, axis=1)
245
+ x = np.arange(-n_months, n_months + 1) / 12
246
+ fig, ax = plt.subplots()
247
+ ax.plot(x, 100 * avg, color=(0.8, 0.8, 0.8), lw=1.0, label="Average")
248
+ ax.plot(x, 100 * moving(avg, 60), lw=1.8, label="5-year moving average")
249
+ ax.set_ylim(-0.5, 1.0)
250
+ ax.set_xlim(-30, 20)
251
+ ax.set_xlabel("Years relative to publication")
252
+ ax.set_title("Average returns across anomalies")
253
+ ax.legend()
254
+ maybe_show(plt)
255
+ return relative