Metadata-Version: 2.4
Name: portblend
Version: 0.2.3
Summary: Local-First Python SDK and CLI for PortBlend strategy correlation matrix calculation, portfolio weight optimization, and drawdown minimization.
Author-email: PortBlend Research <research@portblend.com>
License: MIT
Project-URL: Homepage, https://app.portblend.com
Project-URL: Documentation, https://app.portblend.com/docs
Project-URL: Repository, https://github.com/portblend-research/portblend-python
Keywords: correlation-matrix,portfolio-blending,equity-curve,drawdown-minimization,quant-finance,sharpe-optimization,ai-agent-tools,llm-tools,nav-analytics,trading-telemetry,local-first
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Topic :: Office/Business :: Financial :: Investment
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.28.0
Requires-Dist: pandas>=1.5.0
Requires-Dist: numpy>=1.20.0
Requires-Dist: scipy>=1.9.0
Requires-Dist: openpyxl>=3.0.0
Requires-Dist: tabulate>=0.9.0
Dynamic: license-file

# PortBlend Python SDK & CLI (`portblend`)

[![PyPI version](https://img.shields.io/badge/pypi-v0.2.3-blue.svg)](https://pypi.org/project/portblend/)
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/portblend-research/portblend-python/blob/main/doc/examples/01_quickstart_portblend.ipynb)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python 3.9+](https://img.shields.io/badge/python-3.9%2B-blue.svg)](https://www.python.org/)

Official Python SDK and Command-Line Interface (`portblend`) for **100% Local-First** strategy return correlation matrix calculation, SLSQP portfolio weight optimization, and quantitative drawdown management.

---

## 1. Core Philosophy: 100% Local-First

- **Zero API Key Required:** Core calculations execute 100% locally on your CPU with zero network calls.
- **Zero Alpha Leakage:** Strategy names, NAV time series, and trades never leave your local machine or VPC.
- **Instant Microsecond Performance:** Matrix correlations ($< 5\text{ ms}$) and SLSQP multi-objective optimization ($< 50\text{ ms}$) run in local RAM.
- **Air-Gap Ready:** Works completely offline in secure environments without internet access.

---

## 2. Installation

```bash
pip install portblend
```

### Dependencies
- Python 3.9+
- `numpy >= 1.20.0`
- `scipy >= 1.9.0`
- `pandas >= 1.5.0`
- `openpyxl >= 3.0.0`
- `tabulate >= 0.9.0`

---

## 3. Supported Input File Formats & Data Layouts

PortBlend's built-in `DataTransformer` automatically handles dirty, real-world data files without manual preprocessing.

### Supported File Types
- **CSV (`.csv`)** — auto-detects commas `,`, semicolons `;`, tabs `\t`, or pipes `|`
- **TSV / TXT (`.tsv`, `.txt`)** — tab-separated or fixed-width text
- **Excel Spreadsheets (`.xlsx`, `.xls`)** — multi-sheet or single-sheet workbooks
- **Pandas DataFrames** — direct in-memory Python objects

### Supported Data Layouts

#### Layout A: Multi-Strategy Matrix (Recommended for Portfolios)
A single file containing a Date column and multiple strategy columns:
```csv
Date,Nifty_Trend,BankNifty_Reversal,Gold_Momentum
2026-01-01,100.0,100.0,100.0
2026-01-02,102.5,98.2,100.4
2026-01-03,101.8,99.0,100.8
```

#### Layout B: Single-Strategy Timeseries
A file for an individual strategy:
```csv
Date,Close
2026-01-01,100.0
2026-01-02,102.5
2026-01-03,101.8
```

#### Layout C: Directory of CSVs
Point to an entire directory; PortBlend will scan, parse, and merge all strategy CSVs inside it:
```bash
portblend correlate --file ./my_strategies/
```

### Automatic Data Cleansing
- **Header Auto-Detection:** Automatically skips broker metadata, disclaimers, and empty rows at the top.
- **Fuzzy Column Matching:** Matches column names like `date`, `time`, `obs_date`, `tradedate`, `timestamp`.
- **Date Normalization:** Parses ISO (`2026-01-15`), European dots (`15.01.2026`), slashes (`01/15/2026`), or compact dates.
- **Currency & Number Cleansing:** Automatically strips currency symbols (`$`, `€`, `₹`, `£`), thousand commas (`1,250.50`), and `%` signs.

---

## 4. CLI Quickstart (Command Line)

The CLI is completely self-documenting.

### Discover Commands & Help
```bash
# Top-level help and target options
portblend --help

# Detailed options for any specific command
portblend correlate --help
portblend analyze --help
portblend drawdown --help

# Print copy-pasteable code recipes
portblend examples
```

### CLI Command Recipes (100% Offline)
```bash
# 1. Compute Pairwise Return Correlation Matrix
portblend correlate --file strategies.csv

# 2. Output Machine-Readable JSON (for scripting / jq piping)
portblend correlate --file strategies.csv --json

# 3. Optimize Portfolio Strategy Allocations (SLSQP)
portblend analyze --file strategies.csv --target protection
portblend analyze --file strategies.csv --target recovery --no-cash
portblend analyze --file strategies.csv --target efficiency --json

# 4. Analyze Drawdown Dynamics on an Individual Strategy
portblend drawdown --file my_strategy.csv

# 5. Run Interactive Offline Demo
portblend demo
```

---

## 5. Python SDK Quickstart

### Initialize Client (Zero-Key Local Mode)
```python
from portblend import PortBlendClient

# 100% local, runs offline on CPU with zero network calls
client = PortBlendClient()

# 1. Pairwise Correlation Matrix (returns pandas.DataFrame)
df_corr = client.correlate("strategies.csv")
print(df_corr)

# 2. Portfolio Blending & Optimization
result = client.blend(
    data="strategies.csv",
    target="protection",            # Minimize peak-to-trough drawdown
    allow_cash=True,                # Allow cash buffer if beneficial
    rebalance_frequency="monthly"   # "monthly" | "weekly" | "quarterly" | "yearly"
)

result.summary()                    # Displays ASCII metrics comparison table
print("Weights:", result.weights)   # {'StrategyA': 63.9, 'StrategyB': 36.1}
print("Blended Max Drawdown:", result.metrics["max_drawdown_pct"], "%")

# 3. Single-Strategy Drawdown Dynamics
dcd = client.drawdown("strategies.csv", series_id="StrategyA")
print("Max DD:", dcd["summary"]["max_drawdown_pct"], "%")
print("Total Drawdown Episodes:", dcd["summary"]["total_episodes"])
```

### Direct Mathematical Optimizer (Pure Weights Dictionary)
If you only need optimal weights without instantiating client classes:
```python
from portblend.optimize import optimize_portfolio_weights

weights = optimize_portfolio_weights(
    data="strategies.csv",
    target="recovery",   # Maximize Calmar Ratio
    allow_cash=False     # Enforce exactly 100.0% allocated
)
print(weights)
# {'StrategyA': 63.9, 'StrategyB': 36.1}
```

---

## 6. Optimization Target Matrix

| Target Name | Alias | Mathematical Objective | Best For |
| :--- | :--- | :--- | :--- |
| `protection` | `min_drawdown` | $\min(\text{Max Peak-to-Trough Drawdown})$ | Capital preservation, prop funding limits |
| `efficiency` | `max_sharpe` | $\max\left(\frac{\text{CAGR} - r_f}{\sigma}\right)$ | Maximum risk-adjusted return |
| `recovery` | `max_calmar` | $\max\left(\frac{\text{CAGR}}{\text{Max Drawdown}}\right)$ | Fast post-drawdown recovery |
| `stability` | `min_volatility` | $\min(\text{Annualized Volatility } \sigma)$ | Smooth equity curve, low daily variance |
| `downside_safety` | `max_sortino` | $\max\left(\frac{\text{CAGR}}{\text{Downside Semi-Variance}}\right)$ | Penalizing only loss days |
| `risk_balance` | `balanced_protection` | Dynamic Pareto balance ($\min(\text{Max DD} - \lambda \cdot \text{CAGR})$) | Optimal profit/risk balance |
| `buffered` | `buffered_allocation` | Calmar optimization + adaptive Cash buffer ($0\%\text{--}50\%$) | Defensive market regime shifts |

---

## 7. Documentation & Resources

- **CLI Reference Guide:** `doc/2_design/api/Local_First_CLI_Guide.md`
- **Python SDK Developer Guide:** `doc/2_design/api/Local_First_Python_SDK_Guide.md`
- **Interactive Web App:** [https://app.portblend.com](https://app.portblend.com)
- **AI Agent Context:** [https://app.portblend.com/llms.txt](https://app.portblend.com/llms.txt)
