finlearn-analytics 0.1.0__tar.gz → 0.2.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 → finlearn_analytics-0.2.0}/PKG-INFO +50 -3
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/README.md +48 -1
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/finlearn/__init__.py +16 -1
- finlearn_analytics-0.2.0/finlearn/planning.py +161 -0
- finlearn_analytics-0.2.0/finlearn/risk.py +160 -0
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/finlearn/utils.py +26 -0
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/finlearn_analytics.egg-info/PKG-INFO +50 -3
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/finlearn_analytics.egg-info/SOURCES.txt +5 -1
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/pyproject.toml +2 -2
- finlearn_analytics-0.2.0/tests/test_planning.py +122 -0
- finlearn_analytics-0.2.0/tests/test_risk.py +123 -0
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/LICENSE +0 -0
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/finlearn/benchmarks.py +0 -0
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/finlearn/biases.py +0 -0
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/finlearn/memo.py +0 -0
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/finlearn/metrics.py +0 -0
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/finlearn/py.typed +0 -0
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/finlearn_analytics.egg-info/dependency_links.txt +0 -0
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/finlearn_analytics.egg-info/requires.txt +0 -0
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/finlearn_analytics.egg-info/top_level.txt +0 -0
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/setup.cfg +0 -0
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/tests/test_biases.py +0 -0
- {finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/tests/test_core.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: finlearn-analytics
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Financial analytics and behavioral finance research tools for Python
|
|
5
5
|
Author: Jeevun Sandhu
|
|
6
6
|
License-Expression: MIT
|
|
@@ -8,7 +8,7 @@ Project-URL: Homepage, https://github.com/JSand15/finlearn-analytics
|
|
|
8
8
|
Project-URL: Repository, https://github.com/JSand15/finlearn-analytics
|
|
9
9
|
Project-URL: Issues, https://github.com/JSand15/finlearn-analytics/issues
|
|
10
10
|
Project-URL: Changelog, https://github.com/JSand15/finlearn-analytics/blob/main/CHANGELOG.md
|
|
11
|
-
Keywords: finance,analytics,sharpe ratio,behavioral finance,investment
|
|
11
|
+
Keywords: finance,analytics,sharpe ratio,sortino ratio,value at risk,compound interest,financial literacy,behavioral finance,investment
|
|
12
12
|
Classifier: Development Status :: 3 - Alpha
|
|
13
13
|
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
14
14
|
Classifier: Intended Audience :: Education
|
|
@@ -35,7 +35,7 @@ Dynamic: license-file
|
|
|
35
35
|
|
|
36
36
|
# finlearn-analytics
|
|
37
37
|
|
|
38
|
-
**Detect 69 behavioral-finance biases in investment memos — plus Sharpe
|
|
38
|
+
**Detect 69 behavioral-finance biases in investment memos — plus Sharpe, Sortino, VaR, benchmark analytics, and student-friendly money calculators. Pure Python, zero dependencies.**
|
|
39
39
|
|
|
40
40
|
[](https://pypi.org/project/finlearn-analytics/)
|
|
41
41
|
[](https://github.com/JSand15/finlearn-analytics/actions/workflows/ci.yml)
|
|
@@ -145,6 +145,53 @@ Applies behavioral finance heuristics to score the quality of an investment memo
|
|
|
145
145
|
|
|
146
146
|
---
|
|
147
147
|
|
|
148
|
+
### Risk Metrics
|
|
149
|
+
|
|
150
|
+
| Function | Returns |
|
|
151
|
+
|----------|---------|
|
|
152
|
+
| `calculate_sortino_ratio(returns, risk_free_rate=0.0)` | `float`: annualized Sortino ratio. Like Sharpe, but only downside volatility counts as risk. |
|
|
153
|
+
| `calculate_volatility(returns, annualize=True)` | `float`: sample standard deviation of daily returns, annualized by default. |
|
|
154
|
+
| `calculate_value_at_risk(returns, confidence=0.95)` | `float`: historical one-day VaR. `-0.023` means "on 5% of days you lost 2.3% or more." |
|
|
155
|
+
| `calculate_cagr(start_value, end_value, years)` | `float`: compound annual growth rate. |
|
|
156
|
+
|
|
157
|
+
```python
|
|
158
|
+
from finlearn import calculate_sortino_ratio, calculate_value_at_risk, calculate_cagr
|
|
159
|
+
|
|
160
|
+
returns = [0.012, -0.005, 0.008, 0.003, -0.002, 0.015, 0.001, -0.007, 0.009, 0.004]
|
|
161
|
+
print(f"Sortino: {calculate_sortino_ratio(returns):.2f}")
|
|
162
|
+
print(f"95% VaR: {calculate_value_at_risk(returns):.2%}")
|
|
163
|
+
print(f"CAGR: {calculate_cagr(1000, 2000, 10):.2%}") # 7.18%
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
---
|
|
167
|
+
|
|
168
|
+
### Money Planning Calculators
|
|
169
|
+
|
|
170
|
+
Built for financial-literacy lessons: see what saving early and borrowing actually cost.
|
|
171
|
+
|
|
172
|
+
| Function | Returns |
|
|
173
|
+
|----------|---------|
|
|
174
|
+
| `compound_growth(principal, annual_rate, years, monthly_contribution=0.0, compounds_per_year=12)` | `dict`: `final_balance`, `total_contributed`, `total_interest`, `yearly_balances` |
|
|
175
|
+
| `loan_payment(principal, annual_rate, years)` | `dict`: `monthly_payment`, `num_payments`, `total_paid`, `total_interest` |
|
|
176
|
+
| `rule_of_72(annual_rate)` | `dict`: `estimate_years` (72 ÷ rate) and `exact_years` |
|
|
177
|
+
|
|
178
|
+
```python
|
|
179
|
+
from finlearn import compound_growth, loan_payment, rule_of_72
|
|
180
|
+
|
|
181
|
+
# $1,000 now + $100/month at 7% for 10 years
|
|
182
|
+
plan = compound_growth(1000, 0.07, 10, monthly_contribution=100)
|
|
183
|
+
print(f"Balance: ${plan['final_balance']:,.2f}") # $19,318.14
|
|
184
|
+
print(f"Interest earned: ${plan['total_interest']:,.2f}")
|
|
185
|
+
|
|
186
|
+
# $20,000 car loan at 6% APR over 5 years
|
|
187
|
+
loan = loan_payment(20000, 0.06, 5)
|
|
188
|
+
print(f"Monthly: ${loan['monthly_payment']:,.2f} Interest: ${loan['total_interest']:,.2f}")
|
|
189
|
+
|
|
190
|
+
print(rule_of_72(0.08)) # {'estimate_years': 9.0, 'exact_years': 9.006...}
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
---
|
|
194
|
+
|
|
148
195
|
### Behavioral Bias Detection
|
|
149
196
|
|
|
150
197
|
`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.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# finlearn-analytics
|
|
2
2
|
|
|
3
|
-
**Detect 69 behavioral-finance biases in investment memos — plus Sharpe
|
|
3
|
+
**Detect 69 behavioral-finance biases in investment memos — plus Sharpe, Sortino, VaR, benchmark analytics, and student-friendly money calculators. Pure Python, zero dependencies.**
|
|
4
4
|
|
|
5
5
|
[](https://pypi.org/project/finlearn-analytics/)
|
|
6
6
|
[](https://github.com/JSand15/finlearn-analytics/actions/workflows/ci.yml)
|
|
@@ -110,6 +110,53 @@ Applies behavioral finance heuristics to score the quality of an investment memo
|
|
|
110
110
|
|
|
111
111
|
---
|
|
112
112
|
|
|
113
|
+
### Risk Metrics
|
|
114
|
+
|
|
115
|
+
| Function | Returns |
|
|
116
|
+
|----------|---------|
|
|
117
|
+
| `calculate_sortino_ratio(returns, risk_free_rate=0.0)` | `float`: annualized Sortino ratio. Like Sharpe, but only downside volatility counts as risk. |
|
|
118
|
+
| `calculate_volatility(returns, annualize=True)` | `float`: sample standard deviation of daily returns, annualized by default. |
|
|
119
|
+
| `calculate_value_at_risk(returns, confidence=0.95)` | `float`: historical one-day VaR. `-0.023` means "on 5% of days you lost 2.3% or more." |
|
|
120
|
+
| `calculate_cagr(start_value, end_value, years)` | `float`: compound annual growth rate. |
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
from finlearn import calculate_sortino_ratio, calculate_value_at_risk, calculate_cagr
|
|
124
|
+
|
|
125
|
+
returns = [0.012, -0.005, 0.008, 0.003, -0.002, 0.015, 0.001, -0.007, 0.009, 0.004]
|
|
126
|
+
print(f"Sortino: {calculate_sortino_ratio(returns):.2f}")
|
|
127
|
+
print(f"95% VaR: {calculate_value_at_risk(returns):.2%}")
|
|
128
|
+
print(f"CAGR: {calculate_cagr(1000, 2000, 10):.2%}") # 7.18%
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
### Money Planning Calculators
|
|
134
|
+
|
|
135
|
+
Built for financial-literacy lessons: see what saving early and borrowing actually cost.
|
|
136
|
+
|
|
137
|
+
| Function | Returns |
|
|
138
|
+
|----------|---------|
|
|
139
|
+
| `compound_growth(principal, annual_rate, years, monthly_contribution=0.0, compounds_per_year=12)` | `dict`: `final_balance`, `total_contributed`, `total_interest`, `yearly_balances` |
|
|
140
|
+
| `loan_payment(principal, annual_rate, years)` | `dict`: `monthly_payment`, `num_payments`, `total_paid`, `total_interest` |
|
|
141
|
+
| `rule_of_72(annual_rate)` | `dict`: `estimate_years` (72 ÷ rate) and `exact_years` |
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
from finlearn import compound_growth, loan_payment, rule_of_72
|
|
145
|
+
|
|
146
|
+
# $1,000 now + $100/month at 7% for 10 years
|
|
147
|
+
plan = compound_growth(1000, 0.07, 10, monthly_contribution=100)
|
|
148
|
+
print(f"Balance: ${plan['final_balance']:,.2f}") # $19,318.14
|
|
149
|
+
print(f"Interest earned: ${plan['total_interest']:,.2f}")
|
|
150
|
+
|
|
151
|
+
# $20,000 car loan at 6% APR over 5 years
|
|
152
|
+
loan = loan_payment(20000, 0.06, 5)
|
|
153
|
+
print(f"Monthly: ${loan['monthly_payment']:,.2f} Interest: ${loan['total_interest']:,.2f}")
|
|
154
|
+
|
|
155
|
+
print(rule_of_72(0.08)) # {'estimate_years': 9.0, 'exact_years': 9.006...}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
---
|
|
159
|
+
|
|
113
160
|
### Behavioral Bias Detection
|
|
114
161
|
|
|
115
162
|
`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.
|
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
"""finlearn-analytics: Financial analytics and behavioral finance research tools."""
|
|
2
2
|
|
|
3
|
-
__version__ = "0.
|
|
3
|
+
__version__ = "0.2.0"
|
|
4
4
|
__author__ = "Jeevun Sandhu"
|
|
5
5
|
|
|
6
6
|
from .metrics import calculate_sharpe_ratio, calculate_max_drawdown
|
|
7
|
+
from .risk import (
|
|
8
|
+
calculate_sortino_ratio,
|
|
9
|
+
calculate_volatility,
|
|
10
|
+
calculate_value_at_risk,
|
|
11
|
+
calculate_cagr,
|
|
12
|
+
)
|
|
13
|
+
from .planning import compound_growth, loan_payment, rule_of_72
|
|
7
14
|
from .benchmarks import compare_to_benchmark
|
|
8
15
|
from .memo import analyze_memo_quality
|
|
9
16
|
from .biases import (
|
|
@@ -19,6 +26,14 @@ from .biases import (
|
|
|
19
26
|
__all__ = [
|
|
20
27
|
"calculate_sharpe_ratio",
|
|
21
28
|
"calculate_max_drawdown",
|
|
29
|
+
"calculate_sortino_ratio",
|
|
30
|
+
"calculate_volatility",
|
|
31
|
+
"calculate_value_at_risk",
|
|
32
|
+
"calculate_cagr",
|
|
33
|
+
# Personal-finance planning
|
|
34
|
+
"compound_growth",
|
|
35
|
+
"loan_payment",
|
|
36
|
+
"rule_of_72",
|
|
22
37
|
"compare_to_benchmark",
|
|
23
38
|
"analyze_memo_quality",
|
|
24
39
|
# Behavioral bias detection
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Personal-finance planning calculators: compound growth, loans, rule of 72."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from typing import Dict, List, Union
|
|
5
|
+
|
|
6
|
+
from .utils import validate_number
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def compound_growth(
|
|
10
|
+
principal: float,
|
|
11
|
+
annual_rate: float,
|
|
12
|
+
years: int,
|
|
13
|
+
monthly_contribution: float = 0.0,
|
|
14
|
+
compounds_per_year: int = 12,
|
|
15
|
+
) -> Dict[str, Union[float, List[float]]]:
|
|
16
|
+
"""Project savings growth with compound interest and monthly deposits.
|
|
17
|
+
|
|
18
|
+
Simulates month by month. Interest compounds ``compounds_per_year`` times
|
|
19
|
+
per year (converted to an equivalent monthly rate), and each
|
|
20
|
+
``monthly_contribution`` is deposited at the end of the month.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
principal: Starting balance (>= 0).
|
|
24
|
+
annual_rate: Nominal annual interest rate as a decimal (e.g., 0.07).
|
|
25
|
+
Negative rates are allowed (must be > -1).
|
|
26
|
+
years: Number of whole years to project (>= 1).
|
|
27
|
+
monthly_contribution: Amount deposited at the end of every month (>= 0).
|
|
28
|
+
compounds_per_year: Compounding periods per year (>= 1). Defaults to 12.
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
Dictionary with:
|
|
32
|
+
- final_balance (float): Balance after ``years`` years.
|
|
33
|
+
- total_contributed (float): principal + all monthly deposits.
|
|
34
|
+
- total_interest (float): final_balance - total_contributed.
|
|
35
|
+
- yearly_balances (list[float]): Balance at the end of each year.
|
|
36
|
+
|
|
37
|
+
Raises:
|
|
38
|
+
TypeError: If inputs have the wrong type.
|
|
39
|
+
ValueError: If inputs are out of range.
|
|
40
|
+
|
|
41
|
+
Example:
|
|
42
|
+
>>> result = compound_growth(1000, 0.07, 10, monthly_contribution=100)
|
|
43
|
+
>>> round(result["final_balance"], 2)
|
|
44
|
+
19318.14
|
|
45
|
+
"""
|
|
46
|
+
p = validate_number(principal, "principal", non_negative=True)
|
|
47
|
+
rate = validate_number(annual_rate, "annual_rate")
|
|
48
|
+
if rate <= -1.0:
|
|
49
|
+
raise ValueError(f"annual_rate must be greater than -1, got {rate}")
|
|
50
|
+
contrib = validate_number(monthly_contribution, "monthly_contribution", non_negative=True)
|
|
51
|
+
for name, val in (("years", years), ("compounds_per_year", compounds_per_year)):
|
|
52
|
+
if isinstance(val, bool) or not isinstance(val, int):
|
|
53
|
+
raise TypeError(f"{name} must be an int, got {type(val).__name__}")
|
|
54
|
+
if val < 1:
|
|
55
|
+
raise ValueError(f"{name} must be at least 1, got {val}")
|
|
56
|
+
|
|
57
|
+
periodic = rate / compounds_per_year
|
|
58
|
+
if periodic <= -1.0:
|
|
59
|
+
raise ValueError("annual_rate / compounds_per_year must be greater than -1")
|
|
60
|
+
monthly_rate = (1.0 + periodic) ** (compounds_per_year / 12.0) - 1.0
|
|
61
|
+
|
|
62
|
+
balance = p
|
|
63
|
+
yearly: List[float] = []
|
|
64
|
+
try:
|
|
65
|
+
for _ in range(years):
|
|
66
|
+
for _ in range(12):
|
|
67
|
+
balance = balance * (1.0 + monthly_rate) + contrib
|
|
68
|
+
if math.isinf(balance):
|
|
69
|
+
raise OverflowError
|
|
70
|
+
yearly.append(balance)
|
|
71
|
+
except OverflowError:
|
|
72
|
+
raise ValueError("projection overflowed; inputs are too large") from None
|
|
73
|
+
|
|
74
|
+
total_contributed = p + contrib * 12 * years
|
|
75
|
+
return {
|
|
76
|
+
"final_balance": balance,
|
|
77
|
+
"total_contributed": total_contributed,
|
|
78
|
+
"total_interest": balance - total_contributed,
|
|
79
|
+
"yearly_balances": yearly,
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def loan_payment(principal: float, annual_rate: float, years: float) -> Dict[str, float]:
|
|
84
|
+
"""Calculate the fixed monthly payment on an amortizing loan.
|
|
85
|
+
|
|
86
|
+
Uses the standard amortization formula
|
|
87
|
+
``P * i / (1 - (1 + i) ** -n)`` where ``i`` is the monthly rate and
|
|
88
|
+
``n`` the number of monthly payments. A 0% loan is just ``P / n``.
|
|
89
|
+
|
|
90
|
+
Args:
|
|
91
|
+
principal: Amount borrowed (> 0).
|
|
92
|
+
annual_rate: Annual interest rate (APR) as a decimal (>= 0).
|
|
93
|
+
years: Loan term in years (> 0). Rounded to the nearest whole month.
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
Dictionary with:
|
|
97
|
+
- monthly_payment (float)
|
|
98
|
+
- num_payments (int)
|
|
99
|
+
- total_paid (float)
|
|
100
|
+
- total_interest (float)
|
|
101
|
+
|
|
102
|
+
Raises:
|
|
103
|
+
TypeError: If inputs are non-numeric.
|
|
104
|
+
ValueError: If inputs are out of range or the term is under one month.
|
|
105
|
+
|
|
106
|
+
Example:
|
|
107
|
+
>>> round(loan_payment(20000, 0.06, 5)["monthly_payment"], 2)
|
|
108
|
+
386.66
|
|
109
|
+
"""
|
|
110
|
+
p = validate_number(principal, "principal", positive=True)
|
|
111
|
+
rate = validate_number(annual_rate, "annual_rate", non_negative=True)
|
|
112
|
+
y = validate_number(years, "years", positive=True)
|
|
113
|
+
n = int(round(y * 12))
|
|
114
|
+
if n < 1:
|
|
115
|
+
raise ValueError("loan term must be at least one month")
|
|
116
|
+
|
|
117
|
+
i = rate / 12.0
|
|
118
|
+
if i == 0.0:
|
|
119
|
+
payment = p / n
|
|
120
|
+
else:
|
|
121
|
+
try:
|
|
122
|
+
payment = p * i / (1.0 - (1.0 + i) ** -n)
|
|
123
|
+
except OverflowError:
|
|
124
|
+
raise ValueError("inputs are too large to compute a payment") from None
|
|
125
|
+
total = payment * n
|
|
126
|
+
return {
|
|
127
|
+
"monthly_payment": payment,
|
|
128
|
+
"num_payments": n,
|
|
129
|
+
"total_paid": total,
|
|
130
|
+
"total_interest": total - p,
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def rule_of_72(annual_rate: float) -> Dict[str, float]:
|
|
135
|
+
"""Estimate how many years it takes money to double.
|
|
136
|
+
|
|
137
|
+
The rule of 72 is the classic mental-math shortcut: divide 72 by the
|
|
138
|
+
interest rate in percent. This function returns both the shortcut and the
|
|
139
|
+
exact answer, ``ln(2) / ln(1 + rate)``, so students can see how close it is.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
annual_rate: Annual growth rate as a decimal (> 0), e.g., 0.08 for 8%.
|
|
143
|
+
|
|
144
|
+
Returns:
|
|
145
|
+
Dictionary with:
|
|
146
|
+
- estimate_years (float): ``72 / (rate * 100)``.
|
|
147
|
+
- exact_years (float): Exact doubling time with annual compounding.
|
|
148
|
+
|
|
149
|
+
Raises:
|
|
150
|
+
TypeError: If annual_rate is non-numeric.
|
|
151
|
+
ValueError: If annual_rate is not positive.
|
|
152
|
+
|
|
153
|
+
Example:
|
|
154
|
+
>>> rule_of_72(0.08)
|
|
155
|
+
{'estimate_years': 9.0, 'exact_years': 9.0064...}
|
|
156
|
+
"""
|
|
157
|
+
rate = validate_number(annual_rate, "annual_rate", positive=True)
|
|
158
|
+
return {
|
|
159
|
+
"estimate_years": 72.0 / (rate * 100.0),
|
|
160
|
+
"exact_years": math.log(2.0) / math.log1p(rate),
|
|
161
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Additional risk and growth metrics: Sortino, volatility, VaR, CAGR."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from typing import List
|
|
5
|
+
|
|
6
|
+
from .utils import validate_number, validate_returns
|
|
7
|
+
|
|
8
|
+
TRADING_DAYS = 252
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def calculate_sortino_ratio(
|
|
12
|
+
returns: List[float],
|
|
13
|
+
risk_free_rate: float = 0.0,
|
|
14
|
+
) -> float:
|
|
15
|
+
"""Calculate the annualized Sortino ratio for a series of daily returns.
|
|
16
|
+
|
|
17
|
+
Like the Sharpe ratio, but only penalizes *downside* volatility. Returns
|
|
18
|
+
above the risk-free target don't count as "risk", which matches how most
|
|
19
|
+
investors actually feel about volatility.
|
|
20
|
+
|
|
21
|
+
Downside deviation is ``sqrt(mean(min(0, r - risk_free_rate) ** 2))``
|
|
22
|
+
over all observations.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
returns: List of daily returns as decimals (e.g., 0.01 for 1%).
|
|
26
|
+
risk_free_rate: Daily target / risk-free rate as a decimal. Defaults to 0.0.
|
|
27
|
+
|
|
28
|
+
Returns:
|
|
29
|
+
Annualized Sortino ratio as a float.
|
|
30
|
+
|
|
31
|
+
Raises:
|
|
32
|
+
TypeError: If inputs are non-numeric.
|
|
33
|
+
ValueError: If returns has fewer than 2 values or no return falls
|
|
34
|
+
below the target (downside deviation is zero).
|
|
35
|
+
|
|
36
|
+
Example:
|
|
37
|
+
>>> calculate_sortino_ratio([0.01, -0.02, 0.015, -0.005, 0.02])
|
|
38
|
+
6.8873...
|
|
39
|
+
"""
|
|
40
|
+
rfr = validate_number(risk_free_rate, "risk_free_rate")
|
|
41
|
+
r = validate_returns(returns, "returns")
|
|
42
|
+
if len(r) < 2:
|
|
43
|
+
raise ValueError("returns must contain at least 2 values")
|
|
44
|
+
|
|
45
|
+
n = len(r)
|
|
46
|
+
mean = sum(r) / n
|
|
47
|
+
try:
|
|
48
|
+
downside_sq = sum(min(0.0, x - rfr) ** 2 for x in r) / n
|
|
49
|
+
except OverflowError:
|
|
50
|
+
raise ValueError("returns contain values too large to compute downside deviation") from None
|
|
51
|
+
downside_dev = math.sqrt(downside_sq)
|
|
52
|
+
if downside_dev == 0.0:
|
|
53
|
+
raise ValueError(
|
|
54
|
+
"Downside deviation is zero (no returns below the target); Sortino ratio is undefined"
|
|
55
|
+
)
|
|
56
|
+
return ((mean - rfr) / downside_dev) * math.sqrt(TRADING_DAYS)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def calculate_volatility(returns: List[float], annualize: bool = True) -> float:
|
|
60
|
+
"""Calculate the volatility (sample standard deviation) of daily returns.
|
|
61
|
+
|
|
62
|
+
Args:
|
|
63
|
+
returns: List of daily returns as decimals.
|
|
64
|
+
annualize: If True (default), scale by ``sqrt(252)`` to get annual
|
|
65
|
+
volatility. If False, return daily volatility.
|
|
66
|
+
|
|
67
|
+
Returns:
|
|
68
|
+
Volatility as a non-negative decimal (e.g., 0.18 means 18%).
|
|
69
|
+
|
|
70
|
+
Raises:
|
|
71
|
+
TypeError: If returns is not a list/tuple of numbers, or annualize is not a bool.
|
|
72
|
+
ValueError: If returns has fewer than 2 values.
|
|
73
|
+
|
|
74
|
+
Example:
|
|
75
|
+
>>> calculate_volatility([0.01, -0.01, 0.02, -0.02])
|
|
76
|
+
0.2898...
|
|
77
|
+
"""
|
|
78
|
+
if not isinstance(annualize, bool):
|
|
79
|
+
raise TypeError(f"annualize must be a bool, got {type(annualize).__name__}")
|
|
80
|
+
r = validate_returns(returns, "returns")
|
|
81
|
+
if len(r) < 2:
|
|
82
|
+
raise ValueError("returns must contain at least 2 values to compute volatility")
|
|
83
|
+
|
|
84
|
+
n = len(r)
|
|
85
|
+
mean = sum(r) / n
|
|
86
|
+
try:
|
|
87
|
+
variance = sum((x - mean) ** 2 for x in r) / (n - 1)
|
|
88
|
+
except OverflowError:
|
|
89
|
+
raise ValueError("returns contain values too large to compute variance") from None
|
|
90
|
+
daily = math.sqrt(variance)
|
|
91
|
+
return daily * math.sqrt(TRADING_DAYS) if annualize else daily
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def calculate_value_at_risk(returns: List[float], confidence: float = 0.95) -> float:
|
|
95
|
+
"""Calculate historical one-day Value at Risk (VaR).
|
|
96
|
+
|
|
97
|
+
VaR answers: "On a bad day (the worst ``1 - confidence`` of days), how
|
|
98
|
+
much could I lose?" It is the ``(1 - confidence)`` quantile of the
|
|
99
|
+
historical returns, using linear interpolation between data points
|
|
100
|
+
(the same method as ``numpy.percentile``'s default).
|
|
101
|
+
|
|
102
|
+
The result is a return, so a loss shows up as a negative number:
|
|
103
|
+
``-0.023`` at 95% confidence means "on 5% of days, you lost 2.3% or more."
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
returns: List of daily returns as decimals.
|
|
107
|
+
confidence: Confidence level strictly between 0 and 1. Defaults to 0.95.
|
|
108
|
+
|
|
109
|
+
Returns:
|
|
110
|
+
The VaR threshold return as a float.
|
|
111
|
+
|
|
112
|
+
Raises:
|
|
113
|
+
TypeError: If inputs are non-numeric.
|
|
114
|
+
ValueError: If returns has fewer than 2 values or confidence is not in (0, 1).
|
|
115
|
+
|
|
116
|
+
Example:
|
|
117
|
+
>>> calculate_value_at_risk([0.01, -0.03, 0.02, -0.01, 0.005], confidence=0.8)
|
|
118
|
+
-0.0140...
|
|
119
|
+
"""
|
|
120
|
+
c = validate_number(confidence, "confidence")
|
|
121
|
+
if not 0.0 < c < 1.0:
|
|
122
|
+
raise ValueError(f"confidence must be between 0 and 1 (exclusive), got {c}")
|
|
123
|
+
r = validate_returns(returns, "returns")
|
|
124
|
+
if len(r) < 2:
|
|
125
|
+
raise ValueError("returns must contain at least 2 values")
|
|
126
|
+
|
|
127
|
+
ordered = sorted(r)
|
|
128
|
+
pos = (1.0 - c) * (len(ordered) - 1)
|
|
129
|
+
lower = int(math.floor(pos))
|
|
130
|
+
upper = min(lower + 1, len(ordered) - 1)
|
|
131
|
+
frac = pos - lower
|
|
132
|
+
return ordered[lower] + (ordered[upper] - ordered[lower]) * frac
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def calculate_cagr(start_value: float, end_value: float, years: float) -> float:
|
|
136
|
+
"""Calculate the compound annual growth rate (CAGR).
|
|
137
|
+
|
|
138
|
+
CAGR is the steady yearly growth rate that turns ``start_value`` into
|
|
139
|
+
``end_value`` over ``years`` years: ``(end / start) ** (1 / years) - 1``.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
start_value: Starting value (must be positive).
|
|
143
|
+
end_value: Ending value (must be positive).
|
|
144
|
+
years: Length of the period in years (must be positive; fractions allowed).
|
|
145
|
+
|
|
146
|
+
Returns:
|
|
147
|
+
CAGR as a decimal (e.g., 0.07 means 7% per year).
|
|
148
|
+
|
|
149
|
+
Raises:
|
|
150
|
+
TypeError: If any input is non-numeric.
|
|
151
|
+
ValueError: If any input is not positive.
|
|
152
|
+
|
|
153
|
+
Example:
|
|
154
|
+
>>> calculate_cagr(1000, 2000, 10)
|
|
155
|
+
0.0717...
|
|
156
|
+
"""
|
|
157
|
+
s = validate_number(start_value, "start_value", positive=True)
|
|
158
|
+
e = validate_number(end_value, "end_value", positive=True)
|
|
159
|
+
y = validate_number(years, "years", positive=True)
|
|
160
|
+
return (e / s) ** (1.0 / y) - 1.0
|
|
@@ -31,6 +31,32 @@ def validate_prices(prices: List[float], name: str = "prices") -> List[float]:
|
|
|
31
31
|
return validated
|
|
32
32
|
|
|
33
33
|
|
|
34
|
+
def validate_number(
|
|
35
|
+
value: float,
|
|
36
|
+
name: str,
|
|
37
|
+
*,
|
|
38
|
+
positive: bool = False,
|
|
39
|
+
non_negative: bool = False,
|
|
40
|
+
) -> float:
|
|
41
|
+
"""Validate a single finite numeric scalar (bools rejected).
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
value: The value to check.
|
|
45
|
+
name: Argument name used in error messages.
|
|
46
|
+
positive: If True, require ``value > 0``.
|
|
47
|
+
non_negative: If True, require ``value >= 0``.
|
|
48
|
+
"""
|
|
49
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
50
|
+
raise TypeError(f"{name} must be numeric, got {type(value).__name__}")
|
|
51
|
+
if value != value or math.isinf(value):
|
|
52
|
+
raise ValueError(f"{name} must be a finite number, got {value}")
|
|
53
|
+
if positive and value <= 0:
|
|
54
|
+
raise ValueError(f"{name} must be positive, got {value}")
|
|
55
|
+
if non_negative and value < 0:
|
|
56
|
+
raise ValueError(f"{name} must not be negative, got {value}")
|
|
57
|
+
return float(value)
|
|
58
|
+
|
|
59
|
+
|
|
34
60
|
def validate_text(text: str, name: str = "text") -> str:
|
|
35
61
|
"""Validate that input is a non-empty string."""
|
|
36
62
|
if not isinstance(text, str):
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: finlearn-analytics
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Financial analytics and behavioral finance research tools for Python
|
|
5
5
|
Author: Jeevun Sandhu
|
|
6
6
|
License-Expression: MIT
|
|
@@ -8,7 +8,7 @@ Project-URL: Homepage, https://github.com/JSand15/finlearn-analytics
|
|
|
8
8
|
Project-URL: Repository, https://github.com/JSand15/finlearn-analytics
|
|
9
9
|
Project-URL: Issues, https://github.com/JSand15/finlearn-analytics/issues
|
|
10
10
|
Project-URL: Changelog, https://github.com/JSand15/finlearn-analytics/blob/main/CHANGELOG.md
|
|
11
|
-
Keywords: finance,analytics,sharpe ratio,behavioral finance,investment
|
|
11
|
+
Keywords: finance,analytics,sharpe ratio,sortino ratio,value at risk,compound interest,financial literacy,behavioral finance,investment
|
|
12
12
|
Classifier: Development Status :: 3 - Alpha
|
|
13
13
|
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
14
14
|
Classifier: Intended Audience :: Education
|
|
@@ -35,7 +35,7 @@ Dynamic: license-file
|
|
|
35
35
|
|
|
36
36
|
# finlearn-analytics
|
|
37
37
|
|
|
38
|
-
**Detect 69 behavioral-finance biases in investment memos — plus Sharpe
|
|
38
|
+
**Detect 69 behavioral-finance biases in investment memos — plus Sharpe, Sortino, VaR, benchmark analytics, and student-friendly money calculators. Pure Python, zero dependencies.**
|
|
39
39
|
|
|
40
40
|
[](https://pypi.org/project/finlearn-analytics/)
|
|
41
41
|
[](https://github.com/JSand15/finlearn-analytics/actions/workflows/ci.yml)
|
|
@@ -145,6 +145,53 @@ Applies behavioral finance heuristics to score the quality of an investment memo
|
|
|
145
145
|
|
|
146
146
|
---
|
|
147
147
|
|
|
148
|
+
### Risk Metrics
|
|
149
|
+
|
|
150
|
+
| Function | Returns |
|
|
151
|
+
|----------|---------|
|
|
152
|
+
| `calculate_sortino_ratio(returns, risk_free_rate=0.0)` | `float`: annualized Sortino ratio. Like Sharpe, but only downside volatility counts as risk. |
|
|
153
|
+
| `calculate_volatility(returns, annualize=True)` | `float`: sample standard deviation of daily returns, annualized by default. |
|
|
154
|
+
| `calculate_value_at_risk(returns, confidence=0.95)` | `float`: historical one-day VaR. `-0.023` means "on 5% of days you lost 2.3% or more." |
|
|
155
|
+
| `calculate_cagr(start_value, end_value, years)` | `float`: compound annual growth rate. |
|
|
156
|
+
|
|
157
|
+
```python
|
|
158
|
+
from finlearn import calculate_sortino_ratio, calculate_value_at_risk, calculate_cagr
|
|
159
|
+
|
|
160
|
+
returns = [0.012, -0.005, 0.008, 0.003, -0.002, 0.015, 0.001, -0.007, 0.009, 0.004]
|
|
161
|
+
print(f"Sortino: {calculate_sortino_ratio(returns):.2f}")
|
|
162
|
+
print(f"95% VaR: {calculate_value_at_risk(returns):.2%}")
|
|
163
|
+
print(f"CAGR: {calculate_cagr(1000, 2000, 10):.2%}") # 7.18%
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
---
|
|
167
|
+
|
|
168
|
+
### Money Planning Calculators
|
|
169
|
+
|
|
170
|
+
Built for financial-literacy lessons: see what saving early and borrowing actually cost.
|
|
171
|
+
|
|
172
|
+
| Function | Returns |
|
|
173
|
+
|----------|---------|
|
|
174
|
+
| `compound_growth(principal, annual_rate, years, monthly_contribution=0.0, compounds_per_year=12)` | `dict`: `final_balance`, `total_contributed`, `total_interest`, `yearly_balances` |
|
|
175
|
+
| `loan_payment(principal, annual_rate, years)` | `dict`: `monthly_payment`, `num_payments`, `total_paid`, `total_interest` |
|
|
176
|
+
| `rule_of_72(annual_rate)` | `dict`: `estimate_years` (72 ÷ rate) and `exact_years` |
|
|
177
|
+
|
|
178
|
+
```python
|
|
179
|
+
from finlearn import compound_growth, loan_payment, rule_of_72
|
|
180
|
+
|
|
181
|
+
# $1,000 now + $100/month at 7% for 10 years
|
|
182
|
+
plan = compound_growth(1000, 0.07, 10, monthly_contribution=100)
|
|
183
|
+
print(f"Balance: ${plan['final_balance']:,.2f}") # $19,318.14
|
|
184
|
+
print(f"Interest earned: ${plan['total_interest']:,.2f}")
|
|
185
|
+
|
|
186
|
+
# $20,000 car loan at 6% APR over 5 years
|
|
187
|
+
loan = loan_payment(20000, 0.06, 5)
|
|
188
|
+
print(f"Monthly: ${loan['monthly_payment']:,.2f} Interest: ${loan['total_interest']:,.2f}")
|
|
189
|
+
|
|
190
|
+
print(rule_of_72(0.08)) # {'estimate_years': 9.0, 'exact_years': 9.006...}
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
---
|
|
194
|
+
|
|
148
195
|
### Behavioral Bias Detection
|
|
149
196
|
|
|
150
197
|
`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.
|
{finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/finlearn_analytics.egg-info/SOURCES.txt
RENAMED
|
@@ -7,7 +7,9 @@ finlearn/benchmarks.py
|
|
|
7
7
|
finlearn/biases.py
|
|
8
8
|
finlearn/memo.py
|
|
9
9
|
finlearn/metrics.py
|
|
10
|
+
finlearn/planning.py
|
|
10
11
|
finlearn/py.typed
|
|
12
|
+
finlearn/risk.py
|
|
11
13
|
finlearn/utils.py
|
|
12
14
|
finlearn_analytics.egg-info/PKG-INFO
|
|
13
15
|
finlearn_analytics.egg-info/SOURCES.txt
|
|
@@ -15,4 +17,6 @@ finlearn_analytics.egg-info/dependency_links.txt
|
|
|
15
17
|
finlearn_analytics.egg-info/requires.txt
|
|
16
18
|
finlearn_analytics.egg-info/top_level.txt
|
|
17
19
|
tests/test_biases.py
|
|
18
|
-
tests/test_core.py
|
|
20
|
+
tests/test_core.py
|
|
21
|
+
tests/test_planning.py
|
|
22
|
+
tests/test_risk.py
|
|
@@ -6,14 +6,14 @@ build-backend = "setuptools.build_meta"
|
|
|
6
6
|
|
|
7
7
|
[project]
|
|
8
8
|
name = "finlearn-analytics"
|
|
9
|
-
version = "0.
|
|
9
|
+
version = "0.2.0"
|
|
10
10
|
description = "Financial analytics and behavioral finance research tools for Python"
|
|
11
11
|
readme = "README.md"
|
|
12
12
|
license = "MIT"
|
|
13
13
|
license-files = ["LICENSE"]
|
|
14
14
|
authors = [{name = "Jeevun Sandhu"}]
|
|
15
15
|
requires-python = ">=3.9"
|
|
16
|
-
keywords = ["finance", "analytics", "sharpe ratio", "behavioral finance", "investment"]
|
|
16
|
+
keywords = ["finance", "analytics", "sharpe ratio", "sortino ratio", "value at risk", "compound interest", "financial literacy", "behavioral finance", "investment"]
|
|
17
17
|
classifiers = [
|
|
18
18
|
"Development Status :: 3 - Alpha",
|
|
19
19
|
"Intended Audience :: Financial and Insurance Industry",
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Tests for finlearn.planning — compound growth, loans, rule of 72."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from finlearn import compound_growth, loan_payment, rule_of_72
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TestCompoundGrowth:
|
|
10
|
+
def test_matches_closed_form_with_contributions(self):
|
|
11
|
+
p, r, y, c = 1000, 0.07, 10, 100
|
|
12
|
+
i = r / 12
|
|
13
|
+
n = y * 12
|
|
14
|
+
expected = p * (1 + i) ** n + c * ((1 + i) ** n - 1) / i
|
|
15
|
+
result = compound_growth(p, r, y, monthly_contribution=c)
|
|
16
|
+
assert result["final_balance"] == pytest.approx(expected)
|
|
17
|
+
|
|
18
|
+
def test_annual_compounding_no_contributions(self):
|
|
19
|
+
result = compound_growth(1000, 0.05, 3, compounds_per_year=1)
|
|
20
|
+
assert result["final_balance"] == pytest.approx(1000 * 1.05 ** 3)
|
|
21
|
+
assert result["yearly_balances"] == pytest.approx([1050, 1102.5, 1157.625])
|
|
22
|
+
|
|
23
|
+
def test_totals_add_up(self):
|
|
24
|
+
result = compound_growth(500, 0.04, 5, monthly_contribution=50)
|
|
25
|
+
assert result["total_contributed"] == pytest.approx(500 + 50 * 60)
|
|
26
|
+
assert result["total_interest"] == pytest.approx(
|
|
27
|
+
result["final_balance"] - result["total_contributed"]
|
|
28
|
+
)
|
|
29
|
+
assert len(result["yearly_balances"]) == 5
|
|
30
|
+
assert result["yearly_balances"][-1] == result["final_balance"]
|
|
31
|
+
|
|
32
|
+
def test_zero_rate(self):
|
|
33
|
+
result = compound_growth(100, 0.0, 2, monthly_contribution=10)
|
|
34
|
+
assert result["final_balance"] == pytest.approx(340)
|
|
35
|
+
assert result["total_interest"] == pytest.approx(0)
|
|
36
|
+
|
|
37
|
+
def test_negative_rate_shrinks(self):
|
|
38
|
+
assert compound_growth(1000, -0.02, 3)["final_balance"] < 1000
|
|
39
|
+
|
|
40
|
+
@pytest.mark.parametrize(
|
|
41
|
+
"kwargs",
|
|
42
|
+
[
|
|
43
|
+
dict(principal=-1, annual_rate=0.05, years=1),
|
|
44
|
+
dict(principal=100, annual_rate=-1.0, years=1),
|
|
45
|
+
dict(principal=100, annual_rate=0.05, years=0),
|
|
46
|
+
dict(principal=100, annual_rate=0.05, years=1, monthly_contribution=-5),
|
|
47
|
+
dict(principal=100, annual_rate=0.05, years=1, compounds_per_year=0),
|
|
48
|
+
],
|
|
49
|
+
)
|
|
50
|
+
def test_out_of_range_raises(self, kwargs):
|
|
51
|
+
with pytest.raises(ValueError):
|
|
52
|
+
compound_growth(**kwargs)
|
|
53
|
+
|
|
54
|
+
def test_bad_types_raise(self):
|
|
55
|
+
with pytest.raises(TypeError):
|
|
56
|
+
compound_growth(100, 0.05, 2.5)
|
|
57
|
+
with pytest.raises(TypeError):
|
|
58
|
+
compound_growth(100, 0.05, True)
|
|
59
|
+
with pytest.raises(TypeError):
|
|
60
|
+
compound_growth("100", 0.05, 1)
|
|
61
|
+
|
|
62
|
+
def test_overflow_raises_valueerror(self):
|
|
63
|
+
with pytest.raises(ValueError):
|
|
64
|
+
compound_growth(1e300, 100.0, 50)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class TestLoanPayment:
|
|
68
|
+
def test_known_car_loan(self):
|
|
69
|
+
result = loan_payment(20000, 0.06, 5)
|
|
70
|
+
assert result["monthly_payment"] == pytest.approx(386.656, abs=1e-3)
|
|
71
|
+
assert result["num_payments"] == 60
|
|
72
|
+
|
|
73
|
+
def test_zero_interest(self):
|
|
74
|
+
result = loan_payment(1200, 0.0, 1)
|
|
75
|
+
assert result["monthly_payment"] == pytest.approx(100)
|
|
76
|
+
assert result["total_interest"] == pytest.approx(0)
|
|
77
|
+
|
|
78
|
+
def test_payment_pays_off_balance(self):
|
|
79
|
+
result = loan_payment(15000, 0.045, 3)
|
|
80
|
+
bal = 15000.0
|
|
81
|
+
for _ in range(result["num_payments"]):
|
|
82
|
+
bal = bal * (1 + 0.045 / 12) - result["monthly_payment"]
|
|
83
|
+
assert bal == pytest.approx(0, abs=1e-6)
|
|
84
|
+
|
|
85
|
+
def test_totals(self):
|
|
86
|
+
result = loan_payment(10000, 0.08, 4)
|
|
87
|
+
assert result["total_paid"] == pytest.approx(result["monthly_payment"] * 48)
|
|
88
|
+
assert result["total_interest"] == pytest.approx(result["total_paid"] - 10000)
|
|
89
|
+
|
|
90
|
+
@pytest.mark.parametrize("args", [(0, 0.05, 1), (1000, -0.01, 1), (1000, 0.05, 0), (1000, 0.05, 0.01)])
|
|
91
|
+
def test_out_of_range_raises(self, args):
|
|
92
|
+
with pytest.raises(ValueError):
|
|
93
|
+
loan_payment(*args)
|
|
94
|
+
|
|
95
|
+
def test_bad_type_raises(self):
|
|
96
|
+
with pytest.raises(TypeError):
|
|
97
|
+
loan_payment(1000, "5%", 1)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class TestRuleOf72:
|
|
101
|
+
def test_eight_percent(self):
|
|
102
|
+
result = rule_of_72(0.08)
|
|
103
|
+
assert result["estimate_years"] == pytest.approx(9.0)
|
|
104
|
+
assert result["exact_years"] == pytest.approx(math.log(2) / math.log(1.08))
|
|
105
|
+
|
|
106
|
+
def test_estimate_close_to_exact(self):
|
|
107
|
+
for rate in (0.04, 0.06, 0.1):
|
|
108
|
+
result = rule_of_72(rate)
|
|
109
|
+
assert result["estimate_years"] == pytest.approx(result["exact_years"], rel=0.03)
|
|
110
|
+
|
|
111
|
+
def test_exact_actually_doubles(self):
|
|
112
|
+
y = rule_of_72(0.07)["exact_years"]
|
|
113
|
+
assert 1.07 ** y == pytest.approx(2.0)
|
|
114
|
+
|
|
115
|
+
@pytest.mark.parametrize("rate", [0, -0.05])
|
|
116
|
+
def test_non_positive_raises(self, rate):
|
|
117
|
+
with pytest.raises(ValueError):
|
|
118
|
+
rule_of_72(rate)
|
|
119
|
+
|
|
120
|
+
def test_bad_type_raises(self):
|
|
121
|
+
with pytest.raises(TypeError):
|
|
122
|
+
rule_of_72(None)
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Tests for finlearn.risk — Sortino, volatility, VaR, CAGR."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from finlearn import (
|
|
7
|
+
calculate_sortino_ratio,
|
|
8
|
+
calculate_volatility,
|
|
9
|
+
calculate_value_at_risk,
|
|
10
|
+
calculate_cagr,
|
|
11
|
+
calculate_sharpe_ratio,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class TestSortinoRatio:
|
|
16
|
+
def test_known_output(self):
|
|
17
|
+
r = [0.01, -0.02, 0.015, -0.005, 0.02]
|
|
18
|
+
mean = sum(r) / len(r)
|
|
19
|
+
dd = math.sqrt(sum(min(0.0, x) ** 2 for x in r) / len(r))
|
|
20
|
+
assert calculate_sortino_ratio(r) == pytest.approx(mean / dd * math.sqrt(252))
|
|
21
|
+
|
|
22
|
+
def test_higher_rfr_lowers_ratio(self):
|
|
23
|
+
r = [0.01, -0.02, 0.015, -0.005, 0.02]
|
|
24
|
+
assert calculate_sortino_ratio(r, 0.001) < calculate_sortino_ratio(r)
|
|
25
|
+
|
|
26
|
+
def test_ignores_upside_volatility(self):
|
|
27
|
+
# Bigger up-days raise Sortino; Sharpe would be dragged by the extra spread.
|
|
28
|
+
calm = [0.01, -0.01, 0.01, -0.01]
|
|
29
|
+
spiky = [0.05, -0.01, 0.05, -0.01]
|
|
30
|
+
assert calculate_sortino_ratio(spiky) > calculate_sortino_ratio(calm)
|
|
31
|
+
|
|
32
|
+
def test_no_downside_raises(self):
|
|
33
|
+
with pytest.raises(ValueError, match="[Dd]ownside"):
|
|
34
|
+
calculate_sortino_ratio([0.01, 0.02, 0.03])
|
|
35
|
+
|
|
36
|
+
def test_too_short_raises(self):
|
|
37
|
+
with pytest.raises(ValueError):
|
|
38
|
+
calculate_sortino_ratio([-0.01])
|
|
39
|
+
|
|
40
|
+
def test_bad_types_raise(self):
|
|
41
|
+
with pytest.raises(TypeError):
|
|
42
|
+
calculate_sortino_ratio("nope")
|
|
43
|
+
with pytest.raises(TypeError):
|
|
44
|
+
calculate_sortino_ratio([0.01, -0.01], risk_free_rate=True)
|
|
45
|
+
|
|
46
|
+
def test_nan_rfr_raises(self):
|
|
47
|
+
with pytest.raises(ValueError):
|
|
48
|
+
calculate_sortino_ratio([0.01, -0.01], risk_free_rate=float("nan"))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class TestVolatility:
|
|
52
|
+
def test_known_output(self):
|
|
53
|
+
r = [0.01, -0.01, 0.02, -0.02]
|
|
54
|
+
mean = sum(r) / 4
|
|
55
|
+
daily = math.sqrt(sum((x - mean) ** 2 for x in r) / 3)
|
|
56
|
+
assert calculate_volatility(r, annualize=False) == pytest.approx(daily)
|
|
57
|
+
assert calculate_volatility(r) == pytest.approx(daily * math.sqrt(252))
|
|
58
|
+
|
|
59
|
+
def test_constant_returns_zero(self):
|
|
60
|
+
assert calculate_volatility([0.01, 0.01, 0.01]) == 0.0
|
|
61
|
+
|
|
62
|
+
def test_consistent_with_sharpe(self):
|
|
63
|
+
r = [0.002, 0.003, -0.001, 0.004, 0.0]
|
|
64
|
+
mean = sum(r) / len(r)
|
|
65
|
+
vol = calculate_volatility(r)
|
|
66
|
+
assert calculate_sharpe_ratio(r) == pytest.approx(mean * 252 / vol)
|
|
67
|
+
|
|
68
|
+
def test_too_short_raises(self):
|
|
69
|
+
with pytest.raises(ValueError):
|
|
70
|
+
calculate_volatility([0.01])
|
|
71
|
+
|
|
72
|
+
def test_non_bool_annualize_raises(self):
|
|
73
|
+
with pytest.raises(TypeError):
|
|
74
|
+
calculate_volatility([0.01, 0.02], annualize=1)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class TestValueAtRisk:
|
|
78
|
+
def test_known_output_interpolated(self):
|
|
79
|
+
r = [0.01, -0.03, 0.02, -0.01, 0.005]
|
|
80
|
+
# sorted: -0.03, -0.01, 0.005, 0.01, 0.02 ; pos = 0.2 * 4 = 0.8
|
|
81
|
+
assert calculate_value_at_risk(r, 0.8) == pytest.approx(-0.03 + 0.02 * 0.8)
|
|
82
|
+
|
|
83
|
+
def test_matches_exact_index(self):
|
|
84
|
+
r = [i / 100 for i in range(-10, 11)] # 21 points, pos = 0.05 * 20 = 1
|
|
85
|
+
assert calculate_value_at_risk(r, 0.95) == pytest.approx(-0.09)
|
|
86
|
+
|
|
87
|
+
def test_higher_confidence_more_extreme(self):
|
|
88
|
+
r = [0.01, -0.03, 0.02, -0.01, 0.005, -0.02, 0.015]
|
|
89
|
+
assert calculate_value_at_risk(r, 0.99) <= calculate_value_at_risk(r, 0.9)
|
|
90
|
+
|
|
91
|
+
def test_order_independent(self):
|
|
92
|
+
r = [0.01, -0.03, 0.02, -0.01]
|
|
93
|
+
assert calculate_value_at_risk(r) == calculate_value_at_risk(list(reversed(r)))
|
|
94
|
+
|
|
95
|
+
@pytest.mark.parametrize("c", [0, 1, -0.5, 1.5])
|
|
96
|
+
def test_bad_confidence_raises(self, c):
|
|
97
|
+
with pytest.raises(ValueError):
|
|
98
|
+
calculate_value_at_risk([0.01, -0.01], c)
|
|
99
|
+
|
|
100
|
+
def test_too_short_raises(self):
|
|
101
|
+
with pytest.raises(ValueError):
|
|
102
|
+
calculate_value_at_risk([0.01])
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class TestCAGR:
|
|
106
|
+
def test_doubling_in_ten_years(self):
|
|
107
|
+
assert calculate_cagr(1000, 2000, 10) == pytest.approx(2 ** 0.1 - 1)
|
|
108
|
+
|
|
109
|
+
def test_loss_is_negative(self):
|
|
110
|
+
assert calculate_cagr(100, 50, 2) < 0
|
|
111
|
+
|
|
112
|
+
def test_round_trip(self):
|
|
113
|
+
g = calculate_cagr(250, 912.5, 7.5)
|
|
114
|
+
assert 250 * (1 + g) ** 7.5 == pytest.approx(912.5)
|
|
115
|
+
|
|
116
|
+
@pytest.mark.parametrize("args", [(0, 100, 1), (100, 0, 1), (100, 200, 0), (-1, 100, 1)])
|
|
117
|
+
def test_non_positive_raises(self, args):
|
|
118
|
+
with pytest.raises(ValueError):
|
|
119
|
+
calculate_cagr(*args)
|
|
120
|
+
|
|
121
|
+
def test_bad_type_raises(self):
|
|
122
|
+
with pytest.raises(TypeError):
|
|
123
|
+
calculate_cagr("100", 200, 1)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/finlearn_analytics.egg-info/requires.txt
RENAMED
|
File without changes
|
{finlearn_analytics-0.1.0 → finlearn_analytics-0.2.0}/finlearn_analytics.egg-info/top_level.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|