Skip to content

Backtest

Ben Bell edited this page Nov 15, 2024 · 1 revision

Backtest Class Documentation

The Backtest class is responsible for simulating the execution of a trading strategy over historical data. It manages the portfolio, executes trades, and tracks performance metrics.

Methods

__init__(self, ticker: str, cash: float | int, strategy: 'Strategy', commision: float | int = 0.0, commisionType: str = "FLAT", timePeriod: str = "1mo", interval: str = "1d", startDate: datetime = datetime(2024, 1, 1), endDate: datetime = datetime(2024, 2, 1)) -> None

Initializes the backtest with the specified parameters.

getValidDate(self, target_date: pd.Timestamp) -> pd.Timestamp

Returns the nearest valid date in the historical data for the given target date.

formatDate(self, date: datetime) -> pd.Timestamp

Formats the given date to a valid timestamp in the historical data.

calculateCommision(self, price: float, numShares: int) -> float

Calculates the commission for a trade based on the commission type and rate.

cancelOrder(self, order_index: int) -> bool

Cancels an order by its index in the pending orders list.

submitGTCOrder(self, tradeType: TradeType, numShares: int, targetPrice: float) -> Order

Submits a Good-Till-Canceled (GTC) order.

calculate_trade_cost(self, tradeType: TradeType, numShares: int, price: float = None) -> float

Calculates the total cost of a trade, including commission.

next(self)

Advances the backtest to the next time step, executing any pending orders and calling the strategy's step method.

run(self) -> BacktestResult

Runs the backtest from the start date to the end date and returns the results.

trade(self, tradeType: TradeType, numShares: int, price: float = None, duration: str = 'DAY') -> Optional[Holding]

Executes a trade of the specified type and returns the resulting holding.

totalValue(self) -> float

Calculates the total value of the portfolio, including cash and holdings.

getPosition(self) -> int

Returns the current position (number of shares) held in the portfolio.

calculatePositionSize(self, risk_per_trade: float, stop_loss: float) -> int

Calculates the position size based on the risk per trade and stop loss level.

applyStopLoss(self, stop_loss: float)

Applies a stop loss to the current holdings.

applyTakeProfit(self, take_profit: float)

Applies a take profit to the current holdings.

calculateVaR(self, confidence_level: float = 0.95) -> float

Calculates the Value at Risk (VaR) for the portfolio.

rebalancePortfolio(self, target_allocations: Dict[str, float])

Rebalances the portfolio according to the target allocations.

Clone this wiki locally