quantum-portfolio-opt 0.1.1
Hybrid Quantum-Classical Portfolio Optimization with IBM Qiskit
License: MIT
Requires Python: >=3.9
Keywords: quantum, portfolio, optimization, finance, qiskit, machine-learning, QAOA

# Quantfolio 🚀⚛️

[![PyPI version](https://badge.fury.io/py/quantfolio.svg)](https://badge.fury.io/py/quantfolio)
[![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**Hybrid Quantum-Classical Portfolio Optimization** powered by IBM Qiskit and Deep Learning.

Quantfolio combines classical machine learning (Transformers/LSTM) with quantum optimization algorithms (QAOA) to optimize financial portfolios, offering a cutting-edge approach to asset allocation.

---

## ✨ Features

- 🌌 **Quantum Optimization**: QAOA (Quantum Approximate Optimization Algorithm) for portfolio selection
- 🧠 **Classical ML**: Transformer and LSTM models for return prediction
- 📊 **Hybrid Approach**: Best of both worlds - ML predictions + quantum optimization
- 📈 **Financial Metrics**: Sharpe Ratio, Sortino Ratio, VaR, CVaR, Maximum Drawdown
- 🎨 **Visualization**: Beautiful plots for weights, efficient frontier, and portfolio evolution
- ⚡ **Easy API**: Simple interface for quick prototyping and production use

---

## 🔧 Installation

```bash
pip install quantum-portfolio-opt
```

**Requirements**: Python 3.9+

---

## 🚀 Quick Start

### Simple Optimization

```python
import quantfolio as qf

# Optimize portfolio with quantum algorithm
optimizer = qf.HybridOptimizer(
    tickers=['AAPL', 'MSFT', 'GOOGL', 'AMZN'],
    method='quantum'
)

weights = optimizer.optimize(risk_aversion=0.5)

print("Optimal Portfolio:")
for ticker, weight in zip(optimizer.tickers, weights):
    print(f"  {ticker}: {weight*100:.1f}%")
```

### Advanced Usage

```python
import quantfolio as qf

# Hybrid optimization with ML prediction
optimizer = qf.HybridOptimizer(
    tickers=['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'JPM', 'JNJ'],
    classical_model='transformer',  # or 'lstm'
    use_quantum=True,
    risk_aversion=0.5,
    max_weight=0.30  # Max 30% per asset
)

# Train predictor and optimize
result = optimizer.optimize(
    train_predictor=True,
    epochs=50
)

# Visualize results
optimizer.plot_weights()
optimizer.plot_efficient_frontier()

# View metrics
print(f"Expected Return: {result['expected_return']*100:.2f}%")
print(f"Risk (Volatility): {result['risk']*100:.2f}%")
print(f"Sharpe Ratio: {result['sharpe_ratio']:.2f}")
```

### Compare Methods

```python
import quantfolio as qf

# Compare quantum vs classical vs hybrid
comparison = qf.compare_methods(
    tickers=['AAPL', 'MSFT', 'GOOGL'],
    methods=['quantum', 'classical', 'hybrid']
)

print(comparison)
```

---

## 📊 Available Optimizers

| Optimizer | Description | Use Case |
|-----------|-------------|----------|
| **QAOA** | Quantum Approximate Optimization | Complex constraints, exploration |
| **Markowitz** | Mean-Variance Optimization | Classical baseline, proven |
| **Equal Weight** | 1/N allocation | Simple diversification |
| **Min Variance** | Minimize risk only | Conservative portfolios |
| **Max Sharpe** | Maximize risk-adjusted return | Optimal risk/return |

---

## 🎓 Examples

Check out the [examples/](examples/) directory for:
- `basic_usage.py` - Quick start tutorial
- `custom_portfolio.py` - Advanced configurations
- `comparison_demo.py` - Method comparisons
- `backtesting.py` - Historical performance testing

---

## 📖 Documentation

### Main API

#### `HybridOptimizer`

```python
optimizer = qf.HybridOptimizer(
    tickers: List[str],              # Stock symbols
    method: str = 'hybrid',          # 'quantum', 'classical', or 'hybrid'
    classical_model: str = 'lstm',   # 'transformer' or 'lstm'
    use_quantum: bool = True,        # Use QAOA optimization
    risk_aversion: float = 0.5,      # 0=aggressive, 1=conservative
    max_weight: float = 0.30,        # Maximum weight per asset
    min_weight: float = 0.05         # Minimum weight per asset
)
```

#### Methods

- `optimize(**kwargs)` - Run optimization
- `plot_weights()` - Visualize portfolio weights
- `plot_efficient_frontier()` - Plot risk-return trade-off
- `plot_evolution()` - Show portfolio value over time

---

## 🧪 Technical Details

### Quantum Component

- **Algorithm**: QAOA (Quantum Approximate Optimization Algorithm)
- **Backend**: IBM Qiskit Aer Simulator (portable to real quantum hardware)
- **Qubits**: Configurable based on number of assets
- **Encoding**: Binary representation of portfolio weights

### Classical Component

- **Transformers**: Multi-head attention for time series
- **LSTM**: Bidirectional LSTM for sequence modeling
- **Features**: Price history, technical indicators
- **Framework**: PyTorch

### Optimization Problem

Maximizes: `Expected Return - λ * Risk`

Subject to:
- Σ weights = 1 (fully invested)
- 0 ≤ weight_i ≤ max_weight
- Minimum diversification constraints

---

## ⚠️ Disclaimer

**This software is for educational and research purposes only.**

- Not financial advice
- No guarantee of returns
- Past performance ≠ future results
- Consult a qualified financial advisor before investing

---

## 🤝 Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

### Development Setup

```bash
git clone https://github.com/quantfolio/quantfolio.git
cd quantfolio
pip install -e ".[dev]"
pytest tests/
```

---

## 📚 Citation

If you use Quantfolio in academic research, please cite:

```bibtex
@software{quantfolio2025,
  title = {Quantfolio: Hybrid Quantum-Classical Portfolio Optimization},
  author = {Quantfolio Contributors},
  year = {2025},
  url = {https://github.com/quantfolio/quantfolio}
}
```

---

## 📄 License

MIT License - see [LICENSE](LICENSE) file for details.

---

## 🌟 Acknowledgments

Built with:
- [IBM Qiskit](https://qiskit.org/) - Quantum computing framework
- [PyTorch](https://pytorch.org/) - Deep learning
- [yfinance](https://github.com/ranaroussi/yfinance) - Financial data

---

## 📬 Contact

- **Issues**: [GitHub Issues](https://github.com/quantfolio/quantfolio/issues)
- **Discussions**: [GitHub Discussions](https://github.com/quantfolio/quantfolio/discussions)

---

Made with ❤️ and ⚛️ by the Quantfolio team