finlearn-analytics
Detect 69 behavioral-finance biases in investment memos — plus Sharpe, Sortino, VaR, benchmark analytics, and student-friendly money calculators. Pure Python, zero dependencies.
Installation
pip install finlearn-analytics
Quick Start
from finlearn import (
calculate_sharpe_ratio,
calculate_max_drawdown,
compare_to_benchmark,
analyze_memo_quality,
)
# Daily returns for a hypothetical portfolio
daily_returns = [0.012, -0.005, 0.008, 0.003, -0.002, 0.015, 0.001, -0.007, 0.009, 0.004]
# 1. Sharpe Ratio
sharpe = calculate_sharpe_ratio(daily_returns, risk_free_rate=0.0001)
print(f"Sharpe Ratio: {sharpe:.2f}")
# 2. Max Drawdown
prices = [100, 112, 107, 115, 109, 124, 125, 118, 127, 129]
drawdown = calculate_max_drawdown(prices)
print(f"Max Drawdown: {drawdown:.2%}")
# 3. Benchmark Comparison
benchmark_returns = [0.008, -0.003, 0.005, 0.002, -0.001, 0.010, 0.000, -0.004, 0.006, 0.003]
metrics = compare_to_benchmark(daily_returns, benchmark_returns)
print(f"Alpha: {metrics['alpha']:.4f} Beta: {metrics['beta']:.2f} Correlation: {metrics['correlation']:.2f}")
print(f"Excess Return: {metrics['excess_return']:.4f} Tracking Error: {metrics['tracking_error']:.4f}")
# 4. Memo Quality Analysis
memo = """
This stock shows strong momentum and profit potential. The company's
revenue growth is robust, with favorable market conditions driving
an expected increase in earnings next quarter.
"""
analysis = analyze_memo_quality(memo)
print(f"Word Count: {analysis['word_count']}")
print(f"Sentiment: {analysis['sentiment_score']:.2f}")
print(f"Clarity Score: {analysis['clarity_score']}/100")
print(f"Overconfidence Flags: {analysis['overconfidence_flags']}")
print(f"Behavioral Biases: {analysis['behavioral_biases']}")
print(f"Recommendation: {analysis['recommendation']}")
# 5. Behavioral Bias Detection (60+ specific biases)
from finlearn import analyze_biases, get_bias
note = "It's guaranteed to be the next Amazon. Everyone is buying — can't miss this."
report = analyze_biases(note)
print(f"Biases detected: {report['biases_detected']}")
print(f"By category: {report['by_category']}")
print(get_bias("fomo")["description"])
Functions
calculate_sharpe_ratio(returns, risk_free_rate=0.0)
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.
Parameters: returns — list of daily returns as decimals; risk_free_rate — daily risk-free rate (default 0.0).
Returns: float — annualized Sharpe ratio.
calculate_max_drawdown(prices)
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.
Parameters: prices — list of asset prices in chronological order (all positive).
Returns: float — maximum drawdown, between -1.0 and 0.0.
compare_to_benchmark(portfolio_returns, benchmark_returns)
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.
Parameters: portfolio_returns, benchmark_returns — lists of daily returns as decimals of equal length.
Returns: dict with keys alpha, beta, correlation, excess_return, tracking_error.
analyze_memo_quality(memo_text)
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.
Parameters: memo_text — full text of the investment memo as a string.
Returns: dict with keys word_count, sentiment_score, overconfidence_flags, behavioral_biases, clarity_score, recommendation.
Risk Metrics
| Function | Returns |
|---|---|
calculate_sortino_ratio(returns, risk_free_rate=0.0) |
float: annualized Sortino ratio. Like Sharpe, but only downside volatility counts as risk. |
calculate_volatility(returns, annualize=True) |
float: sample standard deviation of daily returns, annualized by default. |
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." |
calculate_cagr(start_value, end_value, years) |
float: compound annual growth rate. |
from finlearn import calculate_sortino_ratio, calculate_value_at_risk, calculate_cagr
returns = [0.012, -0.005, 0.008, 0.003, -0.002, 0.015, 0.001, -0.007, 0.009, 0.004]
print(f"Sortino: {calculate_sortino_ratio(returns):.2f}")
print(f"95% VaR: {calculate_value_at_risk(returns):.2%}")
print(f"CAGR: {calculate_cagr(1000, 2000, 10):.2%}") # 7.18%
Money Planning Calculators
Built for financial-literacy lessons: see what saving early and borrowing actually cost.
| Function | Returns |
|---|---|
compound_growth(principal, annual_rate, years, monthly_contribution=0.0, compounds_per_year=12) |
dict: final_balance, total_contributed, total_interest, yearly_balances |
loan_payment(principal, annual_rate, years) |
dict: monthly_payment, num_payments, total_paid, total_interest |
rule_of_72(annual_rate) |
dict: estimate_years (72 ÷ rate) and exact_years |
from finlearn import compound_growth, loan_payment, rule_of_72
# $1,000 now + $100/month at 7% for 10 years
plan = compound_growth(1000, 0.07, 10, monthly_contribution=100)
print(f"Balance: ${plan['final_balance']:,.2f}") # $19,318.14
print(f"Interest earned: ${plan['total_interest']:,.2f}")
# $20,000 car loan at 6% APR over 5 years
loan = loan_payment(20000, 0.06, 5)
print(f"Monthly: ${loan['monthly_payment']:,.2f} Interest: ${loan['total_interest']:,.2f}")
print(rule_of_72(0.08)) # {'estimate_years': 9.0, 'exact_years': 9.006...}
Behavioral Bias Detection
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.
| Function | Returns |
|---|---|
detect_biases(text) |
list[dict] — each detected bias with key, name, category, description, matched_phrases |
analyze_biases(text) |
dict — bias_count, biases_detected, by_category, details, bias_density_per_100_words, recommendation |
list_biases() |
list[dict] — metadata (key, name, category, description) for every bias |
list_bias_categories() |
list[str] — the distinct category labels |
get_bias(key) |
dict — full metadata for one bias, including its trigger phrases |
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.
from finlearn import detect_biases
hits = detect_biases("We're in too deep to sell now, but it's a sure thing.")
print([h["key"] for h in hits]) # ['overconfidence', 'sunk_cost']
About
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.
License
MIT — see LICENSE for details.
Metadata
Release files for finlearn-analytics 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| finlearn_analytics-0.2.0.tar.gz | 34.6 kB | With provenance | Details for finlearn_analytics-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| finlearn_analytics-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for finlearn_analytics-0.2.0-py3-none-any.whl |
Total release size: 62.9 kB
Release files / finlearn_analytics-0.2.0.tar.gz
| Download URL | finlearn_analytics-0.2.0.tar.gz |
|---|---|
| Size | 34.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
35b8b96b6f75d24abf2b2a93c077129ffd93f4dc2571c4658c24357fb0e8b669
|
|
BLAKE2b-256 checksum How to use checksums |
11a680f38e89a948deee26cb8158ac13a82a5cb8412c3f8a0eb9e4d5b6566473
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logRelease files / finlearn_analytics-0.2.0-py3-none-any.whl
| Download URL | finlearn_analytics-0.2.0-py3-none-any.whl |
|---|---|
| Size | 28.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
bedcc36493e4a9e1b4edb2cd265ebda50499800439d9856933b332b2ece31d40
|
|
BLAKE2b-256 checksum How to use checksums |
44e5e485282ae592da82e21650f24e81bb7a7e8e3546b91c7fc1e3b10c1989d8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logSecurity for finlearn-analytics 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for finlearn_analytics-0.2.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.