A backtesting framework for stock price prediction strategies
Project description
Stock Trading Backtest Framework
A Python framework for backtesting trading strategies with support for multiple order types and technical indicators.
Features
Trading Operations
- Market Orders (Buy/Sell)
- Limit Orders
- GTC (Good Till Cancelled) Orders
- Short
- Commission Handling
- Flat Fee
- Percentage
- Per Share
Technical Indicators
- Simple Moving Average (SMA)
- Exponential Moving Average (EMA)
- Relative Strength Index (RSI)
- Bollinger Bands
- MACD (Moving Average Convergence Divergence)
- Crossover Detection
- Volume Weighted Average Price (VWAP)
- Average True Range (ATR)
Portfolio Management
- Position Tracking
- Transaction History
- Portfolio Valuation
- Cash Management
- Performance Metrics
Example
import pyBacktest as pbt
from pyBacktest.strategy import Strategy
from pyBacktest.utils import calculateSMA, detectCrossover
from pyBacktest.tradeTypes import TradeType, InsufficientFundsError, InsufficientSharesError, ShortPositionError
from datetime import datetime
import pandas as pd
class SimpleMovingAverageCrossover(Strategy):
def setup(self) -> None:
self.sma20: pd.Series = calculateSMA(self.data['Close'], 20)
self.sma50: pd.Series = calculateSMA(self.data['Close'], 50)
def maxBuyableShares(self, price: float, cash: float) -> int:
numShares = 0
while True:
commission = self.backtest.calculateCommision(price, numShares + 1)
total_cost_per_share = price + (commission / (numShares + 1))
if cash >= total_cost_per_share * (numShares + 1):
numShares += 1
else:
break
return numShares
def next(self, row: pd.Series) -> None:
if len(self.data['Close']) < 51:
return
current_price: float = row['Close']
current_sma20: float = self.sma20[row.name]
current_sma50: float = self.sma50[row.name]
position: int = self.get_position()
try:
if current_sma20 > current_sma50:
numShares = self.maxBuyableShares(current_price, self.backtest.cash)
if numShares > 0:
self.backtest.trade(TradeType.MARKET_BUY, numShares)
elif current_sma20 < current_sma50 and position > 0:
sharesToSell = max(1, position // 3)
self.backtest.trade(TradeType.MARKET_SELL, sharesToSell)
except InsufficientFundsError as e:
print("Insufficient funds to execute trade")
if __name__ == "__main__":
backtest = pbt.Backtest(
"NVDA",
10000.0,
strategy=SimpleMovingAverageCrossover(),
commision=0.0,
commisionType="FLAT",
startDate=datetime(2020, 1, 1),
endDate=datetime(2024, 1, 1)
)
results = backtest.run()
print(f"Final Portfolio Value: ${results['final_value']:,.2f}")
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
pybacktest-1.1.3.tar.gz
(12.2 kB
view details)
Built Distribution
File details
Details for the file pybacktest-1.1.3.tar.gz
.
File metadata
- Download URL: pybacktest-1.1.3.tar.gz
- Upload date:
- Size: 12.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.9.20
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 210e3262032de8b4a28b6fa7e1c919af7333c2613bc00ab6791d481f35dcc85d |
|
MD5 | 61f4bceb739d3a185da9c079fc3ed44c |
|
BLAKE2b-256 | b547c64ed99cb23c0fbde17bf8227426a444f492531798e18aba07cc249568d5 |
File details
Details for the file pyBacktest-1.1.3-py3-none-any.whl
.
File metadata
- Download URL: pyBacktest-1.1.3-py3-none-any.whl
- Upload date:
- Size: 12.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.9.20
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | c4ce164f5cb90a42aea6ef10d5194c84a58cfe143bd5ce7b7a7b5ee445c4418c |
|
MD5 | cc2a6d5c0f6c502472c7fd895f49718d |
|
BLAKE2b-256 | c418d33b7b3b2bcfe63078349ec6632c218885fb816313d0b2775cba624d9509 |