{"id":60,"date":"2019-10-16T23:39:39","date_gmt":"2019-10-16T21:39:39","guid":{"rendered":"https:\/\/market-and-us.com\/blog\/?p=60"},"modified":"2019-11-02T16:06:06","modified_gmt":"2019-11-02T15:06:06","slug":"how-to-code-a-backtest","status":"publish","type":"post","link":"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/","title":{"rendered":"How to code a backtest?"},"content":{"rendered":"\n<p>Because I love <strong>programming<\/strong> since my first experiences at the age of six I wanted to explain you how you can <strong>code your own backtests<\/strong>.<\/p>\n\n\n\n<p><strong>Did you find a signal you would like to know how it worked in the past 20 years?<\/strong><br>We do that know together!<\/p>\n\n\n\n<h2>First the <strong>candlesticks<\/strong> &#8230;<\/h2>\n\n\n\n<p>At first we need the <strong>candlestick data<\/strong> with date, open, high, low, close and volume of each day.<br>You can get the data from your broker, for example through the API of Interactive Brokers or the csv-file export of TC2000, or you use one of the free or cheap APIs (IEX, Quandl, &#8230;).<br>For our example you can <a href=\"https:\/\/market-and-us.com\/blog\/code\/SPY.csv\">download the needed data here<\/a>.<\/p>\n\n\n\n<h2>&#8230; and the import in your program<\/h2>\n\n\n\n<p>Now you\u2019re thinking: Hey, I didn\u2019t code anything yet! No problem, it\u2019s not that difficult.<br>I know many coding languages like JavaScript or PHP but after programming my tools for stocks and trading around 5 years I can recommend to you:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote\"><p><strong>The best language for programming with financial data is <a href=\"https:\/\/www.python.org\/\">Python<\/a>!<\/strong><\/p><\/blockquote>\n\n\n\n<p>Let\u2019s start our example with the <strong>SPY<\/strong>, daily candles and a simple <strong>moving average crossing<\/strong> strategy.<\/p>\n\n\n\n<p>To <span style=\"text-decoration: underline;\">read the data<\/span> of our source file (<code>SPY.csv<\/code>, located in the same folder), we just need write this line into a text file named \u201c<code>backtest.py<\/code>\u201d:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>data = pd.read_csv(\"SPY.csv\")<\/code><\/pre>\n\n\n\n<p>The \u201cpd\u201d stands for pandas, a library for data calculations and comparison which we have to integrate in our code <span style=\"text-decoration: underline;\">before<\/span> the line above:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import pandas as pd<\/code><\/pre>\n\n\n\n<p>To <span style=\"text-decoration: underline;\">check the data<\/span> by printing the last 5 rows\/days on the screen we can add<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>print(data.tail())<\/code><\/pre>\n\n\n\n<h2>The strategy<\/h2>\n\n\n\n<p>The <span style=\"text-decoration: underline;\">simple moving average<\/span> over 200 days (200 SMA) for all rows can be calculated by<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>data['SMA200'] = data.Close.rolling(200).mean()<\/code><\/pre>\n\n\n\n<p>and to check if the <span style=\"text-decoration: underline;\">close is above the SMA 200<\/span> just type<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>data['above']  = data.Close > data.SMA200<\/code><\/pre>\n\n\n\n<p>Now we have 2 new columns with &#8216;<code>SMA200<\/code>&#8216; and &#8216;<code>above<\/code>&#8216; in our dataset. We will add three more for the &#8220;not above&#8221; and for <span style=\"text-decoration: underline;\">the buy and sell signal<\/span> when crossing (<code>-<\/code> stands for <code>not<\/code> and here we have to use <code>&amp;<\/code> instead of <code>and<\/code>):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>data['notabove'] = -data.above\ndata['buy']  = data.above &amp; data.notabove.shift(1)\ndata['sell'] = data.notabove &amp; data.above.shift(1)<\/code><\/pre>\n\n\n\n<h2>Checking each day with one loop<\/h2>\n\n\n\n<p>The &#8216;<code>shift<\/code>&#8216; moves a column one row up (<code>shift(-1)<\/code>) or down (<code>shift(1)<\/code>), so here we can compare with the day before.<br>But how to code the backtest for every row of data? While iterating through the rows, <span style=\"text-decoration: underline;\">we invest at the buy signal and close the position at the sell signal<\/span> while setting the variable <code>invest<\/code> true or false:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>total_return = 0.0\ninvested = False\nfor index, row in data.iterrows():\n    if row.buy and not invested:\n        entry = row.Close\n        invested = True\n    if row.sell and invested:\n        exit = row.Close\n        trade_return = exit\/entry - 1\n        total_return += trade_return\n        invested = False<\/code><\/pre>\n\n\n\n<h2>Show our result<\/h2>\n\n\n\n<p>And finally we just have to <span style=\"text-decoration: underline;\">output the total return<\/span>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>print(\"Total return from\", data.index[0], \"to\", data.index[-1], \"is\", round(total_return*100, 2), \"%.\")<\/code><\/pre>\n\n\n\n<p>Now you <span style=\"text-decoration: underline;\">start our program<\/span> with this command &#8211; and hopefully the same output if you used the source file of the above link:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>>> python3 backtest.py\nTotal return from 1993-01-29 to 2019-10-08 is 172.33 %.<\/code><\/pre>\n\n\n\n<p>Therefore you had profits of 172.33% if you <span style=\"text-decoration: underline;\">invested the same amount<\/span> with our buy signal since 1993. It&#8217;s not difficult to change it to the cumulative return or to compare with a buy &amp; hold strategy.<\/p>\n\n\n\n<p>If there are any questions, experiences or wishes about how to code a backtest I would like to read <span style=\"text-decoration: underline;\">your comment<\/span> below. I wish you good results with your code, fun with many combinations and a strategy that fits best to you!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Because I love programming since my first experiences at the age of six I wanted to explain you how you can code your own backtests. Did you find a signal you would like to know how it worked in the past 20 years?We do that know together! First the candlesticks &#8230; At first we need [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":63,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"yasr_overall_rating":0,"yasr_post_is_review":"","yasr_auto_insert_disabled":"","yasr_review_type":""},"categories":[7],"tags":[18,26,20,25,22,19,21,23,9,24],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v16.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to code a backtest? - The Market and Us<\/title>\n<meta name=\"description\" content=\"To know wether a trading strategy will lead to good profits or not a first step is to do a backtest. Here you can read about how to code a backtest.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to code a backtest? - The Market and Us\" \/>\n<meta property=\"og:description\" content=\"To know wether a trading strategy will lead to good profits or not a first step is to do a backtest. Here you can read about how to code a backtest.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/\" \/>\n<meta property=\"og:site_name\" content=\"The Market and Us\" \/>\n<meta property=\"article:published_time\" content=\"2019-10-16T21:39:39+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2019-11-02T15:06:06+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/market-and-us.com\/blog\/wp-content\/uploads\/2019\/10\/spy-candlestick-data-1024x768.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1024\" \/>\n\t<meta property=\"og:image:height\" content=\"768\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\">\n\t<meta name=\"twitter:data1\" content=\"3 minutes\">\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/market-and-us.com\/blog\/#website\",\"url\":\"https:\/\/market-and-us.com\/blog\/\",\"name\":\"The Market and Us\",\"description\":\"Weekly Analysis of the Stock Market, Financial Coding and Online-Tools\",\"publisher\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/#\/schema\/person\/f32a93c5a88a9ec9a9595fff6179b097\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/market-and-us.com\/blog\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/#primaryimage\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/market-and-us.com\/blog\/wp-content\/uploads\/2019\/10\/spy-candlestick-data.jpg\",\"contentUrl\":\"https:\/\/market-and-us.com\/blog\/wp-content\/uploads\/2019\/10\/spy-candlestick-data.jpg\",\"width\":4032,\"height\":3024,\"caption\":\"How to code a backtest? That's the candlestick-data we're using.\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/#webpage\",\"url\":\"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/\",\"name\":\"How to code a backtest? - The Market and Us\",\"isPartOf\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/#primaryimage\"},\"datePublished\":\"2019-10-16T21:39:39+00:00\",\"dateModified\":\"2019-11-02T15:06:06+00:00\",\"description\":\"To know wether a trading strategy will lead to good profits or not a first step is to do a backtest. Here you can read about how to code a backtest.\",\"breadcrumb\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"item\":{\"@type\":\"WebPage\",\"@id\":\"https:\/\/market-and-us.com\/blog\/\",\"url\":\"https:\/\/market-and-us.com\/blog\/\",\"name\":\"Home\"}},{\"@type\":\"ListItem\",\"position\":2,\"item\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/#webpage\"}}]},{\"@type\":\"Article\",\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/#webpage\"},\"author\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/#\/schema\/person\/f32a93c5a88a9ec9a9595fff6179b097\"},\"headline\":\"How to code a backtest?\",\"datePublished\":\"2019-10-16T21:39:39+00:00\",\"dateModified\":\"2019-11-02T15:06:06+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/#webpage\"},\"commentCount\":2,\"publisher\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/#\/schema\/person\/f32a93c5a88a9ec9a9595fff6179b097\"},\"image\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/#primaryimage\"},\"keywords\":[\"backtest\",\"basics\",\"code\",\"how to code\",\"moving average\",\"programming\",\"Python\",\"SMA\",\"SPY\",\"strategy\"],\"articleSection\":[\"Knowledge\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/#respond\"]}]},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\/\/market-and-us.com\/blog\/#\/schema\/person\/f32a93c5a88a9ec9a9595fff6179b097\",\"name\":\"Alexander\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/market-and-us.com\/blog\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"http:\/\/market-and-us.com\/blog\/wp-content\/uploads\/2019\/10\/redakteur-96x96.png\",\"contentUrl\":\"http:\/\/market-and-us.com\/blog\/wp-content\/uploads\/2019\/10\/redakteur-96x96.png\",\"caption\":\"Alexander\"},\"logo\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/#personlogo\"},\"description\":\"Alexander bought his first stock in October 2009 without knowing about the luck for this point of time. In 2016 he started to trade, since 2017 he notes down watchlists and statistics every day and because he knows how to code since he was a child, he uses Python, PHP, HTML5 and JS for making the daily to-dos easier. Because many of his friends wanted him not to stop writing about the markets he started this blog to share his ideas and tools.\",\"sameAs\":[\"https:\/\/market-and-us.com\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yasr_visitor_votes":{"number_of_votes":0,"sum_votes":0,"stars_attributes":{"read_only":false,"span_bottom":false}},"_links":{"self":[{"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/posts\/60"}],"collection":[{"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/comments?post=60"}],"version-history":[{"count":8,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/posts\/60\/revisions"}],"predecessor-version":[{"id":189,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/posts\/60\/revisions\/189"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/media\/63"}],"wp:attachment":[{"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/media?parent=60"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/categories?post=60"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/tags?post=60"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}