Backtest stock portfolio performance with historical price data.
- Track buys and sells from a simple CSV file
- Fetch historical prices from Yahoo Finance
- Calculate returns, CAGR, and gain/loss metrics
- Compare performance against a benchmark (default: SPY)
- Generate PDF reports with charts
pip install -r requirements.txt- Create a
transactions.csvfile with your transactions:
date,ticker,amount,type
2020-03-16,AAPL,5000,buy
2020-06-19,MSFT,3000,buy
2023-11-15,AAPL,2000,sell- Run the backtest:
python -m portfolio- Open
report.pdfto view your results.
--transactions FILE Input CSV file (default: transactions.csv)
--output FILE Output PDF file (default: report.pdf)
--end-date DATE End date for backtest in YYYY-MM-DD (default: today)
--benchmark TICKER Benchmark for comparison (default: SPY)
--no-benchmark Disable benchmark comparison
# Use the example file
python -m portfolio --transactions examples/example_transactions.csv
# Compare against VT instead of SPY
python -m portfolio --benchmark VT
# Skip benchmark comparison
python -m portfolio --no-benchmark| Column | Required | Description |
|---|---|---|
| date | Yes | Transaction date (YYYY-MM-DD, must be a trading day) |
| ticker | Yes | Stock symbol (e.g., AAPL, MSFT) |
| amount | Yes | Dollar amount |
| type | No | "buy" or "sell" (default: buy) |
- Summary - Contributions, withdrawals, final value, gain/loss, CAGR, benchmark comparison
- Transactions - List of all buy and sell transactions
- Final Holdings - Final positions with values and weights
- Portfolio Value Chart - Value over time
- Benchmark Comparison Chart - Portfolio vs benchmark returns over time
- Holdings Pie Chart - Final allocation breakdown
Run the test suite with pytest:
# Run all tests
pytest
# Run with coverage report
pytest --cov=portfolio --cov-report=term-missingMIT