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

Uploaded Source

Built Distribution

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

Uploaded Python 3

File details

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

File metadata

  • Download URL: pybacktest-1.1.0.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.0.tar.gz
Algorithm Hash digest
SHA256 37021d61aae435580dd846b77ff516e6af4a5620cc7a44bd82fab42d08c43176
MD5 c8dac240d35d0fda1ba01deb54f1219a
BLAKE2b-256 904bc9cf529874b88079a85183058036aeade69da1651ffd897a722c369fb05c

See more details on using hashes here.

File details

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

File metadata

  • Download URL: pyBacktest-1.1.0-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.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ecc872a771bc0e500719c66364c63bd4bd5cae4523ac5e3de0fa56226af5f01c
MD5 e78b8ea762e3a1acdca215e02ff18162
BLAKE2b-256 19464a8b9d1f5d04e35e70430a7193af7196da97555f9ccb53b0681e911ad59e

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