finlearn-analytics 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.
- finlearn/__init__.py +32 -0
- finlearn/benchmarks.py +99 -0
- finlearn/biases.py +659 -0
- finlearn/memo.py +147 -0
- finlearn/metrics.py +100 -0
- finlearn/py.typed +0 -0
- finlearn/utils.py +40 -0
- finlearn_analytics-0.1.0.dist-info/METADATA +179 -0
- finlearn_analytics-0.1.0.dist-info/RECORD +12 -0
- finlearn_analytics-0.1.0.dist-info/WHEEL +5 -0
- finlearn_analytics-0.1.0.dist-info/licenses/LICENSE +21 -0
- finlearn_analytics-0.1.0.dist-info/top_level.txt +1 -0
finlearn/__init__.py
ADDED
|
@@ -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
|
+
]
|
finlearn/benchmarks.py
ADDED
|
@@ -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
|
+
}
|
finlearn/biases.py
ADDED
|
@@ -0,0 +1,659 @@
|
|
|
1
|
+
"""Behavioral-finance bias catalog and detector.
|
|
2
|
+
|
|
3
|
+
This module ships a catalog of 60+ specific behavioral and cognitive biases that
|
|
4
|
+
commonly distort investment decisions, plus a lightweight heuristic detector that
|
|
5
|
+
flags the linguistic fingerprints of those biases in free text (investment memos,
|
|
6
|
+
research notes, trade rationales, journal entries).
|
|
7
|
+
|
|
8
|
+
Detection is intentionally simple and dependency-free: each bias carries a set of
|
|
9
|
+
lowercase trigger phrases, and a phrase is "detected" when it appears as a
|
|
10
|
+
case-insensitive substring of the input text. It is a heuristic screen, not a
|
|
11
|
+
classifier — use it to surface candidate biases for human review.
|
|
12
|
+
|
|
13
|
+
Public API:
|
|
14
|
+
detect_biases(text) -> list of biases found, with the phrases that matched
|
|
15
|
+
analyze_biases(text) -> structured report (counts, categories, density, advice)
|
|
16
|
+
list_biases() -> metadata for every bias in the catalog
|
|
17
|
+
list_bias_categories() -> the distinct category labels
|
|
18
|
+
get_bias(key) -> full metadata (incl. phrases) for one bias
|
|
19
|
+
BIASES -> the immutable catalog tuple
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from dataclasses import dataclass
|
|
23
|
+
from typing import Dict, List, Tuple, Union
|
|
24
|
+
|
|
25
|
+
from .utils import validate_text
|
|
26
|
+
|
|
27
|
+
# Category labels grouping the biases by the cognitive mechanism they stem from.
|
|
28
|
+
CONFIDENCE = "Confidence & Self-Perception"
|
|
29
|
+
RISK = "Loss & Risk"
|
|
30
|
+
ANCHORING = "Anchoring & Adjustment"
|
|
31
|
+
INFORMATION = "Information Processing"
|
|
32
|
+
SOCIAL = "Social & Herding"
|
|
33
|
+
PROBABILITY = "Probability & Statistics"
|
|
34
|
+
FRAMING = "Framing & Accounting"
|
|
35
|
+
TEMPORAL = "Temporal & Planning"
|
|
36
|
+
EMOTIONAL = "Emotional & Affective"
|
|
37
|
+
ATTENTION = "Memory & Attention"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class BehavioralBias:
|
|
42
|
+
"""A single, specific behavioral-finance bias and its linguistic markers.
|
|
43
|
+
|
|
44
|
+
Attributes:
|
|
45
|
+
key: Stable snake_case identifier (unique across the catalog).
|
|
46
|
+
name: Human-readable name.
|
|
47
|
+
category: One of the module-level category labels.
|
|
48
|
+
description: One-sentence, finance-specific explanation of the bias.
|
|
49
|
+
phrases: Lowercase trigger phrases whose presence suggests the bias.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
key: str
|
|
53
|
+
name: str
|
|
54
|
+
category: str
|
|
55
|
+
description: str
|
|
56
|
+
phrases: Tuple[str, ...]
|
|
57
|
+
|
|
58
|
+
def find_matches(self, text_lower: str) -> List[str]:
|
|
59
|
+
"""Return the trigger phrases present in already-lowercased text."""
|
|
60
|
+
return [phrase for phrase in self.phrases if phrase in text_lower]
|
|
61
|
+
|
|
62
|
+
def as_metadata(self, include_phrases: bool = False) -> Dict[str, object]:
|
|
63
|
+
"""Return a JSON-friendly metadata dict for this bias."""
|
|
64
|
+
data: Dict[str, object] = {
|
|
65
|
+
"key": self.key,
|
|
66
|
+
"name": self.name,
|
|
67
|
+
"category": self.category,
|
|
68
|
+
"description": self.description,
|
|
69
|
+
}
|
|
70
|
+
if include_phrases:
|
|
71
|
+
data["phrases"] = list(self.phrases)
|
|
72
|
+
return data
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
76
|
+
# The catalog. 60 specific biases. Phrases MUST be lowercase (text is lowercased
|
|
77
|
+
# before matching). Keep keys and names unique.
|
|
78
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
79
|
+
BIASES: Tuple[BehavioralBias, ...] = (
|
|
80
|
+
# ── Confidence & Self-Perception ──────────────────────────────────────────
|
|
81
|
+
BehavioralBias(
|
|
82
|
+
"overconfidence", "Overconfidence Bias", CONFIDENCE,
|
|
83
|
+
"Overestimating the accuracy of one's own forecasts and the certainty of a positive outcome.",
|
|
84
|
+
("guaranteed", "certain to", "will definitely", "cannot fail", "can't fail",
|
|
85
|
+
"sure thing", "no doubt", "without a doubt", "can't go wrong", "slam dunk",
|
|
86
|
+
"easy money", "impossible to lose"),
|
|
87
|
+
),
|
|
88
|
+
BehavioralBias(
|
|
89
|
+
"overprecision", "Overprecision", CONFIDENCE,
|
|
90
|
+
"Stating point forecasts with unjustified precision, ignoring the wide range of possible outcomes.",
|
|
91
|
+
("will hit exactly", "exactly", "precisely", "to the dollar", "pinpoint",
|
|
92
|
+
"down to the cent", "will reach exactly"),
|
|
93
|
+
),
|
|
94
|
+
BehavioralBias(
|
|
95
|
+
"illusion_of_control", "Illusion of Control", CONFIDENCE,
|
|
96
|
+
"Believing one can control or reliably time outcomes that are largely random.",
|
|
97
|
+
("fully in control", "we control the", "control the outcome", "time the market",
|
|
98
|
+
"timing the market", "manage the risk away", "i can steer"),
|
|
99
|
+
),
|
|
100
|
+
BehavioralBias(
|
|
101
|
+
"optimism_bias", "Optimism Bias", CONFIDENCE,
|
|
102
|
+
"Systematically expecting favorable outcomes while underweighting the odds of things going wrong.",
|
|
103
|
+
("best case", "everything will go right", "only upside", "all upside",
|
|
104
|
+
"smooth sailing", "nothing but blue skies", "what could go wrong"),
|
|
105
|
+
),
|
|
106
|
+
BehavioralBias(
|
|
107
|
+
"self_attribution", "Self-Attribution Bias", CONFIDENCE,
|
|
108
|
+
"Crediting gains to one's own skill while blaming losses on bad luck or others.",
|
|
109
|
+
("due to my analysis", "because of my pick", "i called it", "thanks to my",
|
|
110
|
+
"proves i was right", "my skill", "i nailed it"),
|
|
111
|
+
),
|
|
112
|
+
BehavioralBias(
|
|
113
|
+
"dunning_kruger", "Dunning-Kruger Effect", CONFIDENCE,
|
|
114
|
+
"Limited expertise breeding inflated confidence about how easy the analysis is.",
|
|
115
|
+
("simple to understand", "anyone can see", "it's obvious", "easy to predict",
|
|
116
|
+
"no expertise needed", "not rocket science"),
|
|
117
|
+
),
|
|
118
|
+
BehavioralBias(
|
|
119
|
+
"restraint_bias", "Restraint Bias", CONFIDENCE,
|
|
120
|
+
"Overestimating one's ability to stay disciplined and resist impulsive selling or buying.",
|
|
121
|
+
("i can stay disciplined", "won't panic sell", "can resist the urge",
|
|
122
|
+
"i'll be rational", "i won't get emotional", "i can hold through anything"),
|
|
123
|
+
),
|
|
124
|
+
|
|
125
|
+
# ── Loss & Risk ───────────────────────────────────────────────────────────
|
|
126
|
+
BehavioralBias(
|
|
127
|
+
"loss_aversion", "Loss Aversion", RISK,
|
|
128
|
+
"Feeling the pain of losses far more than the pleasure of equivalent gains.",
|
|
129
|
+
("can't afford to lose", "avoid any loss", "refuse to sell at a loss",
|
|
130
|
+
"hate losing", "protect against any loss", "never take a loss"),
|
|
131
|
+
),
|
|
132
|
+
BehavioralBias(
|
|
133
|
+
"disposition_effect", "Disposition Effect", RISK,
|
|
134
|
+
"Selling winners too early to lock in gains while holding losers hoping to break even.",
|
|
135
|
+
("lock in gains now", "sell the winner", "hold until it recovers",
|
|
136
|
+
"wait for it to break even", "ride the loser", "let the winner go but keep"),
|
|
137
|
+
),
|
|
138
|
+
BehavioralBias(
|
|
139
|
+
"sunk_cost", "Sunk Cost Fallacy", RISK,
|
|
140
|
+
"Continuing a losing position because of resources already committed rather than future merit.",
|
|
141
|
+
("already invested too much", "can't back out now", "we've come too far",
|
|
142
|
+
"throwing away what we put in", "doubling down to recover", "in too deep"),
|
|
143
|
+
),
|
|
144
|
+
BehavioralBias(
|
|
145
|
+
"regret_aversion", "Regret Aversion", RISK,
|
|
146
|
+
"Avoiding decisions that could later feel regrettable, even when they are sound.",
|
|
147
|
+
("would regret missing", "don't want to regret", "avoid the regret",
|
|
148
|
+
"fear of regret", "can't risk the regret", "hate to look back and"),
|
|
149
|
+
),
|
|
150
|
+
BehavioralBias(
|
|
151
|
+
"zero_risk_bias", "Zero-Risk Bias", RISK,
|
|
152
|
+
"Overvaluing the complete elimination of one small risk over a larger reduction of overall risk.",
|
|
153
|
+
("completely safe", "zero risk", "risk-free", "no downside",
|
|
154
|
+
"eliminate all risk", "totally secure", "absolutely no risk"),
|
|
155
|
+
),
|
|
156
|
+
BehavioralBias(
|
|
157
|
+
"ambiguity_aversion", "Ambiguity Aversion", RISK,
|
|
158
|
+
"Preferring known risks over unknown ones, avoiding opportunities that are hard to quantify.",
|
|
159
|
+
("too uncertain", "avoid the unknown", "can't quantify so avoid",
|
|
160
|
+
"stick to what we know", "too murky", "prefer the familiar bet"),
|
|
161
|
+
),
|
|
162
|
+
BehavioralBias(
|
|
163
|
+
"endowment_effect", "Endowment Effect", RISK,
|
|
164
|
+
"Valuing an asset more highly simply because one already owns it.",
|
|
165
|
+
("our position is worth more", "we own it so", "won't sell below cost",
|
|
166
|
+
"it's worth more to us", "wouldn't buy it today but won't sell"),
|
|
167
|
+
),
|
|
168
|
+
BehavioralBias(
|
|
169
|
+
"status_quo_bias", "Status Quo Bias", RISK,
|
|
170
|
+
"Defaulting to the current allocation and resisting change even when rebalancing is warranted.",
|
|
171
|
+
("keep things as they are", "no need to change", "leave it as is",
|
|
172
|
+
"stay the course", "why change now", "don't rock the boat"),
|
|
173
|
+
),
|
|
174
|
+
BehavioralBias(
|
|
175
|
+
"ostrich_effect", "Ostrich Effect", RISK,
|
|
176
|
+
"Avoiding negative information, such as not checking a portfolio during a drawdown.",
|
|
177
|
+
("ignore the bad news", "don't look at the losses", "avoid checking",
|
|
178
|
+
"head in the sand", "stop watching the account", "rather not know"),
|
|
179
|
+
),
|
|
180
|
+
|
|
181
|
+
# ── Anchoring & Adjustment ────────────────────────────────────────────────
|
|
182
|
+
BehavioralBias(
|
|
183
|
+
"anchoring", "Anchoring Bias", ANCHORING,
|
|
184
|
+
"Over-relying on the first number seen (an initial price or estimate) as a reference point.",
|
|
185
|
+
("anchored to", "based on the initial price", "relative to the 52-week high",
|
|
186
|
+
"starting from the original", "the reference price of", "first quoted at"),
|
|
187
|
+
),
|
|
188
|
+
BehavioralBias(
|
|
189
|
+
"purchase_price_anchoring", "Purchase-Price Anchoring", ANCHORING,
|
|
190
|
+
"Fixating on the price originally paid when judging whether to hold or sell.",
|
|
191
|
+
("we paid", "our cost basis", "below what we bought", "get back to our entry",
|
|
192
|
+
"break even on our purchase", "what i paid for it"),
|
|
193
|
+
),
|
|
194
|
+
BehavioralBias(
|
|
195
|
+
"round_number_bias", "Round-Number Bias", ANCHORING,
|
|
196
|
+
"Treating psychologically round price levels as meaningful targets or barriers.",
|
|
197
|
+
("nice round number", "psychological level", "round figure",
|
|
198
|
+
"the 100 level", "the 1000 level", "big round number"),
|
|
199
|
+
),
|
|
200
|
+
BehavioralBias(
|
|
201
|
+
"conservatism_bias", "Conservatism Bias", ANCHORING,
|
|
202
|
+
"Under-reacting to new evidence and revising prior beliefs too slowly.",
|
|
203
|
+
("stick with the original estimate", "no need to update", "the old forecast still holds",
|
|
204
|
+
"slow to revise", "wait and see before changing", "let's not overreact to the news"),
|
|
205
|
+
),
|
|
206
|
+
BehavioralBias(
|
|
207
|
+
"analyst_target_anchoring", "Analyst-Target Anchoring", ANCHORING,
|
|
208
|
+
"Anchoring valuation judgments to published analyst price targets rather than independent analysis.",
|
|
209
|
+
("the price target is", "analysts peg it at", "street target of",
|
|
210
|
+
"consensus target", "the analyst target says"),
|
|
211
|
+
),
|
|
212
|
+
|
|
213
|
+
# ── Information Processing ─────────────────────────────────────────────────
|
|
214
|
+
BehavioralBias(
|
|
215
|
+
"confirmation_bias", "Confirmation Bias", INFORMATION,
|
|
216
|
+
"Seeking and weighting evidence that supports a pre-existing thesis while discounting the rest.",
|
|
217
|
+
("confirms my view", "supports our thesis", "as i expected", "consistent with what i believed",
|
|
218
|
+
"ignore the contrary", "proves my point", "just as i thought"),
|
|
219
|
+
),
|
|
220
|
+
BehavioralBias(
|
|
221
|
+
"selective_perception", "Selective Perception", INFORMATION,
|
|
222
|
+
"Noticing only the data that fits one's expectations and filtering out the rest.",
|
|
223
|
+
("only the data that fits", "focus on the supportive", "disregard the rest",
|
|
224
|
+
"cherry-pick", "cherry pick", "ignore what doesn't fit"),
|
|
225
|
+
),
|
|
226
|
+
BehavioralBias(
|
|
227
|
+
"availability_heuristic", "Availability Heuristic", INFORMATION,
|
|
228
|
+
"Judging likelihood by how easily examples come to mind, e.g., recent headlines.",
|
|
229
|
+
("i just read", "in the news lately", "recent headlines", "top of mind",
|
|
230
|
+
"everyone is talking about", "all over the media"),
|
|
231
|
+
),
|
|
232
|
+
BehavioralBias(
|
|
233
|
+
"recency_bias", "Recency Bias", INFORMATION,
|
|
234
|
+
"Overweighting the most recent results and assuming the latest trend will persist.",
|
|
235
|
+
("based on last quarter", "recent trend will continue", "latest results show it will",
|
|
236
|
+
"just kept going up", "momentum will persist", "the last few months prove"),
|
|
237
|
+
),
|
|
238
|
+
BehavioralBias(
|
|
239
|
+
"base_rate_neglect", "Base-Rate Neglect", INFORMATION,
|
|
240
|
+
"Ignoring the underlying statistical base rate in favor of specific, vivid case details.",
|
|
241
|
+
("ignore the average", "the odds don't apply here", "forget the historical rate",
|
|
242
|
+
"this is a unique situation", "stats don't apply", "different this time"),
|
|
243
|
+
),
|
|
244
|
+
BehavioralBias(
|
|
245
|
+
"representativeness", "Representativeness Heuristic", INFORMATION,
|
|
246
|
+
"Judging an opportunity by how much it resembles a stereotype, e.g., 'the next big winner'.",
|
|
247
|
+
("the next amazon", "the next apple", "looks just like", "reminds me of the last winner",
|
|
248
|
+
"fits the pattern of", "just like the last winner"),
|
|
249
|
+
),
|
|
250
|
+
BehavioralBias(
|
|
251
|
+
"narrative_fallacy", "Narrative Fallacy", INFORMATION,
|
|
252
|
+
"Buying into a compelling story while neglecting whether the numbers support it.",
|
|
253
|
+
("the story makes sense", "compelling narrative", "it all fits the story",
|
|
254
|
+
"great story stock", "such a good story", "the narrative is too good"),
|
|
255
|
+
),
|
|
256
|
+
BehavioralBias(
|
|
257
|
+
"hindsight_bias", "Hindsight Bias", INFORMATION,
|
|
258
|
+
"Believing past events were obvious and predictable after the fact.",
|
|
259
|
+
("i knew it all along", "obvious in retrospect", "saw it coming",
|
|
260
|
+
"predictable in hindsight", "should have known", "knew this would happen"),
|
|
261
|
+
),
|
|
262
|
+
BehavioralBias(
|
|
263
|
+
"survivorship_bias", "Survivorship Bias", INFORMATION,
|
|
264
|
+
"Drawing conclusions only from winners while ignoring the failures that dropped out.",
|
|
265
|
+
("look at the winners", "the ones that succeeded", "ignore the failures",
|
|
266
|
+
"only the survivors", "all the success stories"),
|
|
267
|
+
),
|
|
268
|
+
BehavioralBias(
|
|
269
|
+
"clustering_illusion", "Clustering Illusion", INFORMATION,
|
|
270
|
+
"Perceiving meaningful patterns or streaks in what is actually random price noise.",
|
|
271
|
+
("clear pattern in the chart", "the streak proves", "hot streak",
|
|
272
|
+
"obvious pattern", "connected for a reason", "the chart is forming a"),
|
|
273
|
+
),
|
|
274
|
+
BehavioralBias(
|
|
275
|
+
"curse_of_knowledge", "Curse of Knowledge", INFORMATION,
|
|
276
|
+
"Assuming others share one's information, so it must already be reflected in the price.",
|
|
277
|
+
("everyone already knows", "common knowledge", "already priced in",
|
|
278
|
+
"the market knows this already", "obviously everyone knows"),
|
|
279
|
+
),
|
|
280
|
+
BehavioralBias(
|
|
281
|
+
"outcome_bias", "Outcome Bias", INFORMATION,
|
|
282
|
+
"Judging a decision by its result rather than the quality of the reasoning at the time.",
|
|
283
|
+
("it worked so it was right", "good result proves", "judge by the outcome",
|
|
284
|
+
"the ends justify the pick", "made money so it was a good call"),
|
|
285
|
+
),
|
|
286
|
+
BehavioralBias(
|
|
287
|
+
"information_bias", "Information Bias", INFORMATION,
|
|
288
|
+
"Seeking more data than is useful, believing extra information always improves the decision.",
|
|
289
|
+
("need more data before", "just one more report", "keep researching",
|
|
290
|
+
"more analysis needed", "wait for more information", "analysis paralysis"),
|
|
291
|
+
),
|
|
292
|
+
|
|
293
|
+
# ── Social & Herding ──────────────────────────────────────────────────────
|
|
294
|
+
BehavioralBias(
|
|
295
|
+
"herding", "Herding Bias", SOCIAL,
|
|
296
|
+
"Following the crowd's trades instead of independent analysis.",
|
|
297
|
+
("everyone is buying", "the crowd is", "following the smart money",
|
|
298
|
+
"join the herd", "everybody owns it", "all the funds are in"),
|
|
299
|
+
),
|
|
300
|
+
BehavioralBias(
|
|
301
|
+
"bandwagon_effect", "Bandwagon Effect", SOCIAL,
|
|
302
|
+
"Adopting a position because it is popular and gaining momentum.",
|
|
303
|
+
("jumping on the bandwagon", "getting in while it's hot", "don't miss the wave",
|
|
304
|
+
"ride the hype", "everyone's piling in"),
|
|
305
|
+
),
|
|
306
|
+
BehavioralBias(
|
|
307
|
+
"fomo", "Fear of Missing Out (FOMO)", SOCIAL,
|
|
308
|
+
"Buying out of anxiety about missing further gains rather than a reasoned valuation.",
|
|
309
|
+
("can't miss this", "fear of missing out", "fomo", "last chance to get in",
|
|
310
|
+
"before it's too late", "missing the boat", "everyone's getting rich but me"),
|
|
311
|
+
),
|
|
312
|
+
BehavioralBias(
|
|
313
|
+
"authority_bias", "Authority Bias", SOCIAL,
|
|
314
|
+
"Deferring to a perceived expert or celebrity investor instead of evaluating the case.",
|
|
315
|
+
("the expert said", "the analyst recommends so", "the guru endorsed",
|
|
316
|
+
"because warren buffett", "the ceo promised", "a famous investor bought"),
|
|
317
|
+
),
|
|
318
|
+
BehavioralBias(
|
|
319
|
+
"halo_effect", "Halo Effect", SOCIAL,
|
|
320
|
+
"Letting a positive impression of a brand or CEO spill over into the stock's expected return.",
|
|
321
|
+
("great brand so great stock", "good management means", "because it's a beloved company",
|
|
322
|
+
"the brand is loved so", "such a great product so the stock"),
|
|
323
|
+
),
|
|
324
|
+
BehavioralBias(
|
|
325
|
+
"home_bias", "Home Bias", SOCIAL,
|
|
326
|
+
"Over-allocating to domestic assets and underweighting foreign opportunities.",
|
|
327
|
+
("prefer domestic", "stick to local companies", "only invest at home",
|
|
328
|
+
"avoid foreign markets", "keep it in our own country"),
|
|
329
|
+
),
|
|
330
|
+
BehavioralBias(
|
|
331
|
+
"familiarity_bias", "Familiarity Bias", SOCIAL,
|
|
332
|
+
"Favoring well-known names simply because they feel comfortable and recognizable.",
|
|
333
|
+
("i use their products", "a company i know", "familiar name",
|
|
334
|
+
"brands i recognize", "stick to names i know"),
|
|
335
|
+
),
|
|
336
|
+
BehavioralBias(
|
|
337
|
+
"in_group_bias", "In-Group Bias", SOCIAL,
|
|
338
|
+
"Favoring companies tied to one's own group, region, employer, or community.",
|
|
339
|
+
("companies like us", "our kind of business", "founders like me",
|
|
340
|
+
"our community's pick", "people like us back this"),
|
|
341
|
+
),
|
|
342
|
+
BehavioralBias(
|
|
343
|
+
"commitment_bias", "Commitment & Consistency Bias", SOCIAL,
|
|
344
|
+
"Sticking to a public position to appear consistent, even as evidence turns.",
|
|
345
|
+
("i committed publicly", "stand by my call", "won't flip-flop",
|
|
346
|
+
"consistent with my prior", "i already told everyone", "can't reverse now"),
|
|
347
|
+
),
|
|
348
|
+
|
|
349
|
+
# ── Probability & Statistics ──────────────────────────────────────────────
|
|
350
|
+
BehavioralBias(
|
|
351
|
+
"gamblers_fallacy", "Gambler's Fallacy", PROBABILITY,
|
|
352
|
+
"Believing a reversal is 'due' after a run, as if independent moves must balance out.",
|
|
353
|
+
("due for a rebound", "has to go up now", "overdue for a bounce",
|
|
354
|
+
"can't keep falling", "law of averages says", "due for a reversal"),
|
|
355
|
+
),
|
|
356
|
+
BehavioralBias(
|
|
357
|
+
"hot_hand_fallacy", "Hot-Hand Fallacy", PROBABILITY,
|
|
358
|
+
"Expecting a winning streak to continue because recent picks worked out.",
|
|
359
|
+
("on a winning streak", "can't lose right now", "riding hot",
|
|
360
|
+
"keeps winning so will continue", "i'm on a roll"),
|
|
361
|
+
),
|
|
362
|
+
BehavioralBias(
|
|
363
|
+
"probability_neglect", "Probability Neglect", PROBABILITY,
|
|
364
|
+
"Fixating on the size of a potential payoff while ignoring how unlikely it is.",
|
|
365
|
+
("focus on the payoff not the odds", "ignore the probability", "the prize is huge",
|
|
366
|
+
"doesn't matter how unlikely", "the payoff is what matters"),
|
|
367
|
+
),
|
|
368
|
+
BehavioralBias(
|
|
369
|
+
"conjunction_fallacy", "Conjunction Fallacy", PROBABILITY,
|
|
370
|
+
"Judging a detailed, specific scenario as more likely than a broader one it is part of.",
|
|
371
|
+
("both will happen together", "all of these at once", "the perfect combination of events",
|
|
372
|
+
"every one of these has to line up"),
|
|
373
|
+
),
|
|
374
|
+
BehavioralBias(
|
|
375
|
+
"disaster_myopia", "Disaster Myopia", PROBABILITY,
|
|
376
|
+
"Underestimating the odds of rare crashes because none has happened recently.",
|
|
377
|
+
("hasn't crashed in years", "tail risk won't happen", "ignore the black swan",
|
|
378
|
+
"crashes are rare so", "it can't happen here", "nothing ever goes to zero"),
|
|
379
|
+
),
|
|
380
|
+
BehavioralBias(
|
|
381
|
+
"pseudocertainty", "Pseudocertainty Effect", PROBABILITY,
|
|
382
|
+
"Treating a highly probable outcome as if it were a sure thing.",
|
|
383
|
+
("virtually certain", "as good as guaranteed", "practically sure",
|
|
384
|
+
"almost no chance of loss", "all but certain"),
|
|
385
|
+
),
|
|
386
|
+
BehavioralBias(
|
|
387
|
+
"ludic_fallacy", "Ludic Fallacy", PROBABILITY,
|
|
388
|
+
"Modeling messy markets with the tidy, known odds of a game and ignoring model risk.",
|
|
389
|
+
("the model says it's safe", "the backtest proves", "monte carlo guarantees",
|
|
390
|
+
"the simulation says", "the math says it can't"),
|
|
391
|
+
),
|
|
392
|
+
|
|
393
|
+
# ── Framing & Accounting ──────────────────────────────────────────────────
|
|
394
|
+
BehavioralBias(
|
|
395
|
+
"framing_effect", "Framing Effect", FRAMING,
|
|
396
|
+
"Reacting to how a fact is worded rather than its substance, e.g., 90% success vs 10% failure.",
|
|
397
|
+
("90% success rate", "only a 10% chance of loss", "glass half full",
|
|
398
|
+
"sounds better as", "it's a win rate of", "framed the right way"),
|
|
399
|
+
),
|
|
400
|
+
BehavioralBias(
|
|
401
|
+
"mental_accounting", "Mental Accounting", FRAMING,
|
|
402
|
+
"Treating money differently based on arbitrary mental buckets like 'house money'.",
|
|
403
|
+
("house money", "play money", "separate bucket", "this is my fun money",
|
|
404
|
+
"found money", "it's only my gambling pot"),
|
|
405
|
+
),
|
|
406
|
+
BehavioralBias(
|
|
407
|
+
"money_illusion", "Money Illusion", FRAMING,
|
|
408
|
+
"Focusing on nominal dollar figures while ignoring the effect of inflation on real returns.",
|
|
409
|
+
("nominal gains", "ignoring inflation", "the number is bigger",
|
|
410
|
+
"doubled in dollars", "more dollars so richer"),
|
|
411
|
+
),
|
|
412
|
+
BehavioralBias(
|
|
413
|
+
"denomination_effect", "Denomination Effect", FRAMING,
|
|
414
|
+
"Treating a low per-share price as 'cheap' regardless of valuation.",
|
|
415
|
+
("it's only pennies a share", "cheap at this price", "low share price so cheap",
|
|
416
|
+
"penny stock so room to run", "so cheap per share"),
|
|
417
|
+
),
|
|
418
|
+
BehavioralBias(
|
|
419
|
+
"default_effect", "Default Effect", FRAMING,
|
|
420
|
+
"Accepting the preset or default option instead of an active, considered choice.",
|
|
421
|
+
("just go with the default", "the standard allocation", "whatever's preset",
|
|
422
|
+
"the recommended option", "leave it on default"),
|
|
423
|
+
),
|
|
424
|
+
BehavioralBias(
|
|
425
|
+
"anchoring_to_targets", "Goal-Anchoring Bias", FRAMING,
|
|
426
|
+
"Framing decisions around hitting a self-set dollar goal rather than risk-adjusted merit.",
|
|
427
|
+
("need to hit my number", "until i reach my goal of", "once i make my target",
|
|
428
|
+
"just need to get to", "my goal is exactly"),
|
|
429
|
+
),
|
|
430
|
+
|
|
431
|
+
# ── Temporal & Planning ───────────────────────────────────────────────────
|
|
432
|
+
BehavioralBias(
|
|
433
|
+
"present_bias", "Present Bias (Hyperbolic Discounting)", TEMPORAL,
|
|
434
|
+
"Overweighting immediate payoffs and undervaluing larger but delayed gains.",
|
|
435
|
+
("want returns now", "immediate payoff", "can't wait for the long term",
|
|
436
|
+
"quick gains", "instant gratification", "need it to pay off fast"),
|
|
437
|
+
),
|
|
438
|
+
BehavioralBias(
|
|
439
|
+
"planning_fallacy", "Planning Fallacy", TEMPORAL,
|
|
440
|
+
"Expecting projects and catalysts to land on time despite a track record of delays.",
|
|
441
|
+
("will be done on time", "no delays expected", "ahead of schedule",
|
|
442
|
+
"everything is on track", "faster than expected", "they always ship on time"),
|
|
443
|
+
),
|
|
444
|
+
BehavioralBias(
|
|
445
|
+
"projection_bias", "Projection Bias", TEMPORAL,
|
|
446
|
+
"Assuming current conditions, tastes, or moods will persist unchanged into the future.",
|
|
447
|
+
("current conditions will last", "today's demand will continue forever",
|
|
448
|
+
"extrapolate the present", "this will always be in demand", "the boom will last forever"),
|
|
449
|
+
),
|
|
450
|
+
BehavioralBias(
|
|
451
|
+
"extrapolation_bias", "Extrapolation Bias", TEMPORAL,
|
|
452
|
+
"Projecting a recent growth rate far into the future without mean reversion.",
|
|
453
|
+
("grows forever", "keeps compounding at this rate", "straight line up",
|
|
454
|
+
"this growth is permanent", "will keep doubling", "up and to the right forever"),
|
|
455
|
+
),
|
|
456
|
+
|
|
457
|
+
# ── Emotional & Affective ─────────────────────────────────────────────────
|
|
458
|
+
BehavioralBias(
|
|
459
|
+
"affect_heuristic", "Affect Heuristic", EMOTIONAL,
|
|
460
|
+
"Letting an emotional 'feel' about a stock substitute for analysis of its fundamentals.",
|
|
461
|
+
("i love this company", "feels right", "my gut tells me", "exciting opportunity",
|
|
462
|
+
"just feels good", "in love with the stock"),
|
|
463
|
+
),
|
|
464
|
+
BehavioralBias(
|
|
465
|
+
"wishful_thinking", "Wishful Thinking", EMOTIONAL,
|
|
466
|
+
"Letting hopes about an outcome drive the forecast instead of evidence.",
|
|
467
|
+
("hope it goes up", "i wish", "fingers crossed", "praying it works",
|
|
468
|
+
"hopefully it recovers", "i really need this to work"),
|
|
469
|
+
),
|
|
470
|
+
BehavioralBias(
|
|
471
|
+
"negativity_bias", "Negativity Bias", EMOTIONAL,
|
|
472
|
+
"Giving disproportionate weight to bad news and downside scenarios.",
|
|
473
|
+
("focus on the bad news", "dwell on the risks", "only see downside",
|
|
474
|
+
"catastrophizing", "everything is going to crash", "it's all falling apart"),
|
|
475
|
+
),
|
|
476
|
+
BehavioralBias(
|
|
477
|
+
"panic_selling", "Panic-Driven Action", EMOTIONAL,
|
|
478
|
+
"Reacting to fear or euphoria with abrupt trades rather than a plan.",
|
|
479
|
+
("get me out now", "sell everything", "dump it all", "buy before it runs away",
|
|
480
|
+
"i can't take it anymore", "pull the plug right now"),
|
|
481
|
+
),
|
|
482
|
+
BehavioralBias(
|
|
483
|
+
"euphoria_bias", "Euphoria Bias", EMOTIONAL,
|
|
484
|
+
"Letting market exuberance inflate risk-taking and return expectations.",
|
|
485
|
+
("this time is different", "new paradigm", "to the moon", "can only go up",
|
|
486
|
+
"the sky's the limit", "we're all going to be rich"),
|
|
487
|
+
),
|
|
488
|
+
|
|
489
|
+
# ── Memory & Attention ────────────────────────────────────────────────────
|
|
490
|
+
BehavioralBias(
|
|
491
|
+
"salience_bias", "Salience Bias", ATTENTION,
|
|
492
|
+
"Letting the most vivid or dramatic figure dominate attention over more relevant data.",
|
|
493
|
+
("the headline number", "eye-catching figure", "the dramatic number",
|
|
494
|
+
"stands out so it must matter", "the big flashy stat"),
|
|
495
|
+
),
|
|
496
|
+
BehavioralBias(
|
|
497
|
+
"attentional_bias", "Attentional Bias", ATTENTION,
|
|
498
|
+
"Fixating on a single metric or ticker to the exclusion of the broader picture.",
|
|
499
|
+
("can't stop watching", "fixated on", "glued to the ticker",
|
|
500
|
+
"obsessing over", "checking it every minute", "staring at the price all day"),
|
|
501
|
+
),
|
|
502
|
+
BehavioralBias(
|
|
503
|
+
"recency_of_news", "News-Recency Bias", ATTENTION,
|
|
504
|
+
"Letting the latest single news item drive a decision out of proportion to its importance.",
|
|
505
|
+
("because of today's news", "after this morning's headline", "this one article says",
|
|
506
|
+
"the latest tweet", "breaking news so i'm acting"),
|
|
507
|
+
),
|
|
508
|
+
BehavioralBias(
|
|
509
|
+
"anchoring_to_highs", "High-Water-Mark Fixation", ATTENTION,
|
|
510
|
+
"Fixating on a prior peak price as the 'real' value the asset should return to.",
|
|
511
|
+
("get back to its high", "it was worth more before", "down from its peak so it's cheap",
|
|
512
|
+
"used to trade at", "back to all-time highs"),
|
|
513
|
+
),
|
|
514
|
+
)
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
# Fast lookup by key. Also enforces uniqueness at import time.
|
|
518
|
+
def _build_index() -> Dict[str, BehavioralBias]:
|
|
519
|
+
index: Dict[str, BehavioralBias] = {}
|
|
520
|
+
seen_names = set()
|
|
521
|
+
for bias in BIASES:
|
|
522
|
+
if bias.key in index:
|
|
523
|
+
raise RuntimeError(f"Duplicate bias key in catalog: {bias.key!r}")
|
|
524
|
+
if bias.name in seen_names:
|
|
525
|
+
raise RuntimeError(f"Duplicate bias name in catalog: {bias.name!r}")
|
|
526
|
+
if not bias.phrases:
|
|
527
|
+
raise RuntimeError(f"Bias {bias.key!r} has no trigger phrases")
|
|
528
|
+
for phrase in bias.phrases:
|
|
529
|
+
if phrase != phrase.lower():
|
|
530
|
+
raise RuntimeError(
|
|
531
|
+
f"Bias {bias.key!r} has non-lowercase phrase {phrase!r}; "
|
|
532
|
+
"phrases must be lowercase for case-insensitive matching"
|
|
533
|
+
)
|
|
534
|
+
index[bias.key] = bias
|
|
535
|
+
seen_names.add(bias.name)
|
|
536
|
+
return index
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
_BIAS_BY_KEY: Dict[str, BehavioralBias] = _build_index()
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
def detect_biases(text: str) -> List[Dict[str, object]]:
|
|
543
|
+
"""Detect behavioral biases whose linguistic markers appear in ``text``.
|
|
544
|
+
|
|
545
|
+
Args:
|
|
546
|
+
text: Free text to screen (e.g., an investment memo or trade rationale).
|
|
547
|
+
|
|
548
|
+
Returns:
|
|
549
|
+
A list of dicts, one per detected bias, each with keys ``key``, ``name``,
|
|
550
|
+
``category``, ``description``, and ``matched_phrases`` (the trigger phrases
|
|
551
|
+
that fired). The list is ordered by the catalog order. Empty if nothing fired.
|
|
552
|
+
|
|
553
|
+
Raises:
|
|
554
|
+
TypeError: If ``text`` is not a string.
|
|
555
|
+
ValueError: If ``text`` is empty or whitespace-only.
|
|
556
|
+
|
|
557
|
+
Example:
|
|
558
|
+
>>> hits = detect_biases("This is guaranteed to work, the next amazon!")
|
|
559
|
+
>>> sorted(h["key"] for h in hits)
|
|
560
|
+
['overconfidence', 'representativeness']
|
|
561
|
+
"""
|
|
562
|
+
validated = validate_text(text, "text")
|
|
563
|
+
text_lower = validated.lower()
|
|
564
|
+
|
|
565
|
+
detected: List[Dict[str, object]] = []
|
|
566
|
+
for bias in BIASES:
|
|
567
|
+
matched = bias.find_matches(text_lower)
|
|
568
|
+
if matched:
|
|
569
|
+
entry = bias.as_metadata()
|
|
570
|
+
entry["matched_phrases"] = matched
|
|
571
|
+
detected.append(entry)
|
|
572
|
+
return detected
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def analyze_biases(text: str) -> Dict[str, Union[int, float, str, List, Dict]]:
|
|
576
|
+
"""Produce a structured behavioral-bias report for a block of text.
|
|
577
|
+
|
|
578
|
+
Args:
|
|
579
|
+
text: Free text to analyze.
|
|
580
|
+
|
|
581
|
+
Returns:
|
|
582
|
+
Dictionary with the following keys:
|
|
583
|
+
- bias_count (int): Number of distinct biases detected.
|
|
584
|
+
- biases_detected (list[str]): Keys of the detected biases.
|
|
585
|
+
- by_category (dict[str, list[str]]): Detected bias keys grouped by category.
|
|
586
|
+
- details (list[dict]): Full per-bias detail (same shape as detect_biases).
|
|
587
|
+
- bias_density_per_100_words (float): Detected biases per 100 words.
|
|
588
|
+
- recommendation (str): Plain-English guidance based on the findings.
|
|
589
|
+
|
|
590
|
+
Raises:
|
|
591
|
+
TypeError: If ``text`` is not a string.
|
|
592
|
+
ValueError: If ``text`` is empty or whitespace-only.
|
|
593
|
+
"""
|
|
594
|
+
validated = validate_text(text, "text")
|
|
595
|
+
details = detect_biases(validated)
|
|
596
|
+
|
|
597
|
+
word_count = len(validated.split())
|
|
598
|
+
by_category: Dict[str, List[str]] = {}
|
|
599
|
+
for entry in details:
|
|
600
|
+
by_category.setdefault(str(entry["category"]), []).append(str(entry["key"]))
|
|
601
|
+
|
|
602
|
+
bias_count = len(details)
|
|
603
|
+
density = round(bias_count / word_count * 100, 2) if word_count else 0.0
|
|
604
|
+
|
|
605
|
+
if bias_count == 0:
|
|
606
|
+
recommendation = (
|
|
607
|
+
"No behavioral-bias language detected. The text reads neutrally; "
|
|
608
|
+
"continue to support claims with data."
|
|
609
|
+
)
|
|
610
|
+
else:
|
|
611
|
+
top_categories = sorted(by_category, key=lambda c: len(by_category[c]), reverse=True)
|
|
612
|
+
lead = top_categories[0]
|
|
613
|
+
recommendation = (
|
|
614
|
+
f"Detected {bias_count} potential bias signal(s), concentrated in "
|
|
615
|
+
f"'{lead}'. Review flagged language and pressure-test each claim against "
|
|
616
|
+
"base rates and disconfirming evidence."
|
|
617
|
+
)
|
|
618
|
+
|
|
619
|
+
return {
|
|
620
|
+
"bias_count": bias_count,
|
|
621
|
+
"biases_detected": [str(e["key"]) for e in details],
|
|
622
|
+
"by_category": by_category,
|
|
623
|
+
"details": details,
|
|
624
|
+
"bias_density_per_100_words": density,
|
|
625
|
+
"recommendation": recommendation,
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def list_biases() -> List[Dict[str, str]]:
|
|
630
|
+
"""Return metadata (key, name, category, description) for every bias in the catalog."""
|
|
631
|
+
return [bias.as_metadata() for bias in BIASES] # type: ignore[misc]
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def list_bias_categories() -> List[str]:
|
|
635
|
+
"""Return the distinct bias category labels, sorted alphabetically."""
|
|
636
|
+
return sorted({bias.category for bias in BIASES})
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
def get_bias(key: str) -> Dict[str, object]:
|
|
640
|
+
"""Return full metadata (including trigger phrases) for a single bias.
|
|
641
|
+
|
|
642
|
+
Args:
|
|
643
|
+
key: The snake_case identifier of the bias (see ``list_biases``).
|
|
644
|
+
|
|
645
|
+
Returns:
|
|
646
|
+
Dict with keys ``key``, ``name``, ``category``, ``description``, ``phrases``.
|
|
647
|
+
|
|
648
|
+
Raises:
|
|
649
|
+
TypeError: If ``key`` is not a string.
|
|
650
|
+
ValueError: If ``key`` does not match any bias in the catalog.
|
|
651
|
+
"""
|
|
652
|
+
if not isinstance(key, str):
|
|
653
|
+
raise TypeError(f"key must be a string, got {type(key).__name__}")
|
|
654
|
+
bias = _BIAS_BY_KEY.get(key)
|
|
655
|
+
if bias is None:
|
|
656
|
+
raise ValueError(
|
|
657
|
+
f"Unknown bias key: {key!r}. Use list_biases() to see the {len(BIASES)} available keys."
|
|
658
|
+
)
|
|
659
|
+
return bias.as_metadata(include_phrases=True)
|
finlearn/memo.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Behavioral finance memo quality analyzer."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from typing import Dict, List, Union
|
|
5
|
+
|
|
6
|
+
from .utils import validate_text
|
|
7
|
+
from .biases import detect_biases
|
|
8
|
+
|
|
9
|
+
# Phrases associated with overconfidence bias in investment memos
|
|
10
|
+
_OVERCONFIDENCE_PHRASES = [
|
|
11
|
+
"guaranteed",
|
|
12
|
+
"certain to",
|
|
13
|
+
"will definitely",
|
|
14
|
+
"no risk",
|
|
15
|
+
"risk-free",
|
|
16
|
+
"100%",
|
|
17
|
+
"cannot fail",
|
|
18
|
+
"sure thing",
|
|
19
|
+
"obvious",
|
|
20
|
+
"clearly will",
|
|
21
|
+
"without a doubt",
|
|
22
|
+
"no doubt",
|
|
23
|
+
"impossible to lose",
|
|
24
|
+
"can't go wrong",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
# Simple positive/negative word lists for lightweight sentiment scoring
|
|
28
|
+
_POSITIVE_WORDS = {
|
|
29
|
+
"growth", "profit", "gain", "strong", "outperform", "increase", "positive",
|
|
30
|
+
"upside", "opportunity", "bullish", "recover", "improve", "robust", "solid",
|
|
31
|
+
"momentum", "surge", "rally", "exceed", "beat", "favorable",
|
|
32
|
+
}
|
|
33
|
+
_NEGATIVE_WORDS = {
|
|
34
|
+
"loss", "decline", "risk", "weak", "underperform", "decrease", "negative",
|
|
35
|
+
"downside", "threat", "bearish", "drop", "fall", "miss", "concern",
|
|
36
|
+
"volatile", "uncertain", "headwind", "pressure", "slump", "deteriorate",
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def analyze_memo_quality(memo_text: str) -> Dict[str, Union[int, float, str, List[str]]]:
|
|
41
|
+
"""Analyze the quality and behavioral-finance characteristics of an investment memo.
|
|
42
|
+
|
|
43
|
+
Evaluates word count, tone (sentiment), overconfidence language, structural
|
|
44
|
+
clarity, and produces a plain-English recommendation for improvement.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
memo_text: The full text of the investment memo as a string.
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
Dictionary with the following keys:
|
|
51
|
+
- word_count (int): Total number of words.
|
|
52
|
+
- sentiment_score (float): Score from -1.0 (very negative) to
|
|
53
|
+
+1.0 (very positive) based on financial vocabulary.
|
|
54
|
+
- overconfidence_flags (list[str]): Phrases detected that indicate
|
|
55
|
+
overconfidence bias.
|
|
56
|
+
- behavioral_biases (list[str]): Keys of every behavioral-finance bias
|
|
57
|
+
detected in the memo via the full catalog (see finlearn.biases). A
|
|
58
|
+
superset of overconfidence detection, covering 60+ biases.
|
|
59
|
+
- clarity_score (int): Estimated clarity from 0 to 100, based on
|
|
60
|
+
average sentence length and vocabulary diversity.
|
|
61
|
+
- recommendation (str): Plain-English suggestion for improvement.
|
|
62
|
+
|
|
63
|
+
Raises:
|
|
64
|
+
TypeError: If memo_text is not a string.
|
|
65
|
+
ValueError: If memo_text is empty or whitespace-only.
|
|
66
|
+
|
|
67
|
+
Example:
|
|
68
|
+
>>> memo = "This investment is guaranteed to grow. Strong momentum and profit."
|
|
69
|
+
>>> result = analyze_memo_quality(memo)
|
|
70
|
+
>>> "guaranteed" in result['overconfidence_flags']
|
|
71
|
+
True
|
|
72
|
+
"""
|
|
73
|
+
text = validate_text(memo_text, "memo_text")
|
|
74
|
+
|
|
75
|
+
# Word count: include alphanumeric tokens so financial terms like "Q3", "2024",
|
|
76
|
+
# and "15%" are counted (strip trailing punctuation but keep the token).
|
|
77
|
+
word_count = len(re.findall(r"\S+", text))
|
|
78
|
+
|
|
79
|
+
# Sentiment scoring uses only alphabetic words against the finance lexicon.
|
|
80
|
+
alpha_words = re.findall(r"[A-Za-z']+", text)
|
|
81
|
+
lower_words = [w.lower() for w in alpha_words]
|
|
82
|
+
|
|
83
|
+
# Sentiment score
|
|
84
|
+
pos_count = sum(1 for w in lower_words if w in _POSITIVE_WORDS)
|
|
85
|
+
neg_count = sum(1 for w in lower_words if w in _NEGATIVE_WORDS)
|
|
86
|
+
total_sentiment = pos_count + neg_count
|
|
87
|
+
if total_sentiment == 0:
|
|
88
|
+
sentiment_score = 0.0
|
|
89
|
+
else:
|
|
90
|
+
sentiment_score = round((pos_count - neg_count) / total_sentiment, 4)
|
|
91
|
+
|
|
92
|
+
# Overconfidence flags (kept for backward compatibility)
|
|
93
|
+
text_lower = text.lower()
|
|
94
|
+
overconfidence_flags = [phrase for phrase in _OVERCONFIDENCE_PHRASES if phrase in text_lower]
|
|
95
|
+
|
|
96
|
+
# Full behavioral-bias screen using the catalog in finlearn.biases.
|
|
97
|
+
behavioral_biases = [b["key"] for b in detect_biases(text)]
|
|
98
|
+
|
|
99
|
+
# Clarity score: penalize very long sentences and low vocabulary diversity
|
|
100
|
+
sentences = re.split(r"[.!?]+", text)
|
|
101
|
+
sentences = [s.strip() for s in sentences if s.strip()]
|
|
102
|
+
num_sentences = len(sentences)
|
|
103
|
+
|
|
104
|
+
avg_sentence_length = word_count / num_sentences if num_sentences > 0 else word_count
|
|
105
|
+
# Ideal avg sentence length ~15-20 words; penalize >30
|
|
106
|
+
length_penalty = max(0, (avg_sentence_length - 20) * 2)
|
|
107
|
+
|
|
108
|
+
alpha_word_count = len(lower_words)
|
|
109
|
+
unique_ratio = len(set(lower_words)) / alpha_word_count if alpha_word_count > 0 else 0
|
|
110
|
+
diversity_bonus = unique_ratio * 30 # up to 30 points for vocabulary diversity
|
|
111
|
+
|
|
112
|
+
clarity_score = int(max(0, min(100, 70 - length_penalty + diversity_bonus)))
|
|
113
|
+
|
|
114
|
+
# Build recommendation
|
|
115
|
+
issues = []
|
|
116
|
+
if overconfidence_flags:
|
|
117
|
+
issues.append(
|
|
118
|
+
f"Remove overconfident language ({', '.join(overconfidence_flags[:3])})"
|
|
119
|
+
)
|
|
120
|
+
# Surface other behavioral biases beyond overconfidence (which is already covered above).
|
|
121
|
+
other_biases = [b for b in behavioral_biases if b != "overconfidence"]
|
|
122
|
+
if other_biases:
|
|
123
|
+
issues.append(
|
|
124
|
+
f"Address behavioral biases ({', '.join(other_biases[:3])})"
|
|
125
|
+
)
|
|
126
|
+
if avg_sentence_length > 25:
|
|
127
|
+
issues.append("Shorten sentences for clarity")
|
|
128
|
+
if word_count < 100:
|
|
129
|
+
issues.append("Expand analysis — memo is brief")
|
|
130
|
+
if sentiment_score > 0.6:
|
|
131
|
+
issues.append("Balance tone; memo reads as overly optimistic")
|
|
132
|
+
elif sentiment_score < -0.6:
|
|
133
|
+
issues.append("Balance tone; memo reads as overly pessimistic")
|
|
134
|
+
|
|
135
|
+
if issues:
|
|
136
|
+
recommendation = "Suggested improvements: " + "; ".join(issues) + "."
|
|
137
|
+
else:
|
|
138
|
+
recommendation = "Memo quality is good. No major behavioral finance concerns detected."
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
"word_count": word_count,
|
|
142
|
+
"sentiment_score": sentiment_score,
|
|
143
|
+
"overconfidence_flags": overconfidence_flags,
|
|
144
|
+
"behavioral_biases": behavioral_biases,
|
|
145
|
+
"clarity_score": clarity_score,
|
|
146
|
+
"recommendation": recommendation,
|
|
147
|
+
}
|
finlearn/metrics.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Portfolio risk and return metrics."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from typing import List
|
|
5
|
+
|
|
6
|
+
from .utils import validate_returns, validate_prices
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def calculate_sharpe_ratio(
|
|
10
|
+
returns: List[float],
|
|
11
|
+
risk_free_rate: float = 0.0,
|
|
12
|
+
) -> float:
|
|
13
|
+
"""Calculate the annualized Sharpe ratio for a series of daily returns.
|
|
14
|
+
|
|
15
|
+
The Sharpe ratio measures risk-adjusted return: how much excess return is
|
|
16
|
+
earned per unit of volatility relative to a risk-free baseline.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
returns: List of daily returns as decimals (e.g., 0.01 for 1%).
|
|
20
|
+
risk_free_rate: Daily risk-free rate as a decimal. Defaults to 0.0.
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
Annualized Sharpe ratio as a float.
|
|
24
|
+
|
|
25
|
+
Raises:
|
|
26
|
+
TypeError: If returns is not a list/tuple or contains non-numeric values.
|
|
27
|
+
ValueError: If returns is empty or has zero standard deviation.
|
|
28
|
+
|
|
29
|
+
Example:
|
|
30
|
+
>>> daily_returns = [0.001, 0.002, -0.001, 0.003, 0.0015]
|
|
31
|
+
>>> calculate_sharpe_ratio(daily_returns, risk_free_rate=0.0001)
|
|
32
|
+
12.8431...
|
|
33
|
+
"""
|
|
34
|
+
# bool is a subclass of int — reject it explicitly so True/False can't pose
|
|
35
|
+
# as a numeric risk-free rate (consistent with how returns are validated).
|
|
36
|
+
if isinstance(risk_free_rate, bool) or not isinstance(risk_free_rate, (int, float)):
|
|
37
|
+
raise TypeError(f"risk_free_rate must be numeric, got {type(risk_free_rate).__name__}")
|
|
38
|
+
if risk_free_rate != risk_free_rate or math.isinf(risk_free_rate):
|
|
39
|
+
raise ValueError(f"risk_free_rate must be a finite number, got {risk_free_rate}")
|
|
40
|
+
|
|
41
|
+
r = validate_returns(returns, "returns")
|
|
42
|
+
|
|
43
|
+
if len(r) < 2:
|
|
44
|
+
raise ValueError("returns must contain at least 2 values to compute standard deviation")
|
|
45
|
+
|
|
46
|
+
n = len(r)
|
|
47
|
+
mean = sum(r) / n
|
|
48
|
+
try:
|
|
49
|
+
variance = sum((x - mean) ** 2 for x in r) / (n - 1)
|
|
50
|
+
except OverflowError:
|
|
51
|
+
raise ValueError("returns contain values too large to compute variance") from None
|
|
52
|
+
std = math.sqrt(variance)
|
|
53
|
+
|
|
54
|
+
if std == 0.0:
|
|
55
|
+
raise ValueError("Standard deviation of returns is zero; Sharpe ratio is undefined")
|
|
56
|
+
|
|
57
|
+
excess_return = mean - risk_free_rate
|
|
58
|
+
return (excess_return / std) * math.sqrt(252)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def calculate_max_drawdown(prices: List[float]) -> float:
|
|
62
|
+
"""Calculate the maximum drawdown from a price series.
|
|
63
|
+
|
|
64
|
+
Maximum drawdown measures the largest peak-to-trough decline, expressed
|
|
65
|
+
as a negative decimal (e.g., -0.25 means a 25% loss from peak to trough).
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
prices: List of asset prices in chronological order. All values must
|
|
69
|
+
be positive.
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
Maximum drawdown as a negative decimal between -1.0 and 0.0.
|
|
73
|
+
Returns 0.0 if the price series never declines.
|
|
74
|
+
|
|
75
|
+
Raises:
|
|
76
|
+
TypeError: If prices is not a list/tuple or contains non-numeric values.
|
|
77
|
+
ValueError: If prices is empty, contains non-positive values, or has
|
|
78
|
+
fewer than 2 elements.
|
|
79
|
+
|
|
80
|
+
Example:
|
|
81
|
+
>>> prices = [100, 120, 90, 110, 80, 130]
|
|
82
|
+
>>> calculate_max_drawdown(prices)
|
|
83
|
+
-0.3333...
|
|
84
|
+
"""
|
|
85
|
+
p = validate_prices(prices, "prices")
|
|
86
|
+
|
|
87
|
+
if len(p) < 2:
|
|
88
|
+
raise ValueError("prices must contain at least 2 values")
|
|
89
|
+
|
|
90
|
+
max_drawdown = 0.0
|
|
91
|
+
peak = p[0]
|
|
92
|
+
|
|
93
|
+
for price in p[1:]:
|
|
94
|
+
if price > peak:
|
|
95
|
+
peak = price
|
|
96
|
+
drawdown = (price - peak) / peak
|
|
97
|
+
if drawdown < max_drawdown:
|
|
98
|
+
max_drawdown = drawdown
|
|
99
|
+
|
|
100
|
+
return max_drawdown
|
finlearn/py.typed
ADDED
|
File without changes
|
finlearn/utils.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Shared validation and helper utilities for finlearn."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from typing import List
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def validate_returns(returns: List[float], name: str = "returns") -> List[float]:
|
|
8
|
+
"""Validate that a returns list is non-empty and contains finite numbers."""
|
|
9
|
+
if not isinstance(returns, (list, tuple)):
|
|
10
|
+
raise TypeError(f"{name} must be a list or tuple, got {type(returns).__name__}")
|
|
11
|
+
if len(returns) == 0:
|
|
12
|
+
raise ValueError(f"{name} must not be empty")
|
|
13
|
+
for i, v in enumerate(returns):
|
|
14
|
+
if isinstance(v, bool):
|
|
15
|
+
raise TypeError(f"{name}[{i}] must be numeric, got bool")
|
|
16
|
+
if not isinstance(v, (int, float)):
|
|
17
|
+
raise TypeError(f"{name}[{i}] must be numeric, got {type(v).__name__}")
|
|
18
|
+
if v != v: # NaN check
|
|
19
|
+
raise ValueError(f"{name}[{i}] contains NaN")
|
|
20
|
+
if math.isinf(v):
|
|
21
|
+
raise ValueError(f"{name}[{i}] contains infinity")
|
|
22
|
+
return [float(v) for v in returns]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def validate_prices(prices: List[float], name: str = "prices") -> List[float]:
|
|
26
|
+
"""Validate a price series: non-empty, numeric, all positive."""
|
|
27
|
+
validated = validate_returns(prices, name)
|
|
28
|
+
for i, v in enumerate(validated):
|
|
29
|
+
if v <= 0:
|
|
30
|
+
raise ValueError(f"{name}[{i}] must be positive, got {v}")
|
|
31
|
+
return validated
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def validate_text(text: str, name: str = "text") -> str:
|
|
35
|
+
"""Validate that input is a non-empty string."""
|
|
36
|
+
if not isinstance(text, str):
|
|
37
|
+
raise TypeError(f"{name} must be a string, got {type(text).__name__}")
|
|
38
|
+
if not text.strip():
|
|
39
|
+
raise ValueError(f"{name} must not be empty or whitespace-only")
|
|
40
|
+
return text
|
|
@@ -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,12 @@
|
|
|
1
|
+
finlearn/__init__.py,sha256=Y1gQ05dC_YEkeZVOooMLMP21F-A0YtVbDf3W1Km0EGk,747
|
|
2
|
+
finlearn/benchmarks.py,sha256=QRQHtv-nJvP7SbFVkqPthqCcl9pkuV3eO_Vcf4XLLGc,3620
|
|
3
|
+
finlearn/biases.py,sha256=E4EkBp_ymtWavgsa8kVgJfnpaFqhfnLTGcpHXAHkgbE,33764
|
|
4
|
+
finlearn/memo.py,sha256=1oGRtVUzrDv0NSG6Eq6R2ylzcxaRBEbMrxhDtIMGwXs,5876
|
|
5
|
+
finlearn/metrics.py,sha256=9WerS249cSh_pTqMg-TGw9AR2dL0HNDtvRGj9XKkuPo,3398
|
|
6
|
+
finlearn/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
finlearn/utils.py,sha256=NjyJ0TtmV5nhsfBflEk7BkPYJD9nRegLGl_qQA5GggE,1646
|
|
8
|
+
finlearn_analytics-0.1.0.dist-info/licenses/LICENSE,sha256=6XKkEW6l4rrJWGJfs62_OP93lE2jTMQchv-bdJJPYV8,1070
|
|
9
|
+
finlearn_analytics-0.1.0.dist-info/METADATA,sha256=AKKAHCw3vj0Fb-DU_I8NjRA_pxG0SN9dGkalJaTvAw4,8800
|
|
10
|
+
finlearn_analytics-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
11
|
+
finlearn_analytics-0.1.0.dist-info/top_level.txt,sha256=XW3S4R4KULbZQ_3EDgok5vsQRcSEmvXN0Va4T3ZI9Fs,9
|
|
12
|
+
finlearn_analytics-0.1.0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
finlearn
|