Skip to main content

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.4.tar.gz (12.2 kB view details)

Uploaded Source

Built Distribution

pyBacktest-1.1.4-py3-none-any.whl (12.0 kB view details)

Uploaded Python 3

File details

Details for the file pybacktest-1.1.4.tar.gz.

File metadata

  • Download URL: pybacktest-1.1.4.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

Hashes for pybacktest-1.1.4.tar.gz
Algorithm Hash digest
SHA256 2042f7d9e0a07ce1cd9200e685fce0a84eef1cbde66f6461ff89424e079161a6
MD5 10ef8a60102ec5984888308822db7ef4
BLAKE2b-256 37cbf7ea1f2b2664ecf0f208b9dd17b75a4e3d81c8a27d4c44386ea898f9490c

See more details on using hashes here.

File details

Details for the file pyBacktest-1.1.4-py3-none-any.whl.

File metadata

  • Download URL: pyBacktest-1.1.4-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

Hashes for pyBacktest-1.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 9b7e01fa44801ab854760236b2881b6314d09fed32ef113926a90038c32d2e94
MD5 98b5e77ed32cf848a018fd69a4efac8d
BLAKE2b-256 ba089fb9321543e69e749c892b0f3c471a2c35326cf7291cdbee2bf9c40dcf15

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page