finlearn-analytics 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.
- finlearn_analytics-0.1.0/LICENSE +21 -0
- finlearn_analytics-0.1.0/PKG-INFO +179 -0
- finlearn_analytics-0.1.0/README.md +144 -0
- finlearn_analytics-0.1.0/finlearn/__init__.py +32 -0
- finlearn_analytics-0.1.0/finlearn/benchmarks.py +99 -0
- finlearn_analytics-0.1.0/finlearn/biases.py +659 -0
- finlearn_analytics-0.1.0/finlearn/memo.py +147 -0
- finlearn_analytics-0.1.0/finlearn/metrics.py +100 -0
- finlearn_analytics-0.1.0/finlearn/py.typed +0 -0
- finlearn_analytics-0.1.0/finlearn/utils.py +40 -0
- finlearn_analytics-0.1.0/finlearn_analytics.egg-info/PKG-INFO +179 -0
- finlearn_analytics-0.1.0/finlearn_analytics.egg-info/SOURCES.txt +18 -0
- finlearn_analytics-0.1.0/finlearn_analytics.egg-info/dependency_links.txt +1 -0
- finlearn_analytics-0.1.0/finlearn_analytics.egg-info/requires.txt +5 -0
- finlearn_analytics-0.1.0/finlearn_analytics.egg-info/top_level.txt +1 -0
- finlearn_analytics-0.1.0/pyproject.toml +56 -0
- finlearn_analytics-0.1.0/setup.cfg +7 -0
- finlearn_analytics-0.1.0/tests/test_biases.py +187 -0
- finlearn_analytics-0.1.0/tests/test_core.py +248 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Jeevun Sandhu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: finlearn-analytics
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Financial analytics and behavioral finance research tools for Python
|
|
5
|
+
Author: Jeevun Sandhu
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/JSand15/finlearn-analytics
|
|
8
|
+
Project-URL: Repository, https://github.com/JSand15/finlearn-analytics
|
|
9
|
+
Project-URL: Issues, https://github.com/JSand15/finlearn-analytics/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/JSand15/finlearn-analytics/blob/main/CHANGELOG.md
|
|
11
|
+
Keywords: finance,analytics,sharpe ratio,behavioral finance,investment
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
14
|
+
Classifier: Intended Audience :: Education
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python :: 3
|
|
20
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
26
|
+
Classifier: Typing :: Typed
|
|
27
|
+
Requires-Python: >=3.9
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
License-File: LICENSE
|
|
30
|
+
Provides-Extra: dev
|
|
31
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
32
|
+
Requires-Dist: build>=1.0; extra == "dev"
|
|
33
|
+
Requires-Dist: twine>=4.0; extra == "dev"
|
|
34
|
+
Dynamic: license-file
|
|
35
|
+
|
|
36
|
+
# finlearn-analytics
|
|
37
|
+
|
|
38
|
+
**Detect 69 behavioral-finance biases in investment memos — plus Sharpe ratio, max drawdown, and benchmark analytics. Pure Python, zero dependencies.**
|
|
39
|
+
|
|
40
|
+
[](https://pypi.org/project/finlearn-analytics/)
|
|
41
|
+
[](https://github.com/JSand15/finlearn-analytics/actions/workflows/ci.yml)
|
|
42
|
+
[](https://pepy.tech/project/finlearn-analytics)
|
|
43
|
+
[](LICENSE)
|
|
44
|
+
[](https://www.python.org/)
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## Installation
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pip install finlearn-analytics
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## Quick Start
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from finlearn import (
|
|
60
|
+
calculate_sharpe_ratio,
|
|
61
|
+
calculate_max_drawdown,
|
|
62
|
+
compare_to_benchmark,
|
|
63
|
+
analyze_memo_quality,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
# Daily returns for a hypothetical portfolio
|
|
67
|
+
daily_returns = [0.012, -0.005, 0.008, 0.003, -0.002, 0.015, 0.001, -0.007, 0.009, 0.004]
|
|
68
|
+
|
|
69
|
+
# 1. Sharpe Ratio
|
|
70
|
+
sharpe = calculate_sharpe_ratio(daily_returns, risk_free_rate=0.0001)
|
|
71
|
+
print(f"Sharpe Ratio: {sharpe:.2f}")
|
|
72
|
+
|
|
73
|
+
# 2. Max Drawdown
|
|
74
|
+
prices = [100, 112, 107, 115, 109, 124, 125, 118, 127, 129]
|
|
75
|
+
drawdown = calculate_max_drawdown(prices)
|
|
76
|
+
print(f"Max Drawdown: {drawdown:.2%}")
|
|
77
|
+
|
|
78
|
+
# 3. Benchmark Comparison
|
|
79
|
+
benchmark_returns = [0.008, -0.003, 0.005, 0.002, -0.001, 0.010, 0.000, -0.004, 0.006, 0.003]
|
|
80
|
+
metrics = compare_to_benchmark(daily_returns, benchmark_returns)
|
|
81
|
+
print(f"Alpha: {metrics['alpha']:.4f} Beta: {metrics['beta']:.2f} Correlation: {metrics['correlation']:.2f}")
|
|
82
|
+
print(f"Excess Return: {metrics['excess_return']:.4f} Tracking Error: {metrics['tracking_error']:.4f}")
|
|
83
|
+
|
|
84
|
+
# 4. Memo Quality Analysis
|
|
85
|
+
memo = """
|
|
86
|
+
This stock shows strong momentum and profit potential. The company's
|
|
87
|
+
revenue growth is robust, with favorable market conditions driving
|
|
88
|
+
an expected increase in earnings next quarter.
|
|
89
|
+
"""
|
|
90
|
+
analysis = analyze_memo_quality(memo)
|
|
91
|
+
print(f"Word Count: {analysis['word_count']}")
|
|
92
|
+
print(f"Sentiment: {analysis['sentiment_score']:.2f}")
|
|
93
|
+
print(f"Clarity Score: {analysis['clarity_score']}/100")
|
|
94
|
+
print(f"Overconfidence Flags: {analysis['overconfidence_flags']}")
|
|
95
|
+
print(f"Behavioral Biases: {analysis['behavioral_biases']}")
|
|
96
|
+
print(f"Recommendation: {analysis['recommendation']}")
|
|
97
|
+
|
|
98
|
+
# 5. Behavioral Bias Detection (60+ specific biases)
|
|
99
|
+
from finlearn import analyze_biases, get_bias
|
|
100
|
+
|
|
101
|
+
note = "It's guaranteed to be the next Amazon. Everyone is buying — can't miss this."
|
|
102
|
+
report = analyze_biases(note)
|
|
103
|
+
print(f"Biases detected: {report['biases_detected']}")
|
|
104
|
+
print(f"By category: {report['by_category']}")
|
|
105
|
+
print(get_bias("fomo")["description"])
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
---
|
|
109
|
+
|
|
110
|
+
## Functions
|
|
111
|
+
|
|
112
|
+
### `calculate_sharpe_ratio(returns, risk_free_rate=0.0)`
|
|
113
|
+
|
|
114
|
+
Computes the annualized Sharpe ratio for a series of daily returns. The Sharpe ratio measures risk-adjusted performance: how much excess return is earned per unit of volatility. A ratio above 1.0 is generally considered acceptable; above 2.0 is considered excellent. Raises `ValueError` if returns have zero standard deviation or fewer than 2 observations.
|
|
115
|
+
|
|
116
|
+
**Parameters:** `returns` — list of daily returns as decimals; `risk_free_rate` — daily risk-free rate (default 0.0).
|
|
117
|
+
**Returns:** `float` — annualized Sharpe ratio.
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
### `calculate_max_drawdown(prices)`
|
|
122
|
+
|
|
123
|
+
Calculates the maximum peak-to-trough decline in a price series, returned as a negative decimal (e.g., `-0.25` means a 25% loss from peak to trough). This metric is a standard measure of downside risk. Requires at least 2 positive price values.
|
|
124
|
+
|
|
125
|
+
**Parameters:** `prices` — list of asset prices in chronological order (all positive).
|
|
126
|
+
**Returns:** `float` — maximum drawdown, between -1.0 and 0.0.
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
### `compare_to_benchmark(portfolio_returns, benchmark_returns)`
|
|
131
|
+
|
|
132
|
+
Benchmarks a portfolio against an index by computing Jensen's alpha, beta, Pearson correlation, annualized excess return, and annualized tracking error. Alpha represents return beyond what market exposure (beta) predicts. Tracking error measures consistency of outperformance. Both lists must be equal in length with at least 2 observations.
|
|
133
|
+
|
|
134
|
+
**Parameters:** `portfolio_returns`, `benchmark_returns` — lists of daily returns as decimals of equal length.
|
|
135
|
+
**Returns:** `dict` with keys `alpha`, `beta`, `correlation`, `excess_return`, `tracking_error`.
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
### `analyze_memo_quality(memo_text)`
|
|
140
|
+
|
|
141
|
+
Applies behavioral finance heuristics to score the quality of an investment memo. Detects overconfidence bias (guaranteed returns, zero-risk claims), measures sentiment polarity using financial vocabulary, estimates structural clarity from sentence length and vocabulary diversity, and produces a plain-English improvement recommendation.
|
|
142
|
+
|
|
143
|
+
**Parameters:** `memo_text` — full text of the investment memo as a string.
|
|
144
|
+
**Returns:** `dict` with keys `word_count`, `sentiment_score`, `overconfidence_flags`, `behavioral_biases`, `clarity_score`, `recommendation`.
|
|
145
|
+
|
|
146
|
+
---
|
|
147
|
+
|
|
148
|
+
### Behavioral Bias Detection
|
|
149
|
+
|
|
150
|
+
`finlearn.biases` ships a catalog of **69 specific behavioral-finance biases** across 10 categories (Confidence, Loss & Risk, Anchoring, Information Processing, Social & Herding, Probability, Framing, Temporal, Emotional, and Memory & Attention). Each bias carries a finance-specific description and a set of lowercase trigger phrases. A lightweight, dependency-free detector flags the linguistic fingerprints of these biases in any text — investment memos, research notes, or trade rationales. It is a heuristic screen to surface candidates for human review, not a classifier.
|
|
151
|
+
|
|
152
|
+
| Function | Returns |
|
|
153
|
+
|----------|---------|
|
|
154
|
+
| `detect_biases(text)` | `list[dict]` — each detected bias with `key`, `name`, `category`, `description`, `matched_phrases` |
|
|
155
|
+
| `analyze_biases(text)` | `dict` — `bias_count`, `biases_detected`, `by_category`, `details`, `bias_density_per_100_words`, `recommendation` |
|
|
156
|
+
| `list_biases()` | `list[dict]` — metadata (`key`, `name`, `category`, `description`) for every bias |
|
|
157
|
+
| `list_bias_categories()` | `list[str]` — the distinct category labels |
|
|
158
|
+
| `get_bias(key)` | `dict` — full metadata for one bias, including its trigger `phrases` |
|
|
159
|
+
|
|
160
|
+
Detected biases include: overconfidence, overprecision, loss aversion, the disposition effect, sunk-cost fallacy, anchoring, confirmation bias, recency bias, herding, FOMO, the gambler's fallacy, the hot-hand fallacy, mental accounting, the framing effect, present bias, the affect heuristic, survivorship bias, and ~50 more — each individually addressable by key.
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
from finlearn import detect_biases
|
|
164
|
+
|
|
165
|
+
hits = detect_biases("We're in too deep to sell now, but it's a sure thing.")
|
|
166
|
+
print([h["key"] for h in hits]) # ['overconfidence', 'sunk_cost']
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
---
|
|
170
|
+
|
|
171
|
+
## About
|
|
172
|
+
|
|
173
|
+
Built by **Jeevun Sandhu**, a high school student and founder of **FinanceOS**, a financial literacy platform deployed in LAUSD Title I schools. `finlearn-analytics` powers the quantitative backend of FinanceOS research, giving students and educators access to professional-grade financial analytics tools.
|
|
174
|
+
|
|
175
|
+
---
|
|
176
|
+
|
|
177
|
+
## License
|
|
178
|
+
|
|
179
|
+
MIT — see [LICENSE](LICENSE) for details.
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# finlearn-analytics
|
|
2
|
+
|
|
3
|
+
**Detect 69 behavioral-finance biases in investment memos — plus Sharpe ratio, max drawdown, and benchmark analytics. Pure Python, zero dependencies.**
|
|
4
|
+
|
|
5
|
+
[](https://pypi.org/project/finlearn-analytics/)
|
|
6
|
+
[](https://github.com/JSand15/finlearn-analytics/actions/workflows/ci.yml)
|
|
7
|
+
[](https://pepy.tech/project/finlearn-analytics)
|
|
8
|
+
[](LICENSE)
|
|
9
|
+
[](https://www.python.org/)
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install finlearn-analytics
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## Quick Start
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from finlearn import (
|
|
25
|
+
calculate_sharpe_ratio,
|
|
26
|
+
calculate_max_drawdown,
|
|
27
|
+
compare_to_benchmark,
|
|
28
|
+
analyze_memo_quality,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
# Daily returns for a hypothetical portfolio
|
|
32
|
+
daily_returns = [0.012, -0.005, 0.008, 0.003, -0.002, 0.015, 0.001, -0.007, 0.009, 0.004]
|
|
33
|
+
|
|
34
|
+
# 1. Sharpe Ratio
|
|
35
|
+
sharpe = calculate_sharpe_ratio(daily_returns, risk_free_rate=0.0001)
|
|
36
|
+
print(f"Sharpe Ratio: {sharpe:.2f}")
|
|
37
|
+
|
|
38
|
+
# 2. Max Drawdown
|
|
39
|
+
prices = [100, 112, 107, 115, 109, 124, 125, 118, 127, 129]
|
|
40
|
+
drawdown = calculate_max_drawdown(prices)
|
|
41
|
+
print(f"Max Drawdown: {drawdown:.2%}")
|
|
42
|
+
|
|
43
|
+
# 3. Benchmark Comparison
|
|
44
|
+
benchmark_returns = [0.008, -0.003, 0.005, 0.002, -0.001, 0.010, 0.000, -0.004, 0.006, 0.003]
|
|
45
|
+
metrics = compare_to_benchmark(daily_returns, benchmark_returns)
|
|
46
|
+
print(f"Alpha: {metrics['alpha']:.4f} Beta: {metrics['beta']:.2f} Correlation: {metrics['correlation']:.2f}")
|
|
47
|
+
print(f"Excess Return: {metrics['excess_return']:.4f} Tracking Error: {metrics['tracking_error']:.4f}")
|
|
48
|
+
|
|
49
|
+
# 4. Memo Quality Analysis
|
|
50
|
+
memo = """
|
|
51
|
+
This stock shows strong momentum and profit potential. The company's
|
|
52
|
+
revenue growth is robust, with favorable market conditions driving
|
|
53
|
+
an expected increase in earnings next quarter.
|
|
54
|
+
"""
|
|
55
|
+
analysis = analyze_memo_quality(memo)
|
|
56
|
+
print(f"Word Count: {analysis['word_count']}")
|
|
57
|
+
print(f"Sentiment: {analysis['sentiment_score']:.2f}")
|
|
58
|
+
print(f"Clarity Score: {analysis['clarity_score']}/100")
|
|
59
|
+
print(f"Overconfidence Flags: {analysis['overconfidence_flags']}")
|
|
60
|
+
print(f"Behavioral Biases: {analysis['behavioral_biases']}")
|
|
61
|
+
print(f"Recommendation: {analysis['recommendation']}")
|
|
62
|
+
|
|
63
|
+
# 5. Behavioral Bias Detection (60+ specific biases)
|
|
64
|
+
from finlearn import analyze_biases, get_bias
|
|
65
|
+
|
|
66
|
+
note = "It's guaranteed to be the next Amazon. Everyone is buying — can't miss this."
|
|
67
|
+
report = analyze_biases(note)
|
|
68
|
+
print(f"Biases detected: {report['biases_detected']}")
|
|
69
|
+
print(f"By category: {report['by_category']}")
|
|
70
|
+
print(get_bias("fomo")["description"])
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
## Functions
|
|
76
|
+
|
|
77
|
+
### `calculate_sharpe_ratio(returns, risk_free_rate=0.0)`
|
|
78
|
+
|
|
79
|
+
Computes the annualized Sharpe ratio for a series of daily returns. The Sharpe ratio measures risk-adjusted performance: how much excess return is earned per unit of volatility. A ratio above 1.0 is generally considered acceptable; above 2.0 is considered excellent. Raises `ValueError` if returns have zero standard deviation or fewer than 2 observations.
|
|
80
|
+
|
|
81
|
+
**Parameters:** `returns` — list of daily returns as decimals; `risk_free_rate` — daily risk-free rate (default 0.0).
|
|
82
|
+
**Returns:** `float` — annualized Sharpe ratio.
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
### `calculate_max_drawdown(prices)`
|
|
87
|
+
|
|
88
|
+
Calculates the maximum peak-to-trough decline in a price series, returned as a negative decimal (e.g., `-0.25` means a 25% loss from peak to trough). This metric is a standard measure of downside risk. Requires at least 2 positive price values.
|
|
89
|
+
|
|
90
|
+
**Parameters:** `prices` — list of asset prices in chronological order (all positive).
|
|
91
|
+
**Returns:** `float` — maximum drawdown, between -1.0 and 0.0.
|
|
92
|
+
|
|
93
|
+
---
|
|
94
|
+
|
|
95
|
+
### `compare_to_benchmark(portfolio_returns, benchmark_returns)`
|
|
96
|
+
|
|
97
|
+
Benchmarks a portfolio against an index by computing Jensen's alpha, beta, Pearson correlation, annualized excess return, and annualized tracking error. Alpha represents return beyond what market exposure (beta) predicts. Tracking error measures consistency of outperformance. Both lists must be equal in length with at least 2 observations.
|
|
98
|
+
|
|
99
|
+
**Parameters:** `portfolio_returns`, `benchmark_returns` — lists of daily returns as decimals of equal length.
|
|
100
|
+
**Returns:** `dict` with keys `alpha`, `beta`, `correlation`, `excess_return`, `tracking_error`.
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
### `analyze_memo_quality(memo_text)`
|
|
105
|
+
|
|
106
|
+
Applies behavioral finance heuristics to score the quality of an investment memo. Detects overconfidence bias (guaranteed returns, zero-risk claims), measures sentiment polarity using financial vocabulary, estimates structural clarity from sentence length and vocabulary diversity, and produces a plain-English improvement recommendation.
|
|
107
|
+
|
|
108
|
+
**Parameters:** `memo_text` — full text of the investment memo as a string.
|
|
109
|
+
**Returns:** `dict` with keys `word_count`, `sentiment_score`, `overconfidence_flags`, `behavioral_biases`, `clarity_score`, `recommendation`.
|
|
110
|
+
|
|
111
|
+
---
|
|
112
|
+
|
|
113
|
+
### Behavioral Bias Detection
|
|
114
|
+
|
|
115
|
+
`finlearn.biases` ships a catalog of **69 specific behavioral-finance biases** across 10 categories (Confidence, Loss & Risk, Anchoring, Information Processing, Social & Herding, Probability, Framing, Temporal, Emotional, and Memory & Attention). Each bias carries a finance-specific description and a set of lowercase trigger phrases. A lightweight, dependency-free detector flags the linguistic fingerprints of these biases in any text — investment memos, research notes, or trade rationales. It is a heuristic screen to surface candidates for human review, not a classifier.
|
|
116
|
+
|
|
117
|
+
| Function | Returns |
|
|
118
|
+
|----------|---------|
|
|
119
|
+
| `detect_biases(text)` | `list[dict]` — each detected bias with `key`, `name`, `category`, `description`, `matched_phrases` |
|
|
120
|
+
| `analyze_biases(text)` | `dict` — `bias_count`, `biases_detected`, `by_category`, `details`, `bias_density_per_100_words`, `recommendation` |
|
|
121
|
+
| `list_biases()` | `list[dict]` — metadata (`key`, `name`, `category`, `description`) for every bias |
|
|
122
|
+
| `list_bias_categories()` | `list[str]` — the distinct category labels |
|
|
123
|
+
| `get_bias(key)` | `dict` — full metadata for one bias, including its trigger `phrases` |
|
|
124
|
+
|
|
125
|
+
Detected biases include: overconfidence, overprecision, loss aversion, the disposition effect, sunk-cost fallacy, anchoring, confirmation bias, recency bias, herding, FOMO, the gambler's fallacy, the hot-hand fallacy, mental accounting, the framing effect, present bias, the affect heuristic, survivorship bias, and ~50 more — each individually addressable by key.
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
from finlearn import detect_biases
|
|
129
|
+
|
|
130
|
+
hits = detect_biases("We're in too deep to sell now, but it's a sure thing.")
|
|
131
|
+
print([h["key"] for h in hits]) # ['overconfidence', 'sunk_cost']
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
---
|
|
135
|
+
|
|
136
|
+
## About
|
|
137
|
+
|
|
138
|
+
Built by **Jeevun Sandhu**, a high school student and founder of **FinanceOS**, a financial literacy platform deployed in LAUSD Title I schools. `finlearn-analytics` powers the quantitative backend of FinanceOS research, giving students and educators access to professional-grade financial analytics tools.
|
|
139
|
+
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
## License
|
|
143
|
+
|
|
144
|
+
MIT — see [LICENSE](LICENSE) for details.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""finlearn-analytics: Financial analytics and behavioral finance research tools."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
__author__ = "Jeevun Sandhu"
|
|
5
|
+
|
|
6
|
+
from .metrics import calculate_sharpe_ratio, calculate_max_drawdown
|
|
7
|
+
from .benchmarks import compare_to_benchmark
|
|
8
|
+
from .memo import analyze_memo_quality
|
|
9
|
+
from .biases import (
|
|
10
|
+
BehavioralBias,
|
|
11
|
+
BIASES,
|
|
12
|
+
detect_biases,
|
|
13
|
+
analyze_biases,
|
|
14
|
+
list_biases,
|
|
15
|
+
list_bias_categories,
|
|
16
|
+
get_bias,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"calculate_sharpe_ratio",
|
|
21
|
+
"calculate_max_drawdown",
|
|
22
|
+
"compare_to_benchmark",
|
|
23
|
+
"analyze_memo_quality",
|
|
24
|
+
# Behavioral bias detection
|
|
25
|
+
"BehavioralBias",
|
|
26
|
+
"BIASES",
|
|
27
|
+
"detect_biases",
|
|
28
|
+
"analyze_biases",
|
|
29
|
+
"list_biases",
|
|
30
|
+
"list_bias_categories",
|
|
31
|
+
"get_bias",
|
|
32
|
+
]
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Portfolio-vs-benchmark comparison analytics."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from typing import Dict, List
|
|
5
|
+
|
|
6
|
+
from .utils import validate_returns
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def compare_to_benchmark(
|
|
10
|
+
portfolio_returns: List[float],
|
|
11
|
+
benchmark_returns: List[float],
|
|
12
|
+
) -> Dict[str, float]:
|
|
13
|
+
"""Compare portfolio performance against a benchmark index.
|
|
14
|
+
|
|
15
|
+
Computes alpha, beta, correlation, excess return, and tracking error
|
|
16
|
+
using standard financial definitions. Beta is estimated via OLS regression
|
|
17
|
+
of portfolio returns on benchmark returns.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
portfolio_returns: List of daily portfolio returns as decimals.
|
|
21
|
+
benchmark_returns: List of daily benchmark returns as decimals.
|
|
22
|
+
Must be the same length as portfolio_returns.
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
Dictionary with the following keys:
|
|
26
|
+
- alpha (float): Annualized Jensen's alpha (excess return beyond
|
|
27
|
+
what beta predicts).
|
|
28
|
+
- beta (float): Portfolio sensitivity to benchmark movements.
|
|
29
|
+
- correlation (float): Pearson correlation between portfolio and
|
|
30
|
+
benchmark returns, in [-1, 1].
|
|
31
|
+
- excess_return (float): Annualized mean(portfolio) - mean(benchmark).
|
|
32
|
+
- tracking_error (float): Annualized standard deviation of the
|
|
33
|
+
return difference (portfolio - benchmark).
|
|
34
|
+
|
|
35
|
+
Raises:
|
|
36
|
+
TypeError: If either argument is not a list/tuple or contains
|
|
37
|
+
non-numeric values.
|
|
38
|
+
ValueError: If either list is empty, they differ in length, or the
|
|
39
|
+
benchmark has zero variance.
|
|
40
|
+
|
|
41
|
+
Example:
|
|
42
|
+
>>> port = [0.001, 0.002, -0.001, 0.003]
|
|
43
|
+
>>> bench = [0.0005, 0.0015, -0.0005, 0.002]
|
|
44
|
+
>>> result = compare_to_benchmark(port, bench)
|
|
45
|
+
>>> result['beta']
|
|
46
|
+
1.5254...
|
|
47
|
+
"""
|
|
48
|
+
p = validate_returns(portfolio_returns, "portfolio_returns")
|
|
49
|
+
b = validate_returns(benchmark_returns, "benchmark_returns")
|
|
50
|
+
|
|
51
|
+
if len(p) != len(b):
|
|
52
|
+
raise ValueError(
|
|
53
|
+
f"portfolio_returns (len={len(p)}) and benchmark_returns (len={len(b)}) "
|
|
54
|
+
"must have the same length"
|
|
55
|
+
)
|
|
56
|
+
if len(p) < 2:
|
|
57
|
+
raise ValueError("At least 2 observations are required")
|
|
58
|
+
|
|
59
|
+
n = len(p)
|
|
60
|
+
mean_p = sum(p) / n
|
|
61
|
+
mean_b = sum(b) / n
|
|
62
|
+
|
|
63
|
+
try:
|
|
64
|
+
cov_pb = sum((p[i] - mean_p) * (b[i] - mean_b) for i in range(n)) / (n - 1)
|
|
65
|
+
var_b = sum((x - mean_b) ** 2 for x in b) / (n - 1)
|
|
66
|
+
var_p = sum((x - mean_p) ** 2 for x in p) / (n - 1)
|
|
67
|
+
except OverflowError:
|
|
68
|
+
raise ValueError("returns contain values too large to compute variance") from None
|
|
69
|
+
|
|
70
|
+
if var_b == 0.0:
|
|
71
|
+
raise ValueError("Benchmark returns have zero variance; beta is undefined")
|
|
72
|
+
|
|
73
|
+
beta = cov_pb / var_b
|
|
74
|
+
alpha_daily = mean_p - beta * mean_b
|
|
75
|
+
alpha = alpha_daily * 252 # annualize
|
|
76
|
+
|
|
77
|
+
std_p = math.sqrt(var_p) if var_p > 0 else 0.0
|
|
78
|
+
std_b = math.sqrt(var_b)
|
|
79
|
+
correlation = cov_pb / (std_p * std_b) if std_p > 0 else 0.0
|
|
80
|
+
# Clamp to [-1, 1] for floating-point safety
|
|
81
|
+
correlation = max(-1.0, min(1.0, correlation))
|
|
82
|
+
|
|
83
|
+
excess_return = (mean_p - mean_b) * 252 # annualized
|
|
84
|
+
|
|
85
|
+
diffs = [p[i] - b[i] for i in range(n)]
|
|
86
|
+
mean_diff = sum(diffs) / n
|
|
87
|
+
try:
|
|
88
|
+
var_diff = sum((d - mean_diff) ** 2 for d in diffs) / (n - 1)
|
|
89
|
+
except OverflowError:
|
|
90
|
+
raise ValueError("returns contain values too large to compute tracking error") from None
|
|
91
|
+
tracking_error = math.sqrt(var_diff) * math.sqrt(252) # annualized
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
"alpha": alpha,
|
|
95
|
+
"beta": beta,
|
|
96
|
+
"correlation": correlation,
|
|
97
|
+
"excess_return": excess_return,
|
|
98
|
+
"tracking_error": tracking_error,
|
|
99
|
+
}
|