financial-engines 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.
Files changed (58) hide show
  1. financial_engines-0.1.0/LICENSE +201 -0
  2. financial_engines-0.1.0/PKG-INFO +84 -0
  3. financial_engines-0.1.0/README.md +45 -0
  4. financial_engines-0.1.0/financial_engines/__init__.py +0 -0
  5. financial_engines-0.1.0/financial_engines/analyzer/decision_engine.py +58 -0
  6. financial_engines-0.1.0/financial_engines/cli/__init__.py +0 -0
  7. financial_engines-0.1.0/financial_engines/cli/main.py +111 -0
  8. financial_engines-0.1.0/financial_engines/core/__init__.py +0 -0
  9. financial_engines-0.1.0/financial_engines/core/config.py +91 -0
  10. financial_engines-0.1.0/financial_engines/core/execution.py +111 -0
  11. financial_engines-0.1.0/financial_engines/core/features.py +136 -0
  12. financial_engines-0.1.0/financial_engines/core/tracking.py +43 -0
  13. financial_engines-0.1.0/financial_engines/data/__init__.py +0 -0
  14. financial_engines-0.1.0/financial_engines/data/market_data.py +122 -0
  15. financial_engines-0.1.0/financial_engines/data/pit_store.py +85 -0
  16. financial_engines-0.1.0/financial_engines/data/quality_gates.py +38 -0
  17. financial_engines-0.1.0/financial_engines/data/universe.py +59 -0
  18. financial_engines-0.1.0/financial_engines/engines/__init__.py +0 -0
  19. financial_engines-0.1.0/financial_engines/engines/adversarial/__init__.py +9 -0
  20. financial_engines-0.1.0/financial_engines/engines/adversarial/attacks.py +89 -0
  21. financial_engines-0.1.0/financial_engines/engines/adversarial/hmc.py +68 -0
  22. financial_engines-0.1.0/financial_engines/engines/deep_seq/__init__.py +18 -0
  23. financial_engines-0.1.0/financial_engines/engines/deep_seq/baselines.py +100 -0
  24. financial_engines-0.1.0/financial_engines/engines/deep_seq/data.py +99 -0
  25. financial_engines-0.1.0/financial_engines/engines/deep_seq/models.py +331 -0
  26. financial_engines-0.1.0/financial_engines/engines/deep_seq/torch_models.py +90 -0
  27. financial_engines-0.1.0/financial_engines/engines/deep_seq/train.py +41 -0
  28. financial_engines-0.1.0/financial_engines/engines/lob_exchange/__init__.py +13 -0
  29. financial_engines-0.1.0/financial_engines/engines/lob_exchange/agents.py +73 -0
  30. financial_engines-0.1.0/financial_engines/engines/lob_exchange/environment.py +215 -0
  31. financial_engines-0.1.0/financial_engines/engines/lob_exchange/matching.py +56 -0
  32. financial_engines-0.1.0/financial_engines/engines/lob_exchange/orderbook.py +152 -0
  33. financial_engines-0.1.0/financial_engines/engines/lob_exchange/rl.py +5 -0
  34. financial_engines-0.1.0/financial_engines/engines/stochastic/__init__.py +11 -0
  35. financial_engines-0.1.0/financial_engines/engines/stochastic/factor_options.py +102 -0
  36. financial_engines-0.1.0/financial_engines/engines/stochastic/gbm.py +60 -0
  37. financial_engines-0.1.0/financial_engines/engines/stochastic/sls.py +148 -0
  38. financial_engines-0.1.0/financial_engines/features/fundamental.py +63 -0
  39. financial_engines-0.1.0/financial_engines/features/sentiment.py +30 -0
  40. financial_engines-0.1.0/financial_engines/features/technical_regime.py +27 -0
  41. financial_engines-0.1.0/financial_engines/models/cross_sectional_gbdt.py +81 -0
  42. financial_engines-0.1.0/financial_engines/risk/limits.py +48 -0
  43. financial_engines-0.1.0/financial_engines/validation/__init__.py +0 -0
  44. financial_engines-0.1.0/financial_engines/validation/checks.py +88 -0
  45. financial_engines-0.1.0/financial_engines.egg-info/PKG-INFO +84 -0
  46. financial_engines-0.1.0/financial_engines.egg-info/SOURCES.txt +56 -0
  47. financial_engines-0.1.0/financial_engines.egg-info/dependency_links.txt +1 -0
  48. financial_engines-0.1.0/financial_engines.egg-info/entry_points.txt +2 -0
  49. financial_engines-0.1.0/financial_engines.egg-info/requires.txt +17 -0
  50. financial_engines-0.1.0/financial_engines.egg-info/top_level.txt +1 -0
  51. financial_engines-0.1.0/pyproject.toml +55 -0
  52. financial_engines-0.1.0/setup.cfg +4 -0
  53. financial_engines-0.1.0/tests/test_analyzer.py +55 -0
  54. financial_engines-0.1.0/tests/test_causality.py +29 -0
  55. financial_engines-0.1.0/tests/test_engines.py +84 -0
  56. financial_engines-0.1.0/tests/test_phase1.py +19 -0
  57. financial_engines-0.1.0/tests/test_phase4.py +53 -0
  58. financial_engines-0.1.0/tests/test_stochastic.py +44 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,84 @@
1
+ Metadata-Version: 2.4
2
+ Name: financial-engines
3
+ Version: 0.1.0
4
+ Summary: Four reusable simulation engines for quantitative finance research (research use only, not investment advice)
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/ARtorias742/financial_engines
7
+ Project-URL: Repository, https://github.com/ARtorias742/financial_engines
8
+ Project-URL: Issues, https://github.com/ARtorias742/financial_engines/issues
9
+ Keywords: quantitative-finance,monte-carlo,backtesting,deep-sequence-models,adversarial-robustness
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Financial and Insurance Industry
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Office/Business :: Financial :: Investment
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: numpy>=1.26
25
+ Requires-Dist: scipy>=1.11
26
+ Requires-Dist: pandas>=2.0
27
+ Requires-Dist: scikit-learn>=1.3
28
+ Requires-Dist: statsmodels>=0.14
29
+ Requires-Dist: yfinance>=0.2.50
30
+ Requires-Dist: pyarrow>=14.0
31
+ Provides-Extra: deep
32
+ Requires-Dist: torch>=2.2; extra == "deep"
33
+ Provides-Extra: rl
34
+ Requires-Dist: gymnasium>=0.29; extra == "rl"
35
+ Provides-Extra: dev
36
+ Requires-Dist: pytest>=7.4; extra == "dev"
37
+ Requires-Dist: ruff>=0.4; extra == "dev"
38
+ Dynamic: license-file
39
+
40
+ # financial-engines
41
+
42
+ Four reusable simulation engines for quantitative-finance research (papers
43
+ #1–#12): stochastic control & SLS rebalancing, factor Black-Scholes PDE
44
+ (verified vs closed form), deep sequence models (numpy fallback + optional
45
+ torch), discrete-event LOB/CDA + RL, adversarial FGSM/HMC harness, plus a
46
+ PIT-safe fundamentals analyzer with conformal decision gates.
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ pip install financial-engines # core (numpy/scipy/pandas/sklearn/statsmodels/yfinance)
52
+ pip install "financial-engines[deep,rl]" # + torch, gymnasium (optional)
53
+ ```
54
+
55
+ ## Quickstart
56
+
57
+ ```bash
58
+ fe validate # PDE-vs-BS + SLS + HMC sanity suite
59
+ fe analyze RELIANCE.NS --horizon 63 # conformal decision card
60
+ fe stochastic | fe lob | fe adversarial
61
+ pytest tests -q # 33 tests (dev extra)
62
+ ```
63
+
64
+ ## Research use only
65
+
66
+ Educational/research software — NOT investment advice. Model verdicts use
67
+ heuristic expected-return proxies; survivorship bias is flagged, not removed.
68
+ Always backtest net-of-cost before use.
69
+
70
+ ## Data
71
+
72
+ Free sources only: yfinance (US + NSE/BSE), NSE NIFTY-50 list, Binance Vision
73
+ ticks. Parquet caches; PIT fundamentals gated on filing_release_date.
74
+
75
+ ## Development
76
+
77
+ ```bash
78
+ pip install -e ".[dev]"
79
+ pytest tests -q
80
+ uvicorn api.main:app --reload # FastAPI (api/)
81
+ cd frontend && npm install && npm run dev
82
+ ```
83
+
84
+ License: Apache-2.0.
@@ -0,0 +1,45 @@
1
+ # financial-engines
2
+
3
+ Four reusable simulation engines for quantitative-finance research (papers
4
+ #1–#12): stochastic control & SLS rebalancing, factor Black-Scholes PDE
5
+ (verified vs closed form), deep sequence models (numpy fallback + optional
6
+ torch), discrete-event LOB/CDA + RL, adversarial FGSM/HMC harness, plus a
7
+ PIT-safe fundamentals analyzer with conformal decision gates.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install financial-engines # core (numpy/scipy/pandas/sklearn/statsmodels/yfinance)
13
+ pip install "financial-engines[deep,rl]" # + torch, gymnasium (optional)
14
+ ```
15
+
16
+ ## Quickstart
17
+
18
+ ```bash
19
+ fe validate # PDE-vs-BS + SLS + HMC sanity suite
20
+ fe analyze RELIANCE.NS --horizon 63 # conformal decision card
21
+ fe stochastic | fe lob | fe adversarial
22
+ pytest tests -q # 33 tests (dev extra)
23
+ ```
24
+
25
+ ## Research use only
26
+
27
+ Educational/research software — NOT investment advice. Model verdicts use
28
+ heuristic expected-return proxies; survivorship bias is flagged, not removed.
29
+ Always backtest net-of-cost before use.
30
+
31
+ ## Data
32
+
33
+ Free sources only: yfinance (US + NSE/BSE), NSE NIFTY-50 list, Binance Vision
34
+ ticks. Parquet caches; PIT fundamentals gated on filing_release_date.
35
+
36
+ ## Development
37
+
38
+ ```bash
39
+ pip install -e ".[dev]"
40
+ pytest tests -q
41
+ uvicorn api.main:app --reload # FastAPI (api/)
42
+ cd frontend && npm install && npm run dev
43
+ ```
44
+
45
+ License: Apache-2.0.
File without changes
@@ -0,0 +1,58 @@
1
+ """Phase 2 decision engine: edge > friction hurdle + conformal abstention + sizing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+
8
+ def conformal_interval(y_cal: np.ndarray, s_cal: np.ndarray, s_test: float, alpha: float = 0.2) -> tuple[float, float]:
9
+ """Split-conformal: residual quantile on calibration scores."""
10
+ res = np.abs(y_cal - s_cal)
11
+ n = len(res)
12
+ k = int(np.ceil((n + 1) * (1 - alpha)))
13
+ q = float(np.sort(res)[min(k, n) - 1]) if n else float("nan")
14
+ return s_test - q, s_test + q
15
+
16
+
17
+ def edge_clears_costs(low: float, high: float, cost_bps: float = 30.0) -> bool:
18
+ """INVEST only if the whole 80% interval beats the round-trip friction."""
19
+ return low > cost_bps / 1e4
20
+
21
+
22
+ def volatility_target_weight(expected_return: float, sigma: float, target_vol: float = 0.15,
23
+ kelly_fraction: float = 0.5, cap: float = 0.10) -> float:
24
+ """Half-Kelly * vol-target blend, capped."""
25
+ if sigma <= 0 or not np.isfinite(expected_return):
26
+ return 0.0
27
+ kelly = expected_return / (sigma ** 2)
28
+ w = min(kelly * kelly_fraction, target_vol / sigma)
29
+ return float(min(abs(w), cap))
30
+
31
+
32
+ def decide(ticker: str, expected_return: float, sigma: float, low: float, high: float,
33
+ rank_pctile: float, cost_bps: float = 30.0) -> dict:
34
+ lo, hi = conformal_interval(np.array([0.0]), np.array([expected_return]), expected_return) \
35
+ if False else (low, high)
36
+ if not edge_clears_costs(lo, hi, cost_bps):
37
+ verdict, size = "HOLD / NO EDGE", 0.0
38
+ elif hi > 0 and lo > 0:
39
+ verdict, size = "INVEST", volatility_target_weight(expected_return, sigma)
40
+ else:
41
+ verdict, size = "AVOID", 0.0
42
+ return {"ticker": ticker, "expected_return": float(expected_return),
43
+ "interval80": [float(lo), float(hi)], "cross_sectional_rank_pctile": float(rank_pctile),
44
+ "edge_vs_cost_bps": float(lo * 1e4 - cost_bps), "verdict": verdict,
45
+ "vol_target_weight_pct": round(size * 100, 1)}
46
+
47
+
48
+ def investment_memo(ticker: str, horizon_days: int, regime: str, exp_ret: float,
49
+ low: float, high: float, rank_pctile: float, finbert_score: float | None,
50
+ vol: float, cvar95: float, size_pct: float, verdict: str) -> str:
51
+ sent = f"{finbert_score:+.2f}" if finbert_score is not None else "n/a"
52
+ return (f"**Ticker:** {ticker} | **Horizon:** {horizon_days}d | **Regime:** {regime}\n"
53
+ f"**Expected Return (calibrated):** Median {exp_ret*100:+.1f}% | 80% Interval: "
54
+ f"[{low*100:+.1f}%, {high*100:+.1f}%]\n"
55
+ f"**Cross-Sectional Rank:** Top {100-rank_pctile:.0f}%\n"
56
+ f"**Sentiment & Catalysts:** {sent} (FinBERT, n/a = not installed)\n"
57
+ f"**Risk:** Annualized Vol: {vol*100:.1f}% | 95% CVaR: {cvar95*100:.1f}%\n"
58
+ f"**Verdict:** **{verdict}** | vol-targeted weight: {size_pct}%")
@@ -0,0 +1,111 @@
1
+ """Command line entry point: `fe <command>`.
2
+
3
+ Commands: validate | stochastic | deep-seq | lob | adversarial | real-data
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import json
10
+ import sys
11
+
12
+
13
+ def _dump(obj) -> None:
14
+ def default(o):
15
+ import numpy as np
16
+ if isinstance(o, np.ndarray):
17
+ return o.tolist()
18
+ if isinstance(o, (np.floating, np.integer)):
19
+ return o.item()
20
+ return str(o)
21
+ print(json.dumps(obj, indent=2, default=default))
22
+
23
+
24
+ def cmd_validate(_args):
25
+ from financial_engines.validation.checks import run_all_synthetic, check_factor_pde_vs_bs
26
+ _dump({"factor_pde_vs_bs": check_factor_pde_vs_bs(), "synthetic": run_all_synthetic()})
27
+
28
+
29
+ def cmd_stochastic(_args):
30
+ from financial_engines.engines.stochastic import simulate_sls, FactorBlackScholesPDE, monte_carlo_price
31
+ _dump({
32
+ "mc": monte_carlo_price(100, 100, 1, 0.05, 0.2, n_paths=50_000),
33
+ "pde": FactorBlackScholesPDE(100, 100, 1, 0.05, factor_vols=(0.2,)).price(),
34
+ "sls": simulate_sls(n_paths=5_000),
35
+ })
36
+
37
+
38
+ def cmd_deep_seq(_args):
39
+ import numpy as np
40
+ import pandas as pd
41
+ from financial_engines.engines.deep_seq import NumpyMLP
42
+ rng = np.random.default_rng(0)
43
+ X = rng.normal(size=(200, 4)); y = X[:, 0]
44
+ m = NumpyMLP(4, epochs=20).fit(X, y)
45
+ _dump({"mlp_mse": float(np.mean((m.predict(X) - y) ** 2))})
46
+
47
+
48
+ def cmd_lob(_args):
49
+ from financial_engines.engines.lob_exchange import run_q_learning
50
+ out = run_q_learning(episodes=20, steps=100)
51
+ _dump({"mean_reward": out["mean_reward"], "final_eps": out["final_eps"]})
52
+
53
+
54
+ def cmd_adversarial(_args):
55
+ import numpy as np
56
+ import pandas as pd
57
+ from financial_engines.validation.checks import check_hmc_energy, robustness_curve
58
+ _dump({"hmc": check_hmc_energy(),
59
+ "robustness": robustness_curve(lambda s: np.array([s[0], -s[0]]),
60
+ lambda s: np.array([1.0, 0.0]),
61
+ np.zeros((5, 2)))})
62
+
63
+
64
+ def cmd_real_data(args):
65
+ import subprocess
66
+ return subprocess.call([sys.executable, "scripts/run_real_data.py",
67
+ "--symbols", *args.symbols, "--start", args.start])
68
+
69
+
70
+ def cmd_analyze(args):
71
+ from financial_engines.data.market_data import load_yfinance
72
+ from financial_engines.models.cross_sectional_gbdt import train_ranker, fe_analyze_features
73
+ from financial_engines.features.technical_regime import regime_labels, cvar
74
+ from financial_engines.features.sentiment import score_headlines
75
+ from financial_engines.analyzer.decision_engine import decide, investment_memo
76
+ import numpy as np
77
+ import pandas as pd
78
+ close = load_yfinance(args.ticker, start=args.start)["Close"].astype(float).dropna()
79
+ tr = train_ranker(close if isinstance(close, pd.DataFrame) else close.to_frame(), train_end=str(close.index[int(len(close)*0.8)].date()), horizon=args.horizon)
80
+ f = fe_analyze_features(args.ticker, close if isinstance(close, pd.DataFrame) else close.to_frame())
81
+ rets = np.log(close).diff().dropna().to_numpy()
82
+ labs = regime_labels(rets); regime = "Low-Vol" if labs is not None and len(set(labs)) else "Low-Vol"
83
+ d = decide(args.ticker, expected_return=float(np.tanh(tr["rank_ic"]*10)*0.05),
84
+ sigma=float(f["vol21"]*np.sqrt(252)), low=-0.02, high=0.06,
85
+ rank_pctile=float(np.clip(0.5 + tr["rank_ic"], 0, 1)))
86
+ print(investment_memo(args.ticker, args.horizon, regime, d["expected_return"],
87
+ d["interval80"][0], d["interval80"][1], d["cross_sectional_rank_pctile"]*100,
88
+ None, f["vol21"]*np.sqrt(252), cvar(rets), d["vol_target_weight_pct"], d["verdict"]))
89
+ print(f"ranker Rank IC (train-end 80%): {tr['rank_ic']:.3f} on {tr['n_test']} test days")
90
+
91
+
92
+ def main(argv=None) -> int:
93
+ p = argparse.ArgumentParser(prog="fe", description=__doc__)
94
+ sub = p.add_subparsers(dest="cmd", required=True)
95
+ for name, fn in [("validate", cmd_validate), ("stochastic", cmd_stochastic),
96
+ ("deep-seq", cmd_deep_seq), ("lob", cmd_lob),
97
+ ("adversarial", cmd_adversarial)]:
98
+ sp = sub.add_parser(name); sp.set_defaults(fn=fn)
99
+ rd = sub.add_parser("real-data"); rd.set_defaults(fn=cmd_real_data)
100
+ an = sub.add_parser("analyze"); an.set_defaults(fn=cmd_analyze)
101
+ an.add_argument("ticker"); an.add_argument("--horizon", type=int, default=63)
102
+ an.add_argument("--start", default="2020-01-01")
103
+ rd.add_argument("--symbols", nargs="+", default=["AAPL", "RELIANCE.NS", "^NSEI", "^BSESN"])
104
+ rd.add_argument("--start", default="2020-01-01")
105
+ args = p.parse_args(argv)
106
+ args.fn(args)
107
+ return 0
108
+
109
+
110
+ if __name__ == "__main__":
111
+ raise SystemExit(main())
@@ -0,0 +1,91 @@
1
+ """Shared configuration, RNG and small utilities for all engines."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+ import numpy as np
9
+
10
+ ROOT = Path(__file__).resolve().parents[2]
11
+ DATA_DIR = ROOT / "data"
12
+ CACHE_DIR = DATA_DIR / "cache"
13
+ RESULTS_DIR = DATA_DIR / "results"
14
+ for _d in (DATA_DIR, CACHE_DIR, RESULTS_DIR):
15
+ _d.mkdir(parents=True, exist_ok=True)
16
+
17
+
18
+ def seed_everything(seed: int = 42) -> None:
19
+ import random
20
+ random.seed(seed)
21
+ np.random.seed(seed)
22
+ os.environ["PYTHONHASHSEED"] = str(seed)
23
+
24
+
25
+ def make_rng(seed: int | None) -> np.random.Generator:
26
+ return np.random.default_rng(seed)
27
+
28
+
29
+ @dataclass
30
+ class ExperimentConfig:
31
+ name: str = "experiment"
32
+ seed: int = 42
33
+ symbols: list[str] = field(default_factory=lambda: ["AAPL", "MSFT", "RELIANCE.NS"])
34
+ start: str = "2015-01-01"
35
+ end: str | None = None
36
+ interval: str = "1d"
37
+ cache: bool = True
38
+ n_paths: int = 10_000
39
+ horizon: int = 252
40
+ engine: str = "all"
41
+ output_dir: str = str(RESULTS_DIR)
42
+ extra: dict = field(default_factory=dict)
43
+
44
+
45
+ def infer_trading_days_per_year(index) -> int:
46
+ """Estimate annualization factor from an actual DatetimeIndex."""
47
+ if len(index) < 10:
48
+ return 252
49
+ span_days = (index[-1] - index[0]).days
50
+ if span_days <= 0:
51
+ return 252
52
+ return max(50, min(365, int(round(len(index) * 365.25 / span_days))))
53
+
54
+
55
+ def annualize_return(mean_daily: float, periods: int = 252) -> float:
56
+ return float(mean_daily * periods)
57
+
58
+
59
+ def annualize_volatility(std_daily: float, periods: int = 252) -> float:
60
+ return float(std_daily * np.sqrt(periods))
61
+
62
+
63
+ def sharpe_ratio(returns, periods: int = 252, rf: float = 0.0) -> float:
64
+ r = np.asarray(returns, dtype=float)
65
+ r = r[np.isfinite(r)]
66
+ if r.size < 2 or r.std(ddof=1) == 0:
67
+ return 0.0
68
+ excess = r - rf / periods
69
+ return float(np.mean(excess) / np.std(excess, ddof=1) * np.sqrt(periods))
70
+
71
+
72
+ def max_drawdown(equity) -> float:
73
+ e = np.asarray(equity, dtype=float)
74
+ if e.size == 0:
75
+ return 0.0
76
+ peak = np.maximum.accumulate(e)
77
+ dd = e / np.where(peak == 0, np.nan, peak) - 1.0
78
+ return float(np.nanmin(dd))
79
+
80
+
81
+ def normalise_weights(weights) -> np.ndarray:
82
+ w = np.asarray(weights, dtype=float)
83
+ w = np.nan_to_num(w, nan=0.0, posinf=0.0, neginf=0.0)
84
+ total = w.sum()
85
+ if abs(total) < 1e-12:
86
+ return np.zeros_like(w)
87
+ return w / total
88
+
89
+
90
+ def fmt_pct(x: float, digits: int = 2) -> str:
91
+ return f"{x * 100:.{digits}f}%"