Metadata-Version: 2.4
Name: pandasMFE
Version: 0.1.0
Summary: Risk and performance metrics (Sharpe, drawdown, VaR, CVaR) for pandas, with a .mfe accessor
Author: Gianmarco Scafarto
License-Expression: MIT
Keywords: pandas,finance,risk,var,cvar,sharpe,drawdown
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Topic :: Office/Business :: Financial :: Investment
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pandas>=2.2
Requires-Dist: numpy>=1.26
Provides-Extra: excel
Requires-Dist: openpyxl>=3.1; extra == "excel"
Provides-Extra: data
Requires-Dist: yfinance; extra == "data"
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Requires-Dist: pyinstaller; extra == "dev"
Dynamic: license-file

# pandasMFE

Risk and performance metrics for **pandas**: annualized return (CAGR), volatility,
Sharpe ratio, maximum drawdown, historical and parametric VaR, CVaR (Expected Shortfall).

pandasMFE **extends pandas without modifying it**: after `import pandasmfe`, every
DataFrame and Series gains an `.mfe` namespace, using pandas' official
[accessor API](https://pandas.pydata.org/docs/development/extending.html).
Prices can be read from a CSV file or from a **SQLite database** with a SQL query.

> pandasMFE is an independent project and is not affiliated with the pandas project.

## Installation

Requires Python 3.11+.

```bash
pip install pandasMFE              # library + `pandasmfe` command
pip install "pandasMFE[excel]"     # + .xlsx export
pip install "pandasMFE[data]"      # + yfinance, to download real prices
```

## Usage: the `.mfe` accessor

```python
import pandas as pd
import pandasmfe  # registers .mfe

prices = pd.read_csv("prices.csv", index_col=0, parse_dates=True)

# methods on PRICES
prices.mfe.risk_report(risk_free=0.02, alpha=0.95)
prices.mfe.max_drawdown()
prices.mfe.drawdown()            # full drawdown series
returns = prices.mfe.returns()

# methods on RETURNS
returns.mfe.sharpe(risk_free=0.02)
returns.mfe.ann_volatility()
returns.mfe.var(alpha=0.99)                       # historical
returns.mfe.var(alpha=0.99, method="parametric")  # Gaussian
returns.mfe.cvar(alpha=0.99)

# works on a single Series too, and chains
prices["STOCK_A"].mfe.returns().mfe.sharpe()
```

## Usage: plain functions

```python
import pandasmfe as pm

pm.risk_report(prices, periods_per_year=252, risk_free=0.02, alpha=0.95)
pm.var_historical(pm.simple_returns(prices), alpha=0.99)
```

## Usage: real prices from a SQL database

Prices are stored in a SQLite database (one file, built into Python: no extra
dependency) and read back with a SQL query.

```bash
pip install "pandasMFE[data]"
python examples/download_prices.py      # SPY, AAPL, MSFT, TLT, GLD since 2015 -> examples/prices.db
```

```python
import pandasmfe as pm

prices = pm.read_prices_sql("examples/prices.db", tickers=["SPY", "TLT"], start="2020-01-01")
prices.mfe.risk_report(risk_free=0.02)

pm.list_tickers("examples/prices.db")   # what is in the database
pm.write_prices_sql(my_prices, "my.db") # save any wide DataFrame of prices
```

Table schema: `prices(date TEXT, ticker TEXT, close REAL)`, one row per date and ticker.
More queries in `examples/queries.sql`.

## Usage: command line

```bash
pandasmfe prices.csv
pandasmfe prices.csv --rf 0.02 --alpha 0.99 -o report.csv
pandasmfe excel_export.csv --eu -o report.xlsx      # ';' separator, decimal comma, dd/mm/yyyy dates
pandasmfe examples/prices.db --tickers SPY TLT --start 2020-01-01
python -m pandasmfe prices.csv                      # equivalent
```

`--tickers`, `--start` and `--end` work with both CSV files and databases.
Expected CSV format: first column = dates, then one price column per asset.

```
Date,STOCK_A,STOCK_B
2024-01-02,185.6,370.9
2024-01-03,184.2,370.6
```

`examples/sample_prices.csv` contains **synthetic** prices (geometric Brownian motion),
useful to try the package without downloading anything.

## Standalone executable

The same command can be packaged with PyInstaller into a folder that runs on a
computer without Python:

```bash
pip install pyinstaller
pyinstaller --onedir --name pandasmfe --clean --noconfirm standalone/pandasmfe_app.py
dist/pandasmfe/pandasmfe examples/sample_prices.csv
```

PyInstaller builds for the operating system it runs on (a Windows `.exe` must be built on Windows).

## Conventions

| Metric | Formula | Sign |
|---|---|---|
| `ann_return` | (∏(1+r))^(N/n) − 1 | ± |
| `ann_volatility` | σ · √N (ddof=1) | + |
| `sharpe` | mean(r − rf) / σ · √N | ± |
| `max_drawdown` | min(P / cummax(P) − 1) | ≤ 0 |
| `var_hist_95` | −quantile₅%(r) | positive loss |
| `var_param_95` | −(μ + z₅% σ) | positive loss |
| `cvar_hist_95` | −mean(r ∣ r ≤ quantile₅%) | positive loss |

N = periods per year (252 for daily data), n = number of observations.
Missing prices are never filled: a gap gives NaN returns, which are skipped.

## Tests

```bash
pip install -e ".[dev]"
pytest
```

## License

MIT
