Lesson 11 of 15
Backtest Engine (P&L Tracking)
Backtest Engine
A backtest engine simulates a trading strategy on historical data to estimate its profitability. We track portfolio value over time.
Rules
- Signals:
1= long (buy),-1= short (sell),0= flat (no position) - Positions are entered at the current bar's price when the signal changes.
- The portfolio value at the next bar is:
cash + position * prices[t+1]
Algorithm
Starting with initial_capital:
portfolio = [initial_capital]
position = 0
cash = initial_capital
for t in range(len(signals) - 1):
sig = signals[t]
if sig != position:
cash += position * prices[t] # close existing position
if sig != 0:
cash -= sig * prices[t] # open new position
position = sig
portfolio.append(cash + position * prices[t+1])
Task
Implement backtest(prices, signals, initial_capital=10000.0) that returns a list of portfolio values over time (same length as prices).
Python runtime loading...
Loading...
Click "Run" to execute your code.