pandasMFE 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.
pandasmfe/__init__.py ADDED
@@ -0,0 +1,55 @@
1
+ """pandasMFE — risk and performance metrics for pandas, with a ``.mfe`` accessor.
2
+
3
+ Two ways to use it::
4
+
5
+ import pandasmfe as pm
6
+ pm.risk_report(prices) # plain functions
7
+
8
+ prices.mfe.risk_report() # accessor, available after `import pandasmfe`
9
+
10
+ Prices can come from a CSV or from a SQLite database (``pm.read_prices_sql``).
11
+ """
12
+
13
+ # Importing accessor.py runs its decorators, which register `.mfe` on every
14
+ # DataFrame and Series. The import is needed for this side effect only, so the
15
+ # name is never used ("noqa: F401" tells linters the unused import is intentional).
16
+ from pandasmfe import accessor as _accessor # noqa: F401
17
+
18
+ # Re-export the public functions, so users write pm.risk_report(...)
19
+ # instead of pm.metrics.risk_report(...). Same objects, not copies.
20
+ from pandasmfe.metrics import (
21
+ annualized_return,
22
+ annualized_volatility,
23
+ cvar_historical,
24
+ drawdown_series,
25
+ max_drawdown,
26
+ risk_report,
27
+ sharpe_ratio,
28
+ simple_returns,
29
+ var_historical,
30
+ var_parametric,
31
+ )
32
+ # Re-export the database functions in the same way.
33
+ from pandasmfe.sql import list_tickers, read_prices_sql, write_prices_sql
34
+
35
+ # The package version, written in this single place; pyproject.toml reads it from here.
36
+ __version__ = "0.1.0"
37
+
38
+ # The official list of public names: what `from pandasmfe import *` imports,
39
+ # and what users can rely on. Internal modules and helpers are left out.
40
+ __all__ = [
41
+ "simple_returns",
42
+ "annualized_return",
43
+ "annualized_volatility",
44
+ "sharpe_ratio",
45
+ "drawdown_series",
46
+ "max_drawdown",
47
+ "var_historical",
48
+ "var_parametric",
49
+ "cvar_historical",
50
+ "risk_report",
51
+ "read_prices_sql",
52
+ "write_prices_sql",
53
+ "list_tickers",
54
+ "__version__",
55
+ ]
pandasmfe/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Enables ``python -m pandasmfe prices.csv``."""
2
+
3
+ # Python runs this file when the package is launched with `python -m pandasmfe`.
4
+ from pandasmfe.cli import main
5
+
6
+ # Run the command and pass its exit code (0 = success, 1 = error) to the operating system.
7
+ raise SystemExit(main())
pandasmfe/accessor.py ADDED
@@ -0,0 +1,119 @@
1
+ """The ``.mfe`` accessor: pandasMFE metrics as methods of pandas objects.
2
+
3
+ pandas lets external libraries add a "namespace" to DataFrame and Series
4
+ through ``pandas.api.extensions.register_*_accessor``. pandas classes are NOT
5
+ modified or subclassed: after ``import pandasmfe`` every DataFrame and Series
6
+ simply gains an ``.mfe`` attribute.
7
+
8
+ Two kinds of methods, depending on what the object contains:
9
+
10
+ - on PRICES: ``returns()``, ``drawdown()``, ``max_drawdown()``, ``risk_report()``
11
+ - on RETURNS: ``ann_return()``, ``ann_volatility()``, ``sharpe()``,
12
+ ``var()``, ``cvar()``
13
+
14
+ They chain naturally::
15
+
16
+ prices.mfe.risk_report()
17
+ prices.mfe.returns().mfe.sharpe(risk_free=0.02)
18
+ """
19
+
20
+ # Lets us write type hints such as `pd.DataFrame | pd.Series`.
21
+ from __future__ import annotations
22
+
23
+ # pandas provides the registration decorators used at the bottom of this file.
24
+ import pandas as pd
25
+ # Tells whether a column's data type is numeric (int, float, bool).
26
+ from pandas.api.types import is_numeric_dtype
27
+
28
+ # All the maths lives in metrics.py; the accessor only forwards calls to it.
29
+ from pandasmfe import metrics
30
+
31
+
32
+ class _MFEAccessor:
33
+ """Shared implementation for the DataFrame and Series accessors."""
34
+
35
+ def __init__(self, pandas_obj: pd.DataFrame | pd.Series) -> None:
36
+ # pandas calls this when the user writes `obj.mfe`, passing the object itself.
37
+ # First check that the data can be used...
38
+ self._validate(pandas_obj)
39
+ # ...then store it, so every method below can work on it.
40
+ self._obj = pandas_obj
41
+
42
+ # A static method does not use `self`; it belongs to the class only logically.
43
+ @staticmethod
44
+ def _validate(obj: pd.DataFrame | pd.Series) -> None:
45
+ # A DataFrame has one dtype per column; a Series has one dtype, wrapped in a list
46
+ # so that both cases can be looped over in the same way.
47
+ dtypes = obj.dtypes if isinstance(obj, pd.DataFrame) else [obj.dtype]
48
+ # Every column must be numeric (prices or returns, not text).
49
+ if not all(is_numeric_dtype(d) for d in dtypes):
50
+ # pandas recommends AttributeError when an accessor does not fit the data:
51
+ # for that object `.mfe` simply "does not exist" (so hasattr() returns False).
52
+ raise AttributeError(".mfe requires numeric data (prices or returns)")
53
+
54
+ # ---- methods on PRICES -------------------------------------------------
55
+ def returns(self):
56
+ """Simple returns computed from prices."""
57
+ # Forward to metrics.simple_returns, passing the user's object.
58
+ return metrics.simple_returns(self._obj)
59
+
60
+ def drawdown(self):
61
+ """Drawdown series computed from prices."""
62
+ # Forward to metrics.drawdown_series.
63
+ return metrics.drawdown_series(self._obj)
64
+
65
+ def max_drawdown(self):
66
+ """Maximum drawdown computed from prices."""
67
+ # Forward to metrics.max_drawdown.
68
+ return metrics.max_drawdown(self._obj)
69
+
70
+ def risk_report(self, periods_per_year: int = 252, risk_free: float = 0.0, alpha: float = 0.95):
71
+ """Full risk report computed from prices."""
72
+ # Same defaults as the function, so both interfaces behave identically.
73
+ return metrics.risk_report(self._obj, periods_per_year, risk_free, alpha)
74
+
75
+ # ---- methods on RETURNS ------------------------------------------------
76
+ def ann_return(self, periods_per_year: int = 252):
77
+ """Annualized geometric return (CAGR) from returns."""
78
+ # Forward to metrics.annualized_return.
79
+ return metrics.annualized_return(self._obj, periods_per_year)
80
+
81
+ def ann_volatility(self, periods_per_year: int = 252):
82
+ """Annualized volatility from returns."""
83
+ # Forward to metrics.annualized_volatility.
84
+ return metrics.annualized_volatility(self._obj, periods_per_year)
85
+
86
+ def sharpe(self, risk_free: float = 0.0, periods_per_year: int = 252):
87
+ """Annualized Sharpe ratio from returns."""
88
+ # Forward to metrics.sharpe_ratio.
89
+ return metrics.sharpe_ratio(self._obj, risk_free, periods_per_year)
90
+
91
+ def var(self, alpha: float = 0.95, method: str = "historical"):
92
+ """Value at Risk from returns. ``method``: 'historical' or 'parametric'."""
93
+ # One method with a choice, instead of two separate methods.
94
+ if method == "historical":
95
+ return metrics.var_historical(self._obj, alpha)
96
+ if method == "parametric":
97
+ return metrics.var_parametric(self._obj, alpha)
98
+ # Any other value is an error; !r shows it with quotes, so typos are visible.
99
+ raise ValueError(f"method must be 'historical' or 'parametric', got {method!r}")
100
+
101
+ def cvar(self, alpha: float = 0.95):
102
+ """Historical CVaR / Expected Shortfall from returns."""
103
+ # Forward to metrics.cvar_historical.
104
+ return metrics.cvar_historical(self._obj, alpha)
105
+
106
+
107
+ # The decorator registers this class in pandas under the name "mfe" for DataFrames:
108
+ # from now on `df.mfe` creates DataFrameMFEAccessor(df).
109
+ @pd.api.extensions.register_dataframe_accessor("mfe")
110
+ class DataFrameMFEAccessor(_MFEAccessor):
111
+ """``df.mfe``: one column per asset."""
112
+ # No code needed: every method is inherited from _MFEAccessor.
113
+
114
+
115
+ # Same registration for Series: `s.mfe` creates SeriesMFEAccessor(s).
116
+ @pd.api.extensions.register_series_accessor("mfe")
117
+ class SeriesMFEAccessor(_MFEAccessor):
118
+ """``s.mfe``: a single asset."""
119
+ # No code needed: every method is inherited from _MFEAccessor.
pandasmfe/cli.py ADDED
@@ -0,0 +1,167 @@
1
+ """Command-line interface.
2
+
3
+ pandasmfe prices.csv [options] # prices from a CSV file
4
+ pandasmfe prices.db [options] # prices from a SQLite database (SQL query)
5
+ """
6
+
7
+ # Lets us write type hints such as `str | None`.
8
+ from __future__ import annotations
9
+
10
+ # Standard-library module that reads options typed on the command line.
11
+ import argparse
12
+ # Needed only to recognise database errors (see the except clause in main).
13
+ import sqlite3
14
+ # Gives access to sys.stderr, the output channel for error messages.
15
+ import sys
16
+ # argparse converts file arguments into Path objects (with .suffix, .exists()...).
17
+ from pathlib import Path
18
+
19
+ # pandas reads the CSV and formats the printed report.
20
+ import pandas as pd
21
+
22
+ # The version is defined once, in __init__.py.
23
+ from pandasmfe import __version__
24
+ # The function that computes the whole report.
25
+ from pandasmfe.metrics import risk_report
26
+ # The function that reads prices from a SQLite database.
27
+ from pandasmfe.sql import read_prices_sql
28
+
29
+ # File extensions treated as SQLite databases (a set: we only ask "is it in here?").
30
+ DB_SUFFIXES = {".db", ".sqlite", ".sqlite3"}
31
+
32
+
33
+ def load_prices(
34
+ path: Path, date_col: str | None, sep: str, decimal: str = ".", dayfirst: bool = False
35
+ ) -> pd.DataFrame:
36
+ """Read a CSV of prices: first column (or ``date_col``) = dates, other columns = assets."""
37
+ # sep = field separator (',' or ';'), decimal = decimal mark ('.' or ',').
38
+ df = pd.read_csv(path, sep=sep, decimal=decimal)
39
+ # Use the date column chosen by the user, or the first column if none was given.
40
+ col = date_col or df.columns[0]
41
+ if col not in df.columns:
42
+ # The message lists the available columns, so the user sees the right name.
43
+ raise ValueError(f"Date column '{col}' not found. Columns: {list(df.columns)}")
44
+ # Convert text to dates; dayfirst=True reads 03/01/2024 as 3 January, not 1 March.
45
+ df[col] = pd.to_datetime(df[col], dayfirst=dayfirst)
46
+ # Dates become the index, sorted, so returns are computed in chronological order.
47
+ df = df.set_index(col).sort_index()
48
+ # Convert every column to numbers (non-numbers become NaN) and drop columns that are
49
+ # entirely NaN: text columns such as notes or names disappear automatically.
50
+ df = df.apply(pd.to_numeric, errors="coerce").dropna(axis=1, how="all")
51
+ if df.empty:
52
+ # No usable price column left: say so clearly.
53
+ raise ValueError("No numeric price columns found in the file")
54
+ return df
55
+
56
+
57
+ def select_prices(
58
+ prices: pd.DataFrame, tickers: list[str] | None, start: str | None, end: str | None
59
+ ) -> pd.DataFrame:
60
+ """Apply --tickers/--start/--end to prices read from a CSV (the database does it in SQL)."""
61
+ if tickers:
62
+ # Requested tickers that are not columns of the file (set difference).
63
+ missing = sorted(set(tickers) - set(prices.columns))
64
+ if missing:
65
+ raise ValueError(f"Tickers not found in the file: {missing}")
66
+ # Keep only the requested columns.
67
+ prices = prices[tickers]
68
+ # Cut the date range, both ends included; None on either side means "no limit".
69
+ prices = prices.loc[start:end]
70
+ if prices.empty:
71
+ raise ValueError("No prices left after applying --start/--end")
72
+ return prices
73
+
74
+
75
+ def build_parser() -> argparse.ArgumentParser:
76
+ """Define every option the command accepts (argparse also builds --help from these)."""
77
+ p = argparse.ArgumentParser(
78
+ # Program name shown in the help and in error messages.
79
+ prog="pandasmfe",
80
+ description=(
81
+ "Risk report (return, volatility, Sharpe, drawdown, VaR, CVaR) from a CSV file "
82
+ "or a SQLite database of prices."
83
+ ),
84
+ )
85
+ # Positional, required argument (no dashes): the input file, converted to a Path.
86
+ p.add_argument(
87
+ "source",
88
+ type=Path,
89
+ help="a .csv file (date column + one price column per asset) or a .db SQLite database",
90
+ )
91
+ # nargs="+": one or more values, collected into a list (e.g. --tickers SPY TLT).
92
+ p.add_argument("--tickers", nargs="+", default=None, help="only these assets, e.g. --tickers SPY TLT")
93
+ # Optional date filters, kept as text and validated later.
94
+ p.add_argument("--start", default=None, help="first date included, e.g. 2020-01-01")
95
+ p.add_argument("--end", default=None, help="last date included, e.g. 2024-12-31")
96
+ # CSV reading options; argparse turns --date-col into args.date_col.
97
+ p.add_argument("--date-col", default=None, help="CSV only: name of the date column (default: the first one)")
98
+ p.add_argument("--sep", default=",", help="CSV only: field separator (default ',')")
99
+ p.add_argument("--decimal", default=".", help="CSV only: decimal separator (default '.')")
100
+ # store_true: an on/off switch with no value (True if written, False otherwise).
101
+ p.add_argument("--dayfirst", action="store_true", help="CSV only: dates are in day/month/year format")
102
+ p.add_argument(
103
+ "--eu",
104
+ action="store_true",
105
+ help="shortcut for CSVs exported by European-locale Excel: --sep ';' --decimal ',' --dayfirst",
106
+ )
107
+ # type=int / type=float: argparse converts the typed text into numbers and rejects bad input.
108
+ p.add_argument("--freq", type=int, default=252, help="periods per year: 252 daily, 52, 12 (default 252)")
109
+ p.add_argument("--rf", type=float, default=0.0, help="annual risk-free rate, e.g. 0.02 (default 0)")
110
+ p.add_argument("--alpha", type=float, default=0.95, help="VaR/CVaR confidence level (default 0.95)")
111
+ # Short and long form of the same option.
112
+ p.add_argument("-o", "--output", type=Path, default=None, help="save the report as .csv or .xlsx")
113
+ # Prints "pandasmfe <version>" and exits; %(prog)s is replaced by the program name.
114
+ p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
115
+ return p
116
+
117
+
118
+ def main(argv: list[str] | None = None) -> int:
119
+ """Run the command. Returns the exit code: 0 = success, 1 = error."""
120
+ # argv=None reads the words typed in the terminal; tests pass a list instead.
121
+ args = build_parser().parse_args(argv)
122
+ # --eu sets the three CSV options used by European-locale Excel exports.
123
+ if args.eu:
124
+ args.sep, args.decimal, args.dayfirst = ";", ",", True
125
+ try:
126
+ # The file extension decides where the prices come from.
127
+ if args.source.suffix.lower() in DB_SUFFIXES:
128
+ # Database: the filters become a SQL query.
129
+ prices = read_prices_sql(args.source, args.tickers, args.start, args.end)
130
+ else:
131
+ # CSV: read the file, then filter with pandas.
132
+ prices = load_prices(args.source, args.date_col, args.sep, args.decimal, args.dayfirst)
133
+ prices = select_prices(prices, args.tickers, args.start, args.end)
134
+ # Both paths give the same thing: a wide DataFrame of prices.
135
+ report = risk_report(prices, args.freq, args.rf, args.alpha)
136
+ # Expected problems: missing file (OSError), bad data or options (ValueError),
137
+ # a file that is not a real database (sqlite3.Error).
138
+ except (OSError, ValueError, sqlite3.Error) as exc:
139
+ # A readable message on the error channel instead of a Python traceback.
140
+ print(f"Error: {exc}", file=sys.stderr)
141
+ # Non-zero exit code: tells scripts and the operating system that it failed.
142
+ return 1
143
+
144
+ # Change pandas display options only inside this block: 4 decimals, all columns visible.
145
+ with pd.option_context(
146
+ "display.float_format", "{:.4f}".format,
147
+ "display.max_columns", None,
148
+ "display.width", 200,
149
+ ):
150
+ print(report)
151
+
152
+ # Save the report only if -o/--output was given.
153
+ if args.output:
154
+ # The extension decides the format.
155
+ if args.output.suffix.lower() == ".xlsx":
156
+ report.to_excel(args.output) # needs openpyxl: pip install "pandasMFE[excel]"
157
+ else:
158
+ report.to_csv(args.output)
159
+ print(f"\nReport saved to {args.output}")
160
+ # Exit code 0: success.
161
+ return 0
162
+
163
+
164
+ # Runs main() only when this file is executed directly, not when it is imported.
165
+ if __name__ == "__main__":
166
+ # Pass main's return value (0 or 1) to the operating system as the exit code.
167
+ raise SystemExit(main())
pandasmfe/metrics.py ADDED
@@ -0,0 +1,168 @@
1
+ """Risk and performance metrics built on pandas.
2
+
3
+ Conventions
4
+ -----------
5
+ - ``prices``: a DataFrame (one column per asset) or a Series, indexed by date.
6
+ - ``returns``: simple periodic returns (e.g. daily).
7
+ - ``periods_per_year``: 252 for daily data, 52 for weekly, 12 for monthly.
8
+ - VaR and CVaR are returned as POSITIVE LOSSES (e.g. 0.023 means a 2.3% loss).
9
+ """
10
+
11
+ # Lets us write type hints such as `pd.Series | float` without Python evaluating them.
12
+ from __future__ import annotations
13
+
14
+ # Standard-library normal distribution: gives the z-quantile for the parametric VaR
15
+ # without adding scipy as a dependency.
16
+ from statistics import NormalDist
17
+ # Used to build the type alias below ("this OR that").
18
+ from typing import Union
19
+
20
+ # numpy for the square root used to annualize volatility.
21
+ import numpy as np
22
+ # pandas: every function works on its Series and DataFrame objects.
23
+ import pandas as pd
24
+
25
+ # Short name for "a Series or a DataFrame": every function accepts both,
26
+ # because pandas operations (shift, mean, std, quantile...) work column by column.
27
+ PandasObj = Union[pd.Series, pd.DataFrame]
28
+
29
+
30
+ def _check_alpha(alpha: float) -> None:
31
+ """Reject confidence levels outside (0, 1). Leading underscore = internal helper."""
32
+ # Chained comparison: true only if 0 < alpha AND alpha < 1.
33
+ if not 0 < alpha < 1:
34
+ # Catches the typical mistake of writing 95 instead of 0.95.
35
+ raise ValueError(f"alpha must be in (0, 1), got {alpha}")
36
+
37
+
38
+ def simple_returns(prices: PandasObj) -> PandasObj:
39
+ """Simple returns r_t = P_t / P_{t-1} - 1 (the leading NaN row is dropped).
40
+
41
+ Missing prices are NOT filled: a gap produces NaN on that day and the next,
42
+ and the metrics skip them. Written with ``shift`` instead of ``pct_change``
43
+ because the default NaN handling of ``pct_change`` changed between pandas
44
+ 2.x and 3.x; this way the result is identical on both.
45
+ """
46
+ # (prices <= 0) is a True/False table; .to_numpy().any() is True if ANY cell is True.
47
+ # Going through numpy gives one single bool for both Series and DataFrame.
48
+ if (prices <= 0).to_numpy().any():
49
+ # A zero or negative price would produce meaningless returns.
50
+ raise ValueError("Prices must be strictly positive")
51
+ # shift(1) moves every column down one row, so each date holds yesterday's price;
52
+ # dividing gives P_t / P_{t-1}. dropna(how="all") removes only rows where EVERY
53
+ # asset is NaN (the first row), so one missing asset does not delete the others' data.
54
+ return (prices / prices.shift(1) - 1).dropna(how="all")
55
+
56
+
57
+ def annualized_return(returns: PandasObj, periods_per_year: int = 252) -> PandasObj | float:
58
+ """Geometric annualized return (CAGR): (prod(1 + r)) ** (N / n) - 1."""
59
+ # Number of non-missing returns (count() skips NaN, unlike len()).
60
+ n = returns.count()
61
+ # Total growth over the period: returns compound, so they are multiplied, not added.
62
+ growth = (1 + returns).prod()
63
+ # Raise total growth to N/n to convert it into growth per year.
64
+ return growth ** (periods_per_year / n) - 1
65
+
66
+
67
+ def annualized_volatility(returns: PandasObj, periods_per_year: int = 252) -> PandasObj | float:
68
+ """Sample standard deviation (ddof=1) scaled by sqrt(periods_per_year)."""
69
+ # ddof=1: sample standard deviation (divides by n - 1).
70
+ # Multiply by sqrt(N): with independent returns, variances add up over time,
71
+ # so the yearly standard deviation is sqrt(N) times the per-period one.
72
+ return returns.std(ddof=1) * np.sqrt(periods_per_year)
73
+
74
+
75
+ def sharpe_ratio(
76
+ returns: PandasObj, risk_free: float = 0.0, periods_per_year: int = 252
77
+ ) -> PandasObj | float:
78
+ """Annualized Sharpe ratio: mean excess return / std, scaled by sqrt(N).
79
+
80
+ ``risk_free`` is an ANNUAL rate, converted to a per-period rate.
81
+ """
82
+ # Per-period rate that, compounded N times, gives the annual risk-free rate.
83
+ rf_period = (1 + risk_free) ** (1 / periods_per_year) - 1
84
+ # Excess return of each period over the risk-free rate.
85
+ excess = returns - rf_period
86
+ # Mean scales with N and std with sqrt(N), so their ratio scales with sqrt(N).
87
+ return excess.mean() / excess.std(ddof=1) * np.sqrt(periods_per_year)
88
+
89
+
90
+ def drawdown_series(prices: PandasObj) -> PandasObj:
91
+ """Drawdown at each date: P_t / max(P_0..P_t) - 1 (values <= 0)."""
92
+ # cummax() is the highest price seen so far; the drawdown is the % distance from it.
93
+ return prices / prices.cummax() - 1
94
+
95
+
96
+ def max_drawdown(prices: PandasObj) -> PandasObj | float:
97
+ """Maximum drawdown (a negative number, e.g. -0.35 = -35%)."""
98
+ # The worst (most negative) drawdown: the largest loss from a previous peak.
99
+ return drawdown_series(prices).min()
100
+
101
+
102
+ def var_historical(returns: PandasObj, alpha: float = 0.95) -> PandasObj | float:
103
+ """Historical VaR: minus the (1 - alpha) quantile of returns."""
104
+ # Stop immediately if alpha is not between 0 and 1.
105
+ _check_alpha(alpha)
106
+ # Empirical quantile (e.g. the 5% worst return), sign flipped to a positive loss.
107
+ # No assumption on the distribution: the observed data are used as they are.
108
+ return -returns.quantile(1 - alpha)
109
+
110
+
111
+ def var_parametric(returns: PandasObj, alpha: float = 0.95) -> PandasObj | float:
112
+ """Gaussian VaR: -(mu + z_{1-alpha} * sigma)."""
113
+ # Stop immediately if alpha is not between 0 and 1.
114
+ _check_alpha(alpha)
115
+ # Quantile of the standard normal, e.g. z = -1.645 for alpha = 0.95.
116
+ z = NormalDist().inv_cdf(1 - alpha)
117
+ # Assumes normal returns: the quantile is mean + z * std; sign flipped to a positive loss.
118
+ return -(returns.mean() + z * returns.std(ddof=1))
119
+
120
+
121
+ def cvar_historical(returns: PandasObj, alpha: float = 0.95) -> PandasObj | float:
122
+ """Historical CVaR / Expected Shortfall: average loss beyond the historical VaR."""
123
+ # Stop immediately if alpha is not between 0 and 1.
124
+ _check_alpha(alpha)
125
+ # With a DataFrame the filter below must be done asset by asset:
126
+ # apply() runs this same function on each column (each column is a Series).
127
+ if isinstance(returns, pd.DataFrame):
128
+ return returns.apply(cvar_historical, alpha=alpha)
129
+ # The VaR threshold: the (1 - alpha) quantile of returns.
130
+ threshold = returns.quantile(1 - alpha)
131
+ # Keep only the returns in the tail (boolean indexing), average them,
132
+ # and flip the sign: the average loss on the worst days.
133
+ return -returns[returns <= threshold].mean()
134
+
135
+
136
+ def risk_report(
137
+ prices: PandasObj,
138
+ periods_per_year: int = 252,
139
+ risk_free: float = 0.0,
140
+ alpha: float = 0.95,
141
+ ) -> pd.DataFrame:
142
+ """Summary table: one row per asset, one column per metric."""
143
+ # A single Series becomes a one-column DataFrame, so the report always has one row per asset.
144
+ if isinstance(prices, pd.Series):
145
+ # Use the Series name if it has one, otherwise "asset".
146
+ prices = prices.to_frame(name=prices.name or "asset")
147
+ # Returns are computed once and reused by every return-based metric.
148
+ rets = simple_returns(prices)
149
+ # Confidence level as an integer for the column names (round() avoids 0.29*100 = 28.999...).
150
+ pct = int(round(alpha * 100))
151
+ # Each value is a Series indexed by asset; pandas aligns them into columns.
152
+ report = pd.DataFrame(
153
+ {
154
+ "ann_return": annualized_return(rets, periods_per_year),
155
+ "ann_volatility": annualized_volatility(rets, periods_per_year),
156
+ "sharpe": sharpe_ratio(rets, risk_free, periods_per_year),
157
+ # The drawdown is computed on PRICES, not returns.
158
+ "max_drawdown": max_drawdown(prices),
159
+ f"var_hist_{pct}": var_historical(rets, alpha),
160
+ f"var_param_{pct}": var_parametric(rets, alpha),
161
+ f"cvar_hist_{pct}": cvar_historical(rets, alpha),
162
+ # How many returns were used for each asset.
163
+ "n_obs": rets.count(),
164
+ }
165
+ )
166
+ # Name the index column "asset".
167
+ report.index.name = "asset"
168
+ return report
pandasmfe/py.typed ADDED
File without changes
pandasmfe/sql.py ADDED
@@ -0,0 +1,160 @@
1
+ """Store and read prices in a SQLite database.
2
+
3
+ SQLite is a full SQL database kept in a single file (e.g. ``prices.db``).
4
+ It ships with Python (module ``sqlite3``), so no extra dependency is needed.
5
+
6
+ Prices are stored in LONG format, one row per (date, ticker)::
7
+
8
+ date ticker close
9
+ 2024-01-02 AAPL 185.64
10
+ 2024-01-02 MSFT 370.87
11
+
12
+ and returned in WIDE format, one column per ticker, ready for ``.mfe``.
13
+ """
14
+
15
+ # Lets us write type hints such as `str | None`.
16
+ from __future__ import annotations
17
+
18
+ # The SQLite database driver, part of Python's standard library.
19
+ import sqlite3
20
+ # closing() guarantees the database connection is closed, even if an error occurs.
21
+ from contextlib import closing
22
+ # Path represents a file path and offers methods such as .exists().
23
+ from pathlib import Path
24
+ # Type hint for "anything that can be looped over" (list, tuple...).
25
+ from typing import Iterable
26
+
27
+ # pandas runs the SQL queries and reshapes the results.
28
+ import pandas as pd
29
+
30
+ # SQL that creates the table if it does not exist yet (upper case = a constant).
31
+ SCHEMA = """
32
+ CREATE TABLE IF NOT EXISTS prices (
33
+ date TEXT NOT NULL, -- ISO format 'YYYY-MM-DD': sorts correctly as text
34
+ ticker TEXT NOT NULL, -- asset identifier, e.g. 'SPY'
35
+ close REAL NOT NULL CHECK (close > 0), -- the database itself rejects zero/negative prices
36
+ PRIMARY KEY (date, ticker) -- one price per ticker per day, no duplicates
37
+ )
38
+ """
39
+
40
+
41
+ def _iso(day: str | None) -> str | None:
42
+ """Normalize a date to 'YYYY-MM-DD' (raises ValueError if it is not a date)."""
43
+ # None means "no date filter"; otherwise parse the date and rewrite it in ISO format,
44
+ # the same format used in the database.
45
+ return None if day is None else pd.Timestamp(day).strftime("%Y-%m-%d")
46
+
47
+
48
+ def write_prices_sql(prices: pd.DataFrame, db_path: str | Path) -> int:
49
+ """Save a wide DataFrame of prices (dates x tickers) into the ``prices`` table.
50
+
51
+ Existing (date, ticker) rows are replaced, so the function can be re-run to
52
+ update the database. Returns the number of rows written.
53
+ """
54
+ # Reshape from WIDE (one column per ticker) to LONG (one row per date and ticker).
55
+ long = (
56
+ # Give the index the name "date"...
57
+ prices.rename_axis("date")
58
+ # ...and turn it into an ordinary column.
59
+ .reset_index()
60
+ # "Melt" the ticker columns into rows: date stays, each ticker becomes a row.
61
+ .melt(id_vars="date", var_name="ticker", value_name="close")
62
+ # Do not store prices that do not exist.
63
+ .dropna(subset=["close"])
64
+ )
65
+ # Write every date as ISO text 'YYYY-MM-DD', the format used in the table.
66
+ long["date"] = pd.to_datetime(long["date"]).dt.strftime("%Y-%m-%d")
67
+ # One plain tuple (date, ticker, close) per row: the format sqlite3 expects.
68
+ rows = list(long[["date", "ticker", "close"]].itertuples(index=False, name=None))
69
+
70
+ # Open (or create) the database file; closing() closes it at the end of the block.
71
+ with closing(sqlite3.connect(db_path)) as con:
72
+ # Create the table if it is not there yet.
73
+ con.execute(SCHEMA)
74
+ # Insert all rows; each ? is filled by one value of the tuple, in order.
75
+ # INSERT OR REPLACE overwrites an existing (date, ticker) instead of duplicating it.
76
+ con.executemany(
77
+ "INSERT OR REPLACE INTO prices (date, ticker, close) VALUES (?, ?, ?)", rows
78
+ )
79
+ # Confirm the changes: without commit they would be lost when closing.
80
+ con.commit()
81
+ # Tell the caller how many rows were written.
82
+ return len(rows)
83
+
84
+
85
+ def read_prices_sql(
86
+ db_path: str | Path,
87
+ tickers: Iterable[str] | None = None,
88
+ start: str | None = None,
89
+ end: str | None = None,
90
+ ) -> pd.DataFrame:
91
+ """Read prices from the ``prices`` table with a SQL query, as a wide DataFrame.
92
+
93
+ ``tickers``, ``start`` and ``end`` become WHERE conditions. They are passed as
94
+ query parameters (``?``), never pasted into the SQL text, so user input cannot
95
+ alter the query (protection against SQL injection).
96
+ """
97
+ # sqlite3.connect would silently CREATE a missing file, so check it exists first.
98
+ path = Path(db_path)
99
+ if not path.exists():
100
+ raise FileNotFoundError(f"Database not found: {path}")
101
+
102
+ # The query is built piece by piece. "WHERE 1 = 1" is always true: it lets every
103
+ # filter below start with AND, without special-casing the first one.
104
+ sql = "SELECT date, ticker, close FROM prices WHERE 1 = 1"
105
+ # The values for the ? placeholders, in the same order as they appear in the query.
106
+ params: list[str] = []
107
+ # No tickers given -> empty list; otherwise turn whatever was passed into a list.
108
+ tickers = list(tickers) if tickers else []
109
+ if tickers:
110
+ # One ? per ticker, e.g. "IN (?, ?)". Only placeholders go into the text,
111
+ # never the ticker names themselves.
112
+ sql += f" AND ticker IN ({', '.join('?' for _ in tickers)})"
113
+ # The ticker names travel separately, as parameters.
114
+ params += tickers
115
+ if start:
116
+ # ISO dates compare correctly as text: '2024-01-05' >= '2023-12-31'.
117
+ sql += " AND date >= ?"
118
+ params.append(_iso(start))
119
+ if end:
120
+ sql += " AND date <= ?"
121
+ params.append(_iso(end))
122
+ # Sorted output: by date, then by ticker.
123
+ sql += " ORDER BY date, ticker"
124
+
125
+ # Open the database, run the query with its parameters, get a LONG DataFrame.
126
+ with closing(sqlite3.connect(path)) as con:
127
+ long = pd.read_sql_query(sql, con, params=params)
128
+
129
+ # Requested tickers that came back empty (set difference). Checked first,
130
+ # so the error names the missing ticker instead of just "no prices".
131
+ missing = sorted(set(tickers) - set(long["ticker"]))
132
+ if missing:
133
+ raise ValueError(f"Tickers not found in the database for this selection: {missing}")
134
+ # Nothing matched the filters at all (e.g. a start date in the future).
135
+ if long.empty:
136
+ raise ValueError("No prices found in the database for this selection")
137
+
138
+ # Reshape back to WIDE: dates as index, one column per ticker.
139
+ wide = long.pivot(index="date", columns="ticker", values="close")
140
+ # Dates come back from the database as text: convert them to real dates.
141
+ wide.index = pd.to_datetime(wide.index)
142
+ # Tidy the labels so the result looks like a DataFrame read from a CSV.
143
+ wide.index.name = "date"
144
+ wide.columns.name = None
145
+ return wide
146
+
147
+
148
+ def list_tickers(db_path: str | Path) -> pd.DataFrame:
149
+ """Summary of the database: first date, last date and number of prices per ticker."""
150
+ # One summary row per ticker (GROUP BY); MIN/MAX work on dates because they are ISO text.
151
+ with closing(sqlite3.connect(db_path)) as con:
152
+ return pd.read_sql_query(
153
+ """
154
+ SELECT ticker, MIN(date) AS first_date, MAX(date) AS last_date, COUNT(*) AS n_prices
155
+ FROM prices
156
+ GROUP BY ticker
157
+ ORDER BY ticker
158
+ """,
159
+ con,
160
+ )
@@ -0,0 +1,169 @@
1
+ Metadata-Version: 2.4
2
+ Name: pandasMFE
3
+ Version: 0.1.0
4
+ Summary: Risk and performance metrics (Sharpe, drawdown, VaR, CVaR) for pandas, with a .mfe accessor
5
+ Author: Gianmarco Scafarto
6
+ License-Expression: MIT
7
+ Keywords: pandas,finance,risk,var,cvar,sharpe,drawdown
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Intended Audience :: Financial and Insurance Industry
14
+ Classifier: Topic :: Office/Business :: Financial :: Investment
15
+ Requires-Python: >=3.11
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: pandas>=2.2
19
+ Requires-Dist: numpy>=1.26
20
+ Provides-Extra: excel
21
+ Requires-Dist: openpyxl>=3.1; extra == "excel"
22
+ Provides-Extra: data
23
+ Requires-Dist: yfinance; extra == "data"
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest>=7; extra == "dev"
26
+ Requires-Dist: build; extra == "dev"
27
+ Requires-Dist: twine; extra == "dev"
28
+ Requires-Dist: pyinstaller; extra == "dev"
29
+ Dynamic: license-file
30
+
31
+ # pandasMFE
32
+
33
+ Risk and performance metrics for **pandas**: annualized return (CAGR), volatility,
34
+ Sharpe ratio, maximum drawdown, historical and parametric VaR, CVaR (Expected Shortfall).
35
+
36
+ pandasMFE **extends pandas without modifying it**: after `import pandasmfe`, every
37
+ DataFrame and Series gains an `.mfe` namespace, using pandas' official
38
+ [accessor API](https://pandas.pydata.org/docs/development/extending.html).
39
+ Prices can be read from a CSV file or from a **SQLite database** with a SQL query.
40
+
41
+ > pandasMFE is an independent project and is not affiliated with the pandas project.
42
+
43
+ ## Installation
44
+
45
+ Requires Python 3.11+.
46
+
47
+ ```bash
48
+ pip install pandasMFE # library + `pandasmfe` command
49
+ pip install "pandasMFE[excel]" # + .xlsx export
50
+ pip install "pandasMFE[data]" # + yfinance, to download real prices
51
+ ```
52
+
53
+ ## Usage: the `.mfe` accessor
54
+
55
+ ```python
56
+ import pandas as pd
57
+ import pandasmfe # registers .mfe
58
+
59
+ prices = pd.read_csv("prices.csv", index_col=0, parse_dates=True)
60
+
61
+ # methods on PRICES
62
+ prices.mfe.risk_report(risk_free=0.02, alpha=0.95)
63
+ prices.mfe.max_drawdown()
64
+ prices.mfe.drawdown() # full drawdown series
65
+ returns = prices.mfe.returns()
66
+
67
+ # methods on RETURNS
68
+ returns.mfe.sharpe(risk_free=0.02)
69
+ returns.mfe.ann_volatility()
70
+ returns.mfe.var(alpha=0.99) # historical
71
+ returns.mfe.var(alpha=0.99, method="parametric") # Gaussian
72
+ returns.mfe.cvar(alpha=0.99)
73
+
74
+ # works on a single Series too, and chains
75
+ prices["STOCK_A"].mfe.returns().mfe.sharpe()
76
+ ```
77
+
78
+ ## Usage: plain functions
79
+
80
+ ```python
81
+ import pandasmfe as pm
82
+
83
+ pm.risk_report(prices, periods_per_year=252, risk_free=0.02, alpha=0.95)
84
+ pm.var_historical(pm.simple_returns(prices), alpha=0.99)
85
+ ```
86
+
87
+ ## Usage: real prices from a SQL database
88
+
89
+ Prices are stored in a SQLite database (one file, built into Python: no extra
90
+ dependency) and read back with a SQL query.
91
+
92
+ ```bash
93
+ pip install "pandasMFE[data]"
94
+ python examples/download_prices.py # SPY, AAPL, MSFT, TLT, GLD since 2015 -> examples/prices.db
95
+ ```
96
+
97
+ ```python
98
+ import pandasmfe as pm
99
+
100
+ prices = pm.read_prices_sql("examples/prices.db", tickers=["SPY", "TLT"], start="2020-01-01")
101
+ prices.mfe.risk_report(risk_free=0.02)
102
+
103
+ pm.list_tickers("examples/prices.db") # what is in the database
104
+ pm.write_prices_sql(my_prices, "my.db") # save any wide DataFrame of prices
105
+ ```
106
+
107
+ Table schema: `prices(date TEXT, ticker TEXT, close REAL)`, one row per date and ticker.
108
+ More queries in `examples/queries.sql`.
109
+
110
+ ## Usage: command line
111
+
112
+ ```bash
113
+ pandasmfe prices.csv
114
+ pandasmfe prices.csv --rf 0.02 --alpha 0.99 -o report.csv
115
+ pandasmfe excel_export.csv --eu -o report.xlsx # ';' separator, decimal comma, dd/mm/yyyy dates
116
+ pandasmfe examples/prices.db --tickers SPY TLT --start 2020-01-01
117
+ python -m pandasmfe prices.csv # equivalent
118
+ ```
119
+
120
+ `--tickers`, `--start` and `--end` work with both CSV files and databases.
121
+ Expected CSV format: first column = dates, then one price column per asset.
122
+
123
+ ```
124
+ Date,STOCK_A,STOCK_B
125
+ 2024-01-02,185.6,370.9
126
+ 2024-01-03,184.2,370.6
127
+ ```
128
+
129
+ `examples/sample_prices.csv` contains **synthetic** prices (geometric Brownian motion),
130
+ useful to try the package without downloading anything.
131
+
132
+ ## Standalone executable
133
+
134
+ The same command can be packaged with PyInstaller into a folder that runs on a
135
+ computer without Python:
136
+
137
+ ```bash
138
+ pip install pyinstaller
139
+ pyinstaller --onedir --name pandasmfe --clean --noconfirm standalone/pandasmfe_app.py
140
+ dist/pandasmfe/pandasmfe examples/sample_prices.csv
141
+ ```
142
+
143
+ PyInstaller builds for the operating system it runs on (a Windows `.exe` must be built on Windows).
144
+
145
+ ## Conventions
146
+
147
+ | Metric | Formula | Sign |
148
+ |---|---|---|
149
+ | `ann_return` | (∏(1+r))^(N/n) − 1 | ± |
150
+ | `ann_volatility` | σ · √N (ddof=1) | + |
151
+ | `sharpe` | mean(r − rf) / σ · √N | ± |
152
+ | `max_drawdown` | min(P / cummax(P) − 1) | ≤ 0 |
153
+ | `var_hist_95` | −quantile₅%(r) | positive loss |
154
+ | `var_param_95` | −(μ + z₅% σ) | positive loss |
155
+ | `cvar_hist_95` | −mean(r ∣ r ≤ quantile₅%) | positive loss |
156
+
157
+ N = periods per year (252 for daily data), n = number of observations.
158
+ Missing prices are never filled: a gap gives NaN returns, which are skipped.
159
+
160
+ ## Tests
161
+
162
+ ```bash
163
+ pip install -e ".[dev]"
164
+ pytest
165
+ ```
166
+
167
+ ## License
168
+
169
+ MIT
@@ -0,0 +1,13 @@
1
+ pandasmfe/__init__.py,sha256=VCJaTG2i6DfcZh4RyWJEA3XZne0vtM8ek5MHQ6sffq4,1740
2
+ pandasmfe/__main__.py,sha256=X9K64KufillN0IeAE0iEO8sHt809XiHNGPmCkIaNz7E,280
3
+ pandasmfe/accessor.py,sha256=w7nJgVAA8Y4PwtQQzg0MaJFYJ_ZbUhVzlXzEVQo0fqY,5474
4
+ pandasmfe/cli.py,sha256=ZSB2_ucsxm8VjSnO7bbSO5nUjuDe6BvcWb0wnhWN5lc,8236
5
+ pandasmfe/metrics.py,sha256=k4inrWfHewGJ-aIbBoS3sBHrPQVuTNjHu6piRkhKLYM,7932
6
+ pandasmfe/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ pandasmfe/sql.py,sha256=G1zPW8_3B-oL49UFfeyfJSqA0GvuqturYHELfeJwIdE,7046
8
+ pandasmfe-0.1.0.dist-info/licenses/LICENSE,sha256=E53z5acNO8dsoaoDEdKg53hGoFt1nubkyLSsBm0fm60,1078
9
+ pandasmfe-0.1.0.dist-info/METADATA,sha256=j6TZzcqZO4CzN2fQEmG0YoxydQIWdazIRh5Khc6Dp_I,5527
10
+ pandasmfe-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ pandasmfe-0.1.0.dist-info/entry_points.txt,sha256=y2jUc8YzlnCNU5hEPXBmDz1qPbJ8GbAjWgq6G5Sf1d4,49
12
+ pandasmfe-0.1.0.dist-info/top_level.txt,sha256=9YeTj1Qe57Zpw6IMQlAB4N_5cIrYS2RbBLy9lQ4AfPg,10
13
+ pandasmfe-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pandasmfe = pandasmfe.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The pandasMFE authors
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
+ pandasmfe