Backtesting¶
Strategy simulation often includes going through same steps : determining entry and exit moments, calculating number of shares capital and pnl. To limit the number of lines of code needed to perform a backtest, the twp library includes a simple backtesting module.
The backtest module is a very simple version of a vectorized backtester. It can be used as a stand-alone module without the rest of the tradingWithPython library.
All of the functionality is accessible through the Backtest class, which will be demonstrated here.
The backtester needs an instrument price and entry/exit signals to do its job. Let’s start by creating simple data series to test it.
In [1]: import tradingWithPython as twp
In [2]: import pandas as pd
In [3]: import numpy as np
Backtest class¶
-
class
tradingWithPython.lib.backtest.
Backtest
(price, signal, signalType='capital', initialCash=0, roundShares=True)[source]¶ Simple vectorized backtester. Works with pandas objects.
Attributes
trades (Series) trade data Methods
plotTrades
-
plotTrades
()[source]¶ visualise trades on the price chart long entry : green triangle up short entry : red triangle down exit : black circle
-
pnl
¶ easy access to pnl data column
-
sharpe
¶ return annualized sharpe ratio of the pnl
-
Functions¶
-
tradingWithPython.lib.backtest.
tradeBracket
(price, entryBar, upper=None, lower=None, timeout=None)[source]¶ trade a bracket on price series, return price delta and exit bar #
Parameters: price : np.array
array of price values
entryBar : int
entry bar number, determines entry price
upper : float
high stop
lower : float
low stop
timeout : int
max number of periods to hold
Returns: exit price and number of bars held