Metadata-Version: 2.4
Name: stratpy-lib
Version: 0.2.0
Summary: A modular python library for building algorithmic trading strategies.
Author-email: Albert Akinola <albert.akinola@outlook.com>
License-Expression: MIT
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pandas
Requires-Dist: numpy
Requires-Dist: yfinance
Requires-Dist: matplotlib
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Dynamic: license-file

<p align="center"><img src="assets/stratpy_logo_main.png" alt="Stratpy Logo" width="300"></p>

# Stratpy (v0.2.0)

**Stratpy** is a lightweight, high-performance, and modular Python library designed for building, testing, evaluating, and simulating algorithmic trading strategies.

Built on pure vectorized operations (`pandas` and `numpy`), Stratpy abstracts away repetitive data science tasks and event loops so quantitative researchers and developers can focus entirely on mathematical modeling, risk management, and strategy logic.

---

## 🚀 What's New in v0.2.0 (The Risk, Visualizations & Simulation Update)

Stratpy v0.2.0 combines two major release milestones (v0.1.5 & v0.2.0) to deliver institutional-grade risk modeling, visualizations, and simulation capabilities:

- **Vectorized Trade Friction & Risk Controls (v0.2.0):**
  - **Commissions & Slippage:** Realistically deduct execution friction (`commission_pct`, `slippage_pct`) on actual trade transition days.
  - **Path-Dependent Risk Engine:** Enforce dynamic position exits via `stop_loss_pct` and `take_profit_pct`.
  - **Pythonic Callable Syntax:** Run strategies directly as callables: `df_signals = sp.MACrossover(20, 50)(df)` followed by `results = sp.runstrat(df_signals)`.
- **Visuals & Forecasting Engine (v0.1.5):**
  - **Monte Carlo Simulations (GBM Math):** Project future asset price trajectories using Geometric Brownian Motion with drift ($\mu$) and volatility ($\sigma$).
  - **3D Parameter Optimization:** Run 2D parameter grid searches across strategies and plot 3D Sharpe ratio surfaces to spot robust parameter plateaus and prevent overfitting.

---

## 1. Installation & Quickstart

Install Stratpy via PyPI within your virtual environment (`venv`):

```bash
pip install stratpy-lib
```

Execute a complete backtest with trade friction and risk management in four lines of code:

```python
import stratpy as sp

# 1. Fetch market data (e.g., 2 years of Apple)
df = sp.data("AAPL", period="2y", interval="1d")

# 2. Generate signals using the Pythonic callable MACrossover Strategy
df_signals = sp.MACrossover(short_window=20, long_window=50)(df)

# 3. Execute vectorized backtest with commissions, slippage, and stop-loss
results = sp.runstrat(
    df_signals, 
    commission_pct=0.001, 
    slippage_pct=0.0005, 
    stop_loss_pct=0.05
)
```

---

## 2. Core Architecture & Philosophy

1. **Vectorization (Speed):** Operates on series and arrays rather than slow tick-by-tick `for` loops, processing years of daily data in milliseconds.
2. **Bias-Free Execution:** Applies defensive `.shift(1)` logic to signal vectors so today's close only trades tomorrow's return—eliminating Look-Ahead Bias.
3. **Friction & Risk Awareness:** Evaluates strategies under realistic market conditions with transaction costs, slippage, stop-loss, and take-profit rules.

---

## 3. Feature Spotlight

### 3D Parameter Optimization (Grid Search Terrain)
Find robust parameter regions for your strategies and avoid sharp, overfit performance peaks:

```python
# 1. Run grid search over parameter ranges
results = sp.optimize_parameters(df, sp.MACrossover, 'short_window', [5, 10, 15, 20], 'long_window', [30, 40, 50, 60])
# 2. Render 3D Sharpe ratio terrain plot
sp.plot_3d_surface(results, 'short_window', 'long_window', title="Sharpe Ratio Optimization Terrain")
```

### Monte Carlo Simulations (Geometric Brownian Motion)
Forecast future price distribution paths using Ito's Lemma stochastic differential equations:

```python
# 1. Simulate 100 future price paths over 252 trading days using GBM
sims = sp.generate_monte_carlo(df, column='Close', n_simulations=100, n_days=252)
# 2. Plot percentile fan chart (5th, 50th, 95th percentiles)
sp.plot_monte_carlo(sims, last_price=df['Close'].iloc[-1], title="SPY 1-Year Monte Carlo Projection")
```

---

## 4. Custom Strategy OOP Abstraction

Build custom strategies by subclassing `sp.BaseStrategy` and overriding `generate_signals()`:

```python
import stratpy as sp
import numpy as np

class MeanReversion(sp.BaseStrategy):
    def __init__(self, rsi_period=14, buy_level=30, sell_level=70):
        self.rsi_period = rsi_period
        self.buy_level = buy_level
        self.sell_level = sell_level

    def generate_signals(self, df):
        df = df.copy()

        # 1. Calculate technical indicator
        df = sp.rsi(df, window=self.rsi_period)

        # 2. Generate signals: 1 (Buy), -1 (Sell), 0 (Hold)
        df['Signal'] = 0
        df.loc[df[f'RSI_{self.rsi_period}'] < self.buy_level, 'Signal'] = 1
        df.loc[df[f'RSI_{self.rsi_period}'] > self.sell_level, 'Signal'] = -1

        # 3. Hold position until opposite signal occurs
        df['Signal'] = df['Signal'].replace(0, method='ffill')

        return df

# Run custom strategy
my_data = sp.data("SPY", "2y")
df_signals = MeanReversion(rsi_period=14, buy_level=25, sell_level=75)(my_data)
results = sp.runstrat(df_signals, commission_pct=0.001, stop_loss_pct=0.05)
```

---

## 5. Mathematical Indicators & Utilities

- **Moving Averages:** `sp.sma()`, `sp.ema()`
- **Momentum & Trend:** `sp.macd()`, `sp.rsi()`
- **Volatility & Bands:** `sp.bb()` (Bollinger Bands), `sp.atr()` (Average True Range)
- **Volume Execution:** `sp.vwap()` (Volume Weighted Average Price)
- **Data Pipeline:** `sp.data()` (yfinance downloader), `sp.clean()` (CSV parser & forward-fill handler)

*All indicators include safeguards (e.g., `np.errstate` / `np.where`) against division-by-zero errors in zero-volatility or zero-volume periods.*

---

## 6. Comprehensive Guide & Documentation

For a deep dive into the math, backtesting engine design, and detailed API references, please see [`DOCUMENTATION.md`](DOCUMENTATION.md).
