{"id":69,"date":"2019-10-19T15:16:53","date_gmt":"2019-10-19T13:16:53","guid":{"rendered":"http:\/\/market-and-us.com\/blog\/?p=69"},"modified":"2019-11-02T15:56:20","modified_gmt":"2019-11-02T14:56:20","slug":"how-to-code-basic-stock-scanner","status":"publish","type":"post","link":"https:\/\/market-and-us.com\/blog\/how-to-code-basic-stock-scanner-69\/","title":{"rendered":"How to code a basic stock scanner?"},"content":{"rendered":"\n<p>After writing the <a href=\"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/\">code for a basic backtest<\/a> I got the feedback that <strong>a stock scanner would be useful<\/strong> to find the signals validated with backtests. And here it is: The instructions how to code a stock scanner.<br>In the first steps <strong>we use only one stock<\/strong> for backtesting or scanning. Because for scanning the whole market you will need all the data for 500 (S&amp;P 500) or 6000-8000 stocks. In my opinion you can do that just with a server running the data loading over night.<\/p>\n\n\n\n<p>But now let&#8217;s start with our little scan code:<\/p>\n\n\n\n<h2>Getting the stock data<\/h2>\n\n\n\n<p>Like for the backtest we need to <strong>download or import the stock data<\/strong> as csv-file. I could present you a file on my blog server but that wouldn&#8217;t make sense because you want to scan the stock for the current day and for tomorrow, &#8230;<br>Therefore we need a solution to get <strong>the daily data for a stock symbol<\/strong>. Again you can use the data of your broker or other free or cheap APIs. For our example I will use a manual method. You will learn automatic methods later for loading many stocks without &#8220;doing&#8221; anything.<\/p>\n\n\n\n<h3>The 4 steps to download historical data online:<\/h3>\n\n\n\n<ol><li>Visit the <a href=\"https:\/\/finance.yahoo.com\/\">Yahoo Finance website<\/a>.<\/li><li>Click in the search field at the top and type your stock symbol (e.g. GE).<\/li><li>Click on the tab Historical Data.<\/li><li>The time period is already set to a year and the frequency to daily data, so you just click the &#8220;Download Data&#8221;-link to get your csv-file.<\/li><\/ol>\n\n\n\n<p>If you have <strong>problems getting the data<\/strong> (or anything changed with the Yahoo Finance services) write me a comment below and <a href=\"https:\/\/market-and-us.com\/blog\/code\/GE.csv\">download a sample file here<\/a>.<\/p>\n\n\n\n<h2>Loading data in variable<\/h2>\n\n\n\n<p>Like in the last article we use the library <code><span style=\"text-decoration: underline;\">pandas<\/span><\/code><span style=\"text-decoration: underline;\"> for the financial calculations<\/span>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import pandas as pd\ndata = pd.read_csv(\"GE.csv\")<\/code><\/pre>\n\n\n\n<p>And during the coding process it&#8217;s always interesting to get the first and the last lines for <span style=\"text-decoration: underline;\">checking the content<\/span>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>print(data.head())\nprint(data.tail())<\/code><\/pre>\n\n\n\n<h2>Setting up the strategy<\/h2>\n\n\n\n<p>I am sure you&#8217;re interested in <span style=\"text-decoration: underline;\">other indicators<\/span> than the SMA and you want to code strategies with <span style=\"text-decoration: underline;\">EMA, stochastics, MACD, ATR<\/span> and many others. Am I right?<br>But that&#8217;s complex and I have to explain you how to use a function with a <code>DataFrame<\/code> (the variable type of the <code>pandas<\/code> library). So you have to wait for the next articles.<\/p>\n\n\n\n<p>Our strategy is still with <span style=\"text-decoration: underline;\">two simple moving averages crossing<\/span> each other. But we will add the form of the candle.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote\"><p><strong>Please notice: The strategies in the basic articles are not to make money. They are just examples for our code!<\/strong><\/p><\/blockquote>\n\n\n\n<h3>Crossing of two moving averages<\/h3>\n\n\n\n<p>Here the <span style=\"text-decoration: underline;\">20 and the 50 SMA<\/span><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>data['SMA20'] = data.Close.rolling(20).mean()\ndata['SMA50'] = data.Close.rolling(50).mean()<\/code><\/pre>\n\n\n\n<p>and the <span style=\"text-decoration: underline;\">crossing variables<\/span> for long and short positions:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>data['long']  = (data.SMA20 > data.SMA50) &amp; (data.SMA20.shift(1) &lt;= data.SMA50.shift(1))\ndata['short'] = (data.SMA20 &lt; data.SMA50) &amp; (data.SMA50.shift(1) >= data.SMA50.shift(1)) <\/code><\/pre>\n\n\n\n<p>Now you will get the <strong>long-signal, when the 20 SMA is above the 50 SMA and the 20 SMA was below the 50 SMA the day before<\/strong>.<\/p>\n\n\n\n<h3>Green body bigger than the last five bodies<\/h3>\n\n\n\n<p>To add the condition for a <span style=\"text-decoration: underline;\">green candle with a body bigger than the body of the last 5 candles<\/span> (red candle for the short signal) you do not have to set it for the whole dataset. It&#8217;s much easier to write it for the last line:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>lastrow  = data.iloc[-1]\ngreen    = lastrow.Close > lastrow.Open\nred      = lastrow.Open > lastrow.Close\nmaxBody5 = (df.Close.iloc[-5:] - df.Open.iloc[-5:]).abs().max()\nbigbody  = abs(lastrow.Close - lastrow.Open) > maxBody5<\/code><\/pre>\n\n\n\n<p>The <code>lastrow<\/code> is checked for a <code>green<\/code> body. And then the biggest body of the last 5 candles (<code>maxBody5<\/code>) is compared with the current body, resulting in the variable <code>bigbody<\/code>.<\/p>\n\n\n\n<h2>Scan the stock<\/h2>\n\n\n\n<p>To <span style=\"text-decoration: underline;\">scan the stock<\/span> (here <strong>GE<\/strong>) wether our strategy is showing us an entry signal or not, you can simply type:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>long_signal  = data['long'].iloc[-1]  and green and bigbody\nshort_signal = data['short'].iloc[-1] and red   and bigbody<\/code><\/pre>\n\n\n\n<h2>Output of the result<\/h2>\n\n\n\n<p>The last step is to <span style=\"text-decoration: underline;\">show the result<\/span>. And you just write:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>if long_signal:\n    print(\"Today there's a buy signal for GE.\")\nelif short_signal:\n    print(\"Today there's a short signal for GE.\")\nelse:\n    print(\"No signals for GE today.\")<\/code><\/pre>\n\n\n\n<p>That&#8217;s it. I hope again you learned some coding possibilities with this articles to open the world for all your ideas one step more.<\/p>\n\n\n\n<p><strong>Tell me<\/strong> what you like and what not, what&#8217;s missing and where you had problems. <strong>I will help you<\/strong> in the comments section to get your program done.<br>Good results for your scans, huge profits with your strategy development and fun with your coding!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>After writing the code for a basic backtest I got the feedback that a stock scanner would be useful to find the signals validated with backtests. And here it is: The instructions how to code a stock scanner.In the first steps we use only one stock for backtesting or scanning. Because for scanning the whole [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":83,"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":[26,20,32,25,33,22,21,27,28,23,29,30],"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 basic stock scanner? - The Market and Us<\/title>\n<meta name=\"description\" content=\"In this article you will learn how to code a basic stock scanner. With code examples you can find a step by step explanation.\" \/>\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-basic-stock-scanner-69\/\" \/>\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 basic stock scanner? - The Market and Us\" \/>\n<meta property=\"og:description\" content=\"In this article you will learn how to code a basic stock scanner. With code examples you can find a step by step explanation.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/market-and-us.com\/blog\/how-to-code-basic-stock-scanner-69\/\" \/>\n<meta property=\"og:site_name\" content=\"The Market and Us\" \/>\n<meta property=\"article:published_time\" content=\"2019-10-19T13:16:53+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2019-11-02T14:56:20+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/market-and-us.com\/blog\/wp-content\/uploads\/2019\/10\/balls-blue-bright-887821.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"2448\" \/>\n\t<meta property=\"og:image:height\" content=\"2448\" \/>\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=\"4 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-basic-stock-scanner-69\/#primaryimage\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/market-and-us.com\/blog\/wp-content\/uploads\/2019\/10\/balls-blue-bright-887821.jpg\",\"contentUrl\":\"https:\/\/market-and-us.com\/blog\/wp-content\/uploads\/2019\/10\/balls-blue-bright-887821.jpg\",\"width\":2448,\"height\":2448,\"caption\":\"The balls are like stocks. Stock scan is like picking one of many color balls out of a pool.\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-basic-stock-scanner-69\/#webpage\",\"url\":\"https:\/\/market-and-us.com\/blog\/how-to-code-basic-stock-scanner-69\/\",\"name\":\"How to code a basic stock scanner? - The Market and Us\",\"isPartOf\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-basic-stock-scanner-69\/#primaryimage\"},\"datePublished\":\"2019-10-19T13:16:53+00:00\",\"dateModified\":\"2019-11-02T14:56:20+00:00\",\"description\":\"In this article you will learn how to code a basic stock scanner. With code examples you can find a step by step explanation.\",\"breadcrumb\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-basic-stock-scanner-69\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/market-and-us.com\/blog\/how-to-code-basic-stock-scanner-69\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-basic-stock-scanner-69\/#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-basic-stock-scanner-69\/#webpage\"}}]},{\"@type\":\"Article\",\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-basic-stock-scanner-69\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-basic-stock-scanner-69\/#webpage\"},\"author\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/#\/schema\/person\/f32a93c5a88a9ec9a9595fff6179b097\"},\"headline\":\"How to code a basic stock scanner?\",\"datePublished\":\"2019-10-19T13:16:53+00:00\",\"dateModified\":\"2019-11-02T14:56:20+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-basic-stock-scanner-69\/#webpage\"},\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/#\/schema\/person\/f32a93c5a88a9ec9a9595fff6179b097\"},\"image\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-basic-stock-scanner-69\/#primaryimage\"},\"keywords\":[\"basics\",\"code\",\"GE\",\"how to code\",\"knowledge\",\"moving average\",\"Python\",\"scan\",\"scanning\",\"SMA\",\"stock\",\"trading\"],\"articleSection\":[\"Knowledge\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/market-and-us.com\/blog\/how-to-code-basic-stock-scanner-69\/#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\/69"}],"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=69"}],"version-history":[{"count":10,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/posts\/69\/revisions"}],"predecessor-version":[{"id":187,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/posts\/69\/revisions\/187"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/media\/83"}],"wp:attachment":[{"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/media?parent=69"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/categories?post=69"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/tags?post=69"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}