{"id":21028,"date":"2023-03-27T11:02:15","date_gmt":"2023-03-27T11:02:15","guid":{"rendered":"https:\/\/algotrading101.com\/learn\/?p=21028"},"modified":"2023-05-10T16:02:45","modified_gmt":"2023-05-10T16:02:45","slug":"backtesting-py-guide","status":"publish","type":"post","link":"https:\/\/algotrading101.com\/learn\/backtesting-py-guide\/","title":{"rendered":"Backtesting.py &#8211; An Introductory Guide to Backtesting with Python"},"content":{"rendered":"<div class=\"pvc_clear\"><\/div><p id=\"pvc_stats_21028\" class=\"pvc_stats total_only  \" data-element-id=\"21028\" style=\"\"><i class=\"pvc-stats-icon medium\" aria-hidden=\"true\"><svg aria-hidden=\"true\" focusable=\"false\" data-prefix=\"far\" data-icon=\"chart-bar\" role=\"img\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" viewBox=\"0 0 512 512\" class=\"svg-inline--fa fa-chart-bar fa-w-16 fa-2x\"><path fill=\"currentColor\" d=\"M396.8 352h22.4c6.4 0 12.8-6.4 12.8-12.8V108.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v230.4c0 6.4 6.4 12.8 12.8 12.8zm-192 0h22.4c6.4 0 12.8-6.4 12.8-12.8V140.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v198.4c0 6.4 6.4 12.8 12.8 12.8zm96 0h22.4c6.4 0 12.8-6.4 12.8-12.8V204.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v134.4c0 6.4 6.4 12.8 12.8 12.8zM496 400H48V80c0-8.84-7.16-16-16-16H16C7.16 64 0 71.16 0 80v336c0 17.67 14.33 32 32 32h464c8.84 0 16-7.16 16-16v-16c0-8.84-7.16-16-16-16zm-387.2-48h22.4c6.4 0 12.8-6.4 12.8-12.8v-70.4c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v70.4c0 6.4 6.4 12.8 12.8 12.8z\" class=\"\"><\/path><\/svg><\/i> <img decoding=\"async\" width=\"16\" height=\"16\" alt=\"Loading\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/plugins\/page-views-count\/ajax-loader-2x.gif\" border=0 \/><\/p><div class=\"pvc_clear\"><\/div>\n<figure class=\"wp-block-image size-large\"><img fetchpriority=\"high\" decoding=\"async\" width=\"1024\" height=\"203\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2023\/03\/backtesting-py-1024x203.png\" alt=\"\" class=\"wp-image-21035\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2023\/03\/backtesting-py-1024x203.png 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2023\/03\/backtesting-py-300x59.png 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2023\/03\/backtesting-py-768x152.png 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2023\/03\/backtesting-py-1536x304.png 1536w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2023\/03\/backtesting-py.png 1727w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Table of contents:<\/h3>\n\n\n\n<ol>\n<li><a href=\"#what-is-backtesting.py\">What is Backtesting.py?<\/a><\/li>\n\n\n\n<li><a href=\"#backtesting.py-use\">What is Backtesting.py used for?<\/a><\/li>\n\n\n\n<li><a href=\"#backtesting.py-pros\">Why should I use Backtesting.py?<\/a><\/li>\n\n\n\n<li><a href=\"#backtesting.py-cons\">Why shouldn\u2019t I use Backtesting.py?<\/a><\/li>\n\n\n\n<li><a href=\"#backtesting.py-free\">Is Backtesting.py free?<\/a><\/li>\n\n\n\n<li><a href=\"#backtesting.py-alternatives\">What are some Backtesting.py alternatives?<\/a><\/li>\n\n\n\n<li><a href=\"#backtesting.py-start\">How to get started with Backtesting.py?<\/a><\/li>\n\n\n\n<li><a href=\"#backtesting.py-get-data\">How to get data with Backtesting.py?<\/a><\/li>\n\n\n\n<li><a href=\"#backtesting.py-technical-indicators\">How to use technical indicators with Backtesting.py?<\/a><\/li>\n\n\n\n<li><a href=\"#backtesting.py-define-entries-and-exits\">How to define entries and exits with Backtesting.py?<\/a><\/li>\n\n\n\n<li><a href=\"#backtesting.py-strategy-types\">What strategy types does Backtesting.py offer?<\/a><\/li>\n\n\n\n<li><a href=\"#backtesting.py-mean-reversion\">How to code a mean-reversion strategy with Backtesting.py?<\/a><\/li>\n\n\n\n<li><a href=\"#backtesting.py-backtesting\">How to perform backtesting with Backtesting.py?<\/a><\/li>\n\n\n\n<li><a href=\"#backtesting.py-optimizations\">How to perform optimizations with Backtesting.py?<\/a><\/li>\n\n\n\n<li><a href=\"#backtesting.py-multiple-time-frames\">How to use multiple time frames with Backtesting.py?<\/a><\/li>\n\n\n\n<li><a href=\"#backtesting.py-learn-more\">Where can I learn more about Backtesting.py?<\/a><\/li>\n\n\n\n<li><a href=\"#backtesting.py-full-code\">Full code<\/a><\/li>\n<\/ol>\n\n\n\n<a name=\"what-is-backtesting.py\">\n\n\n\n<h2 class=\"wp-block-heading\">What is Backtesting.py?<\/h2>\n\n\n\n<p>Backtesting.py is an open-source backtesting Python library that allows users to test their trading strategies via code.<\/p>\n\n\n\n<p>Link: <a href=\"https:\/\/github.com\/kernc\/backtesting.py\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/github.com\/kernc\/backtesting.py<\/a><\/p>\n\n\n\n<a name=\"backtesting.py-use\">\n\n\n\n<h2 class=\"wp-block-heading\">What is Backtesting.py used for?<\/h2>\n\n\n\n<p>Algorithmic traders often use Backtesting.py to backtest, optimize, research, and improve different trading strategies. To learn more about backtesting and its benefits please read the following article:<\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-quantitative-trading-ideas-and-guides-algotrading-101-blog wp-block-embed-quantitative-trading-ideas-and-guides-algotrading-101-blog\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"2R1ObgBTUF\"><a href=\"https:\/\/algotrading101.com\/learn\/backtesting-guide\/\">What is Backtesting? 3 Aims of Backtesting<\/a><\/blockquote><iframe class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" title=\"&#8220;What is Backtesting? 3 Aims of Backtesting&#8221; &#8212; Quantitative Trading Ideas and Guides - AlgoTrading101 Blog\" src=\"https:\/\/algotrading101.com\/learn\/backtesting-guide\/embed\/#?secret=5BhMJKO2Qr#?secret=2R1ObgBTUF\" data-secret=\"2R1ObgBTUF\" width=\"500\" height=\"282\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n\n\n<a name=\"backtesting.py-pros\">\n\n\n\n<h2 class=\"wp-block-heading\">Why should I use Backtesting.py?<\/h2>\n\n\n\n<ul>\n<li>Backtesting.py is easy to use.<\/li>\n\n\n\n<li>Backtesting.py is open-sourced.<\/li>\n\n\n\n<li>Is compatible with forex, crypto, stocks, futures, and more.<\/li>\n\n\n\n<li>Offers interactive charts.<\/li>\n\n\n\n<li>Allows for vectorized or event-based backtesting.<\/li>\n\n\n\n<li>Has a built-in optimizer.<\/li>\n\n\n\n<li>Is actively maintained.<\/li>\n<\/ul>\n\n\n\n<a name=\"backtesting.py-cons\">\n\n\n\n<h2 class=\"wp-block-heading\">Why shouldn\u2019t I use Backtesting.py?<\/h2>\n\n\n\n<ul>\n<li>Backtesting.py could use more features.<\/li>\n\n\n\n<li>Doesn&#8217;t support the use of multiple assets at the same time.<\/li>\n\n\n\n<li>Data that the strategy needs is constrained (OHLCV).<\/li>\n\n\n\n<li>Is heavily indicator based.<\/li>\n\n\n\n<li>Complex strategies either can&#8217;t work or require hacking to work.<\/li>\n\n\n\n<li>The documentation could be better.<\/li>\n\n\n\n<li>The charting should be more customizable.<\/li>\n\n\n\n<li>Can be easily replaced by its alternatives.<\/li>\n<\/ul>\n\n\n\n<a name=\"backtesting.py-free\">\n\n\n\n<h2 class=\"wp-block-heading\">Is Backtesting.py free?<\/h2>\n\n\n\n<p>Yes, Backtesting.py is completely free and open-sourced.<\/p>\n\n\n\n<a name=\"backtesting.py-alternatives\">\n\n\n\n<h2 class=\"wp-block-heading\">What are some Backtesting.py alternatives?<\/h2>\n\n\n\n<p>Some Backtesting.py alternatives are the following:<\/p>\n\n\n\n<ul>\n<li>VectorBT<\/li>\n\n\n\n<li><a href=\"https:\/\/algotrading101.com\/learn\/backtrader-for-backtesting\/\">Backtrader<\/a><\/li>\n\n\n\n<li>Zipline<\/li>\n\n\n\n<li>Bt<\/li>\n\n\n\n<li><a href=\"https:\/\/algotrading101.com\/learn\/quantconnect-guide\/\">QuantConnect<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/algotrading101.com\/learn\/pine-script-tradingview-guide\/\">TradinView&#8217;s PineScript<\/a><\/li>\n<\/ul>\n\n\n\n<a name=\"backtesting.py-start\">\n\n\n\n<h2 class=\"wp-block-heading\">How to get started with Backtesting.py?<\/h2>\n\n\n\n<p>To get started with <a href=\"https:\/\/kernc.github.io\/backtesting.py\/\">Backtesting.py<\/a>, you will need to install it via pip with the following command:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-bash\" data-lang=\"Bash\"><code>pip3 install backtesting<\/code><\/pre><\/div>\n\n\n\n<p>To start creating a trading strategy, you will import the Strategy object which is used within your trading algorithm classes:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>from backtesting import Strategy\n\nclass Algorithm(Strategy):\n      ...<\/code><\/pre><\/div>\n\n\n\n<p>For this article, I&#8217;ll be using Google Colab. Feel free to use any IDE of your choice. All code will be found on our <a href=\"https:\/\/github.com\/AlgoTrading101\">GitHub<\/a> and also at the bottom of the article. In the following sections, we&#8217;ll test out the main features that backtesting.py has to offer.<\/p>\n\n\n\n<a name=\"backtesting.py-get-data\">\n\n\n\n<h2 class=\"wp-block-heading\">How to get data with Backtesting.py?<\/h2>\n\n\n\n<p>To import data from Backtesting.py, we will access the <code>test<\/code> module and obtain a specific asset by passing its symbol. It returns the data as a Pandas data frame.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>from backtesting.test import GOOG\n\nGOOG.head()<\/code><\/pre><\/div>\n\n\n\n<pre class=\"wp-block-code\"><code>\n                Open\tHigh\tLow\tClose\tVolume\n2004-08-19\t100.00\t104.06\t95.96\t100.34\t22351900\n2004-08-20\t101.01\t109.08\t100.50\t108.31\t11428600\n2004-08-23\t110.75\t113.48\t109.05\t109.40\t9137200\n2004-08-24\t111.24\t111.60\t103.57\t104.87\t7631300\n2004-08-25\t104.96\t108.00\t103.88\t106.00\t4598900<\/code><\/pre>\n\n\n\n<p>Keep in mind that Backtesting only has GOOG and EURUSD for test data. Thus, you should use alternative data providers such as <a href=\"https:\/\/algotrading101.com\/learn\/yahoo-finance-api-guide\/\">Yahoo Finance<\/a> or <a href=\"https:\/\/algotrading101.com\/learn\/quandl-guide\/\">Quandl<\/a>.<\/p>\n\n\n\n<a name=\"backtesting.py-technical-indicators\">\n\n\n\n<h2 class=\"wp-block-heading\">How to use technical indicators with Backtesting.py?<\/h2>\n\n\n\n<p>To use technical indicators with Backtesting.py, you will need to import them from the <code>test<\/code> module by passing their function name. For example, if you want to obtain the Simple Moving Average indicator, you would write:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>from backtesting.test import SMA\n\nclass SmaCross(Strategy):\n    n1 = 20 # period of the first SMA\n    n2 = 50 # period of the second SMA\n\n    def init(self):\n        close = self.data.Close # close price data\n        self.sma1 = self.I(SMA, close, self.n1)\n        self.sma2 = self.I(SMA, close, self.n2)<\/code><\/pre><\/div>\n\n\n\n<p>Have in mind that Backtesting.py only offers the SMA as an example, it isn&#8217;t an indicators library which means that you should build your own indicators or use a library such as <a href=\"https:\/\/mrjbq7.github.io\/ta-lib\/\">TA-Lib<\/a>&nbsp;or&nbsp;<a href=\"https:\/\/tulipindicators.org\/\">Tulip<\/a>. Backtesting.py integrated well with both proposed libraries.<\/p>\n\n\n\n<p>Each technical indicator can be combined with an event such as the cross and crossover.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>from backtesting.lib import crossover\n\ndef next(self):\n      if crossover(self.sma1, self.sma2):\n          self.buy()\n      elif crossover(self.sma2, self.sma1):\n          self.sell()<\/code><\/pre><\/div>\n\n\n\n<a name=\"backtesting.py-define-entries-and-exits\">\n\n\n\n<h2 class=\"wp-block-heading\">How to define entries and exits with Backtesting.py?<\/h2>\n\n\n\n<p>Entries and exits can be defined with Backtesting.py by using conditions that can trigger a buy or sell order. An example of buy and sell order parameters are the following:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>def buy(self, *, size=.9999, limit=None, stop=None, sl=None, tp=None)\n\ndef sell(self, *, size=.9999, limit=None, stop=None, sl=None, tp=None)<\/code><\/pre><\/div>\n\n\n\n<p>When an entry or exit is executed, it results in a trade. We can query existing orders through&nbsp;<code><a href=\"https:\/\/kernc.github.io\/backtesting.py\/doc\/backtesting\/backtesting.html#backtesting.backtesting.Strategy.orders\">Strategy.orders<\/a><\/code>.<\/p>\n\n\n\n<a name=\"backtesting.py-strategy-types\">\n\n\n\n<h2 class=\"wp-block-heading\">What strategy types does Backtesting.py offer?<\/h2>\n\n\n\n<p>Backtesting.py has three main types of strategies which are the following:<\/p>\n\n\n\n<ul>\n<li><strong>Strategy <\/strong>&#8211; A trading strategy base class. Extend this class and override methods&nbsp;<code><a href=\"https:\/\/kernc.github.io\/backtesting.py\/doc\/backtesting\/backtesting.html#backtesting.backtesting.Strategy.init\">Strategy.init()<\/a><\/code>&nbsp;and&nbsp;<code><a href=\"https:\/\/kernc.github.io\/backtesting.py\/doc\/backtesting\/backtesting.html#backtesting.backtesting.Strategy.next\">Strategy.next()<\/a><\/code>&nbsp;to define your own strategy.<\/li>\n\n\n\n<li><strong>Trailing Strategy <\/strong>&#8211; A strategy with automatic trailing stop-loss, trailing the current price at a distance of some multiple of the average true range (ATR).<\/li>\n\n\n\n<li><strong>Signal Strategy<\/strong> &#8211; A simple helper strategy that operates on position entry\/exit signals. This makes the backtest of the strategy simulate a&nbsp;vectorized backtest.<\/li>\n<\/ul>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>class ExampleStrategy(SignalStrategy):\n    def init(self):\n        super().init()\n        self.set_signal(sma1 &gt; sma2, sma1 &lt; sma2)<\/code><\/pre><\/div>\n\n\n\n<p>Knowing when to use which strategy type will help you. Keep in mind that the <code>Strategy<\/code> module is an ancestor of the Trailing and Signal strategies. Now, let&#8217;s code a pairs trade strategy as an example and backtest it.<\/p>\n\n\n\n<a name=\"backtesting.py-mean-reversion\">\n\n\n\n<h2 class=\"wp-block-heading\">How to code a mean-reversion strategy with Backtesting.py?<\/h2>\n\n\n\n<p>To code a mean-reversion strategy with Backtesting.py, we will first need to obtain the data of the asset we plan to trade. Then, we will lay out our strategy logic to make all the steps clear. After that, we will code it out and run the backtest.<\/p>\n\n\n\n<p>The goal of this strategy will be to sell\/short the asset if it is trading more than 3 standard deviations above the rolling mean and to buy\/long the asset if it is trading more than 3 standard deviations below the rolling mean.<\/p>\n\n\n\n<p>We will use 15-minute candles and a rolling mean of 50. The take profit will be the value of our simple moving average.<\/p>\n\n\n\n<p>Now, let us obtain the data for the HE asset. We will do a date closer to the time of writing due to the yfinance constraints on the 15-minute data.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code># Obtain OHLV data for HE\n# Obtain OHLV data for HE\nhe = yf.download(&quot;HE&quot;, start=&quot;2023-01-15&quot;, interval=&quot;15m&quot;)[\n    [&quot;Open&quot;, &quot;High&quot;, &quot;Low&quot;, &quot;Close&quot;, &quot;Volume&quot;]\n]\nhe.head()<\/code><\/pre><\/div>\n\n\n\n<p>Now, let&#8217;s set up the trading strategy and the initialization logic.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>from backtesting.test import SMA\n\ndef std_3(arr, n):\n    return pd.Series(arr).rolling(n).std() * 3\n\nclass MeanReversion(Strategy):\n    roll = 50\n\n    def init(self):\n        self.he = self.data.Close\n\n        self.he_mean = self.I(SMA, self.he, self.roll)\n        self.he_std = self.I(std_3, self.he, self.roll)\n        self.he_upper = self.he_mean + self.he_std\n        self.he_lower = self.he_mean - self.he_std\n\n        self.he_close = self.I(SMA, self.he, 1)<\/code><\/pre><\/div>\n\n\n\n<p>Above, I imported the built-in SMA indicator and coded the 3 STD indicator by hand. You can also use libraries for more complicated indicators. Then, we specified the rolling window and initialized the algorithm.<\/p>\n\n\n\n<p>You can also see the first &#8220;hack&#8221; that needed to be introduced to adequately compare the indicator to the candle closing price. Essentially, it needed to be transformed into an indicator. There might be a better way of doing this but accessing the prices from <code>self.he<\/code> was broken at the time of writing.<\/p>\n\n\n\n<p>Now, we will code the trading logic. <\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>def next(self):\n\n        if self.he_close &lt; self.he_lower:\n            self.buy(\n                tp = self.he_mean,\n            )\n\n        if self.he_close &gt; self.he_upper:\n            self.sell(\n                tp = self.he_mean,\n            )<\/code><\/pre><\/div>\n\n\n\n<p>Now, we will wrap everything up and plot the strategy and print out its stats.<\/p>\n\n\n\n<a name=\"backtesting.py-backtesting\">\n\n\n\n<h2 class=\"wp-block-heading\">How to perform backtesting with Backtesting.py?<\/h2>\n\n\n\n<p>To perform backtesting with Backtesting.py, you will need to import the <code>Backtest<\/code> module and pass it the data, the strategy class, set initial cash, and the trade commission value. Below is an example of how to run a backtest and view its results.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>from backtesting import Backtest\n\nbt = Backtest(he, MeanReversion, cash=10000, commission=0.002)\nstats = bt.run()\nbt.plot()\nstats<\/code><\/pre><\/div>\n\n\n\n<pre class=\"wp-block-code\"><code>Start                     2023-01-17 09:30...\nEnd                       2023-03-08 16:00...\nDuration                     50 days 06:30:00\nExposure Time &#91;%]                   43.436499\nEquity Final &#91;$]                 10104.838029\nEquity Peak &#91;$]                  10291.717912\nReturn &#91;%]                            1.04838\nBuy &amp; Hold Return &#91;%]               -7.059514\nReturn (Ann.) &#91;%]                    7.573549\nVolatility (Ann.) &#91;%]               18.320732\nSharpe Ratio                         0.413387\nSortino Ratio                        0.748415\nCalmar Ratio                         1.805436\nMax. Drawdown &#91;%]                   -4.194859\nAvg. Drawdown &#91;%]                   -0.888331\nMax. Drawdown Duration        8 days 02:45:00\nAvg. Drawdown Duration        1 days 05:46:00\n# Trades                                    3\nWin Rate &#91;%]                        66.666667\nBest Trade &#91;%]                       1.008354\nWorst Trade &#91;%]                     -0.502406\nAvg. Trade &#91;%]                        0.34971\nMax. Trade Duration          13 days 02:45:00\nAvg. Trade Duration           6 days 19:20:00\nProfit Factor                        3.100131\nExpectancy &#91;%]                       0.351706\nSQN                                  0.776997<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" width=\"1024\" height=\"446\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2023\/03\/backtesting_results-1024x446.webp\" alt=\"\" class=\"wp-image-20763\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2023\/03\/backtesting_results-1024x446.webp 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2023\/03\/backtesting_results-300x131.webp 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2023\/03\/backtesting_results-768x335.webp 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2023\/03\/backtesting_results-1536x669.webp 1536w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2023\/03\/backtesting_results.webp 1829w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>Have in mind that this is just an example strategy for showcasing the library. It shouldn&#8217;t be used for real trading.<\/p>\n\n\n\n<a name=\"backtesting.py-optimizations\">\n\n\n\n<h2 class=\"wp-block-heading\">How to perform optimizations with Backtesting.py?<\/h2>\n\n\n\n<p>To perform optimizations with Backtesting.py, we can utilize the <code>optimize<\/code> function that can receive parameters to optimize and the metric to optimize for. For example, let&#8217;s optimize the rolling window size for our previous strategy.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>stats = bt.optimize(\n    roll=range(10, 60, 5),\n    maximize=&quot;Equity Final [$]&quot;,\n    constraint=lambda p: p.roll &gt; 10,\n)\nstats<\/code><\/pre><\/div>\n\n\n\n<pre class=\"wp-block-code\"><code>Start                     2023-01-17 09:30...\nEnd                       2023-03-08 16:00...\nDuration                     50 days 06:30:00\nExposure Time &#91;%]                    4.802561\nEquity Final &#91;$]                 10149.401675\nEquity Peak &#91;$]                  10149.401675\nReturn &#91;%]                           1.494017\nBuy &amp; Hold Return &#91;%]               -7.059514\nReturn (Ann.) &#91;%]                   10.938703\nVolatility (Ann.) &#91;%]                3.333441\nSharpe Ratio                         3.281505\nSortino Ratio                             inf\nCalmar Ratio                         8.567644\nMax. Drawdown &#91;%]                   -1.276746\nAvg. Drawdown &#91;%]                   -0.428759\nMax. Drawdown Duration        0 days 04:30:00\nAvg. Drawdown Duration        0 days 01:45:00\n# Trades                                    2\nWin Rate &#91;%]                            100.0\nBest Trade &#91;%]                       1.041394\nWorst Trade &#91;%]                       0.45102\nAvg. Trade &#91;%]                       0.745774\nMax. Trade Duration           0 days 05:30:00\nAvg. Trade Duration           0 days 05:23:00\nProfit Factor                             NaN\nExpectancy &#91;%]                       0.746207\nSQN                                   2.52049<\/code><\/pre>\n\n\n\n<p>To access the final value the strategy landed on, we can access the <code>stats['_strategy']<\/code>:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>&lt;Strategy MeanReversion(roll=15)&gt;<\/code><\/pre><\/div>\n\n\n\n<p>Be careful to not overfit the strategy and play with different buy\/sell order settings.<\/p>\n\n\n\n<p>To learn more about overfitting, check out: <a href=\"https:\/\/algotrading101.com\/learn\/what-is-overfitting-in-trading\/\">https:\/\/algotrading101.com\/learn\/what-is-overfitting-in-trading\/<\/a><\/p>\n\n\n\n<a name=\"backtesting.py-multiple-time-frames\">\n\n\n\n<h2 class=\"wp-block-heading\">How to use multiple time frames with Backtesting.py?<\/h2>\n\n\n\n<p>To use multiple time series with Backtesting.py, you can use the <code>resample_apply()<\/code> function which will allow you to resample the data to accommodate another time frame. <\/p>\n\n\n\n<p>Here is an <a href=\"https:\/\/hub.gke2.mybinder.org\/user\/kernc-backtesting.py-hlf9y5vw\/lab\/tree\/doc\/examples\/Multiple%20Time%20Frames.ipynb\">example<\/a> of how to use them that is provided by Backtesting.py.<\/p>\n\n\n\n<a name=\"backtesting.py-learn-more\">\n\n\n\n<h2 class=\"wp-block-heading\">Where can I learn more about Backtesting.py?<\/h2>\n\n\n\n<p>To learn more about Backtesting.py, I suggest checking out their <a href=\"https:\/\/kernc.github.io\/backtesting.py\/doc\/backtesting\/#gsc.tab=0\">documentation<\/a> and exploring the example notebooks on <a href=\"https:\/\/mybinder.org\/v2\/gh\/kernc\/backtesting.py\/master?urlpath=lab%2Ftree%2Fdoc%2Fexamples%2FQuick%20Start%20User%20Guide.ipynb\">Binder<\/a>. <\/p>\n\n\n\n<a name=\"backtesting.py-full-code\">\n\n\n\n<h2 class=\"wp-block-heading\">Full code<\/h2>\n\n\n\n<p><a href=\"https:\/\/github.com\/AlgoTrading101\/Backtesting.py-AlgoTrading101\">GitHub link<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<div class=\"pvc_clear\"><\/div>\n<p id=\"pvc_stats_21028\" class=\"pvc_stats total_only  \" data-element-id=\"21028\" style=\"\"><i class=\"pvc-stats-icon medium\" aria-hidden=\"true\"><svg aria-hidden=\"true\" focusable=\"false\" data-prefix=\"far\" data-icon=\"chart-bar\" role=\"img\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" viewBox=\"0 0 512 512\" class=\"svg-inline--fa fa-chart-bar fa-w-16 fa-2x\"><path fill=\"currentColor\" d=\"M396.8 352h22.4c6.4 0 12.8-6.4 12.8-12.8V108.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v230.4c0 6.4 6.4 12.8 12.8 12.8zm-192 0h22.4c6.4 0 12.8-6.4 12.8-12.8V140.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v198.4c0 6.4 6.4 12.8 12.8 12.8zm96 0h22.4c6.4 0 12.8-6.4 12.8-12.8V204.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v134.4c0 6.4 6.4 12.8 12.8 12.8zM496 400H48V80c0-8.84-7.16-16-16-16H16C7.16 64 0 71.16 0 80v336c0 17.67 14.33 32 32 32h464c8.84 0 16-7.16 16-16v-16c0-8.84-7.16-16-16-16zm-387.2-48h22.4c6.4 0 12.8-6.4 12.8-12.8v-70.4c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v70.4c0 6.4 6.4 12.8 12.8 12.8z\" class=\"\"><\/path><\/svg><\/i> <img decoding=\"async\" width=\"16\" height=\"16\" alt=\"Loading\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/plugins\/page-views-count\/ajax-loader-2x.gif\" border=0 \/><\/p>\n<div class=\"pvc_clear\"><\/div>\n<p>Table of contents: What is Backtesting.py? Backtesting.py is an open-source backtesting Python library that allows users to test their trading strategies via code. Link: https:\/\/github.com\/kernc\/backtesting.py What is Backtesting.py used for? Algorithmic traders often use Backtesting.py to backtest, optimize, research, and improve different trading strategies. To learn more about backtesting and its benefits please read the [&hellip;]<\/p>\n","protected":false},"author":14,"featured_media":21033,"comment_status":"closed","ping_status":"closed","sticky":true,"template":"","format":"standard","meta":{"_lmt_disableupdate":"no","_lmt_disable":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0},"categories":[3,2],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v20.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Backtesting.py - An Introductory Guide to Backtesting with Python - AlgoTrading101 Blog<\/title>\n<meta name=\"description\" content=\"Backtesting.py is an open-source backtesting Python library that allows users to test their trading strategies via code\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/algotrading101.com\/learn\/backtesting-py-guide\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Backtesting.py - An Introductory Guide to Backtesting with Python - AlgoTrading101 Blog\" \/>\n<meta property=\"og:description\" content=\"Backtesting.py is an open-source backtesting Python library that allows users to test their trading strategies via code\" \/>\n<meta property=\"og:url\" content=\"https:\/\/algotrading101.com\/learn\/backtesting-py-guide\/\" \/>\n<meta property=\"og:site_name\" content=\"Quantitative Trading Ideas and Guides - AlgoTrading101 Blog\" \/>\n<meta property=\"article:published_time\" content=\"2023-03-27T11:02:15+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-05-10T16:02:45+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2023\/03\/backtesting-py-2.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1727\" \/>\n\t<meta property=\"og:image:height\" content=\"1427\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Igor Radovanovic\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Igor Radovanovic\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Backtesting.py - An Introductory Guide to Backtesting with Python - AlgoTrading101 Blog","description":"Backtesting.py is an open-source backtesting Python library that allows users to test their trading strategies via code","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/algotrading101.com\/learn\/backtesting-py-guide\/","og_locale":"en_US","og_type":"article","og_title":"Backtesting.py - An Introductory Guide to Backtesting with Python - AlgoTrading101 Blog","og_description":"Backtesting.py is an open-source backtesting Python library that allows users to test their trading strategies via code","og_url":"https:\/\/algotrading101.com\/learn\/backtesting-py-guide\/","og_site_name":"Quantitative Trading Ideas and Guides - AlgoTrading101 Blog","article_published_time":"2023-03-27T11:02:15+00:00","article_modified_time":"2023-05-10T16:02:45+00:00","og_image":[{"width":1727,"height":1427,"url":"http:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2023\/03\/backtesting-py-2.png","type":"image\/png"}],"author":"Igor Radovanovic","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Igor Radovanovic","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/algotrading101.com\/learn\/backtesting-py-guide\/#article","isPartOf":{"@id":"https:\/\/algotrading101.com\/learn\/backtesting-py-guide\/"},"author":{"name":"Igor Radovanovic","@id":"https:\/\/algotrading101.com\/learn\/#\/schema\/person\/a7ae60c112a73b7c3fe14ac56726a0ae"},"headline":"Backtesting.py &#8211; An Introductory Guide to Backtesting with Python","datePublished":"2023-03-27T11:02:15+00:00","dateModified":"2023-05-10T16:02:45+00:00","mainEntityOfPage":{"@id":"https:\/\/algotrading101.com\/learn\/backtesting-py-guide\/"},"wordCount":1285,"publisher":{"@id":"https:\/\/algotrading101.com\/learn\/#organization"},"articleSection":["Programming","Trading"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/algotrading101.com\/learn\/backtesting-py-guide\/","url":"https:\/\/algotrading101.com\/learn\/backtesting-py-guide\/","name":"Backtesting.py - An Introductory Guide to Backtesting with Python - AlgoTrading101 Blog","isPartOf":{"@id":"https:\/\/algotrading101.com\/learn\/#website"},"datePublished":"2023-03-27T11:02:15+00:00","dateModified":"2023-05-10T16:02:45+00:00","description":"Backtesting.py is an open-source backtesting Python library that allows users to test their trading strategies via code","breadcrumb":{"@id":"https:\/\/algotrading101.com\/learn\/backtesting-py-guide\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/algotrading101.com\/learn\/backtesting-py-guide\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/algotrading101.com\/learn\/backtesting-py-guide\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/algotrading101.com\/learn\/"},{"@type":"ListItem","position":2,"name":"Backtesting.py &#8211; An Introductory Guide to Backtesting with Python"}]},{"@type":"WebSite","@id":"https:\/\/algotrading101.com\/learn\/#website","url":"https:\/\/algotrading101.com\/learn\/","name":"Quantitative Trading Ideas and Guides - AlgoTrading101 Blog","description":"Authentic Stories about Algorithmic trading, coding and life.","publisher":{"@id":"https:\/\/algotrading101.com\/learn\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/algotrading101.com\/learn\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/algotrading101.com\/learn\/#organization","name":"AlgoTrading101","url":"https:\/\/algotrading101.com\/learn\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/algotrading101.com\/learn\/#\/schema\/logo\/image\/","url":"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/11\/AlgoTrading101-Lucas-Liew.jpg","contentUrl":"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/11\/AlgoTrading101-Lucas-Liew.jpg","width":1200,"height":627,"caption":"AlgoTrading101"},"image":{"@id":"https:\/\/algotrading101.com\/learn\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/algotrading101.com\/learn\/#\/schema\/person\/a7ae60c112a73b7c3fe14ac56726a0ae","name":"Igor Radovanovic","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/algotrading101.com\/learn\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/d46175c509b3ee240a1e2bbe735a4d1e?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/d46175c509b3ee240a1e2bbe735a4d1e?s=96&d=mm&r=g","caption":"Igor Radovanovic"},"sameAs":["https:\/\/igorradovanovic.com","https:\/\/www.linkedin.com\/in\/igor-radovanovic-profile"],"url":"https:\/\/algotrading101.com\/learn\/author\/igor\/"}]}},"modified_by":"Lucas Liew","_links":{"self":[{"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/posts\/21028"}],"collection":[{"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/comments?post=21028"}],"version-history":[{"count":5,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/posts\/21028\/revisions"}],"predecessor-version":[{"id":21738,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/posts\/21028\/revisions\/21738"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/media\/21033"}],"wp:attachment":[{"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/media?parent=21028"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/categories?post=21028"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/tags?post=21028"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}