{"id":117,"date":"2019-10-26T13:47:44","date_gmt":"2019-10-26T11:47:44","guid":{"rendered":"http:\/\/market-and-us.com\/blog\/?p=117"},"modified":"2019-11-02T15:49:21","modified_gmt":"2019-11-02T14:49:21","slug":"how-to-code-indicators","status":"publish","type":"post","link":"https:\/\/market-and-us.com\/blog\/how-to-code-indicators-117\/","title":{"rendered":"How to code the first indicators"},"content":{"rendered":"\n<p>In this article I want to show you how you can write the <strong>code for an indicator using functions<\/strong>.<\/p>\n\n\n\n<p>In our <strong>last two coding articles<\/strong> about <a href=\"https:\/\/market-and-us.com\/blog\/how-to-code-a-backtest-60\/\">backtesting<\/a> and <a href=\"https:\/\/market-and-us.com\/blog\/how-to-code-basic-stock-scanner-69\/\">scanning<\/a> we used the Python library <code><a href=\"https:\/\/pandas.pydata.org\/\">pandas<\/a><\/code> for financial data. And in Python you can use your own <strong>functions<\/strong> instead of the ones in the libraries.<\/p>\n\n\n\n<p>Here an <span style=\"text-decoration: underline;\">easy example<\/span>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def calculateTarget(entry, stop, multiple):\n    return entry + (entry - stop) * multiple\n\nEP = 46.3\nSL = 44.96\n# target should be at 2R\nTP = calculateTarget(EP, SL, 2)\nprint(\"EP: {:5.2f}\\nSL: {:5.2f}\\nTP: {:5.2f}\".format(EP, SL, TP))<\/code><\/pre>\n\n\n\n<p>Now we can use a <span style=\"text-decoration: underline;\">function to integrate the SMA<\/span> for making the usage in our code much easier:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def sma(data_series, period):\n    return data_series.rolling(period).mean()<\/code><\/pre>\n\n\n\n<p>A <code>Series<\/code> is a column (like Close, Low, Volume) in a <code>pandas<\/code> <code>DataFrame<\/code> (used as object for our whole candlestick package) and with the above code we just can use <code>sma(data.Close, 200)<\/code> to get the <span style=\"text-decoration: underline;\">200 SMA which is based on the close<\/span> of each candle but we can also write <code>sma(data.Volume, 30)<\/code> to get the <span style=\"text-decoration: underline;\">average volume of the last 30 days<\/span>.<\/p>\n\n\n\n<p>With the knowledge about functions we can also create an indicator for the exponential moving average (EMA):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def ema(data_series, period):\n    return data_series.ewm(span=period).mean()<\/code><\/pre>\n\n\n\n<p>Easy, right? Yes. It&#8217;s a function of the library <code>pandas<\/code> and we can use it so easily. Now you can write <code>ema(data.Close, 20)<\/code> to get the <span style=\"text-decoration: underline;\">20 EMA<\/span>.<\/p>\n\n\n\n<p>But for all the following calculations or usage of our <code>DataFrame<\/code> we have to <span style=\"text-decoration: underline;\">pay attention on the first rows<\/span> according to the number of the biggest moving average. If it&#8217;s the 200 SMA or 200 EMA the first 200 rows will contain a &#8220;<code>nan<\/code>&#8221; or &#8220;<code>NaN<\/code>&#8220;.<br>That&#8217;s a placeholder because for the first 200 rows <span style=\"text-decoration: underline;\">the functions cannot compute the SMA or EMA<\/span>.<\/p>\n\n\n\n<p>Of course, there is a solution for this problem:<br>If our <code>DataFrame<\/code> is called <code>data<\/code> we simply add <code>data = data.iloc[200:]<\/code> and the first 200 rows will not be included in your variable.<\/p>\n\n\n\n<p>For your <span style=\"text-decoration: underline;\">overview<\/span> I wrote the following little code (<strong><span style=\"text-decoration: underline;\">warning<\/span><\/strong>: <em>not for real trading, just as an example!!<\/em>). You can see how you combine the implementation of the libraries, the functions and your main code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># import of libraries\nimport pandas as pd\n\n# functions\ndef sma(data_series, period):\n    return data_series.rolling(period).mean()\n\ndef ema(data_series, period):\n    return data_series.ewm(span=period).mean()\n\n# variables\nfilename = \"SPY.csv\"\n\n# preparing the data\ndata             = pd.read_csv(filename)\ndata['SMA200']   = sma(data.Close, 200)\ndata['EMA20']    = ema(data.Close, 20)\ndata['EMA50']    = ema(data.Close, 50)\ndata['AvgVol']   = sma(data.Volume, 60)\n\n# little strategy\ndata['trend']    = (data.EMA20 > data.EMA50) &amp; (data.EMA50 > data.SMA200)\ndata['minVol']   = data.AvgVol > 200000\ndata['green']    = data.Close > data.Open\n\n# checking the last date in our data (mostly the current date)\ncurrent          = data.iloc[-1]\nif current.trend and current.minVol and current.green:\n    print(\"Yes, you should get in.\")\nelse:\n    print(\"Nothing to do. Enjoy your day!\")<\/code><\/pre>\n\n\n\n<p>If you not just read the article but wrote the code and tried around with it you <strong>reached the next step in programming<\/strong> financial data. I am <strong>happy to teach you<\/strong> all the elements and you can subscribe the RSS-feed or the newsletter to get informed about new articles and other news about <a href=\"https:\/\/market-and-us.com\">market-and-us.com<\/a>!<\/p>\n\n\n\n<p>Please, write me about your experiences and <strong>questions in the comments<\/strong> below and I will answer every question. Thanks for being in my community!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article I want to show you how you can write the code for an indicator using functions. In our last two coding articles about backtesting and scanning we used the Python library pandas for financial data. And in Python you can use your own functions instead of the ones in the libraries. Here [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":121,"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":[20,39,40,22,21,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 the first indicators - The Market and Us<\/title>\n<meta name=\"description\" content=\"Do you want to know how to code indicators for stock data with Python? We present you a basic code with our explanations.\" \/>\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-indicators-117\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to code the first indicators - The Market and Us\" \/>\n<meta property=\"og:description\" content=\"Do you want to know how to code indicators for stock data with Python? We present you a basic code with our explanations.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/market-and-us.com\/blog\/how-to-code-indicators-117\/\" \/>\n<meta property=\"og:site_name\" content=\"The Market and Us\" \/>\n<meta property=\"article:published_time\" content=\"2019-10-26T11:47:44+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2019-11-02T14:49:21+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/market-and-us.com\/blog\/wp-content\/uploads\/2019\/10\/backlight-indicator-of-orange-oldtimer.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1350\" \/>\n\t<meta property=\"og:image:height\" content=\"900\" \/>\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-indicators-117\/#primaryimage\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/market-and-us.com\/blog\/wp-content\/uploads\/2019\/10\/backlight-indicator-of-orange-oldtimer.jpg\",\"contentUrl\":\"https:\/\/market-and-us.com\/blog\/wp-content\/uploads\/2019\/10\/backlight-indicator-of-orange-oldtimer.jpg\",\"width\":1350,\"height\":900,\"caption\":\"Like the indicators of our stock charts the backlights of the car are indicators as well.\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-indicators-117\/#webpage\",\"url\":\"https:\/\/market-and-us.com\/blog\/how-to-code-indicators-117\/\",\"name\":\"How to code the first indicators - The Market and Us\",\"isPartOf\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-indicators-117\/#primaryimage\"},\"datePublished\":\"2019-10-26T11:47:44+00:00\",\"dateModified\":\"2019-11-02T14:49:21+00:00\",\"description\":\"Do you want to know how to code indicators for stock data with Python? We present you a basic code with our explanations.\",\"breadcrumb\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-indicators-117\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/market-and-us.com\/blog\/how-to-code-indicators-117\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-indicators-117\/#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-indicators-117\/#webpage\"}}]},{\"@type\":\"Article\",\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-indicators-117\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-indicators-117\/#webpage\"},\"author\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/#\/schema\/person\/f32a93c5a88a9ec9a9595fff6179b097\"},\"headline\":\"How to code the first indicators\",\"datePublished\":\"2019-10-26T11:47:44+00:00\",\"dateModified\":\"2019-11-02T14:49:21+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/market-and-us.com\/blog\/how-to-code-indicators-117\/#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-indicators-117\/#primaryimage\"},\"keywords\":[\"code\",\"EMA\",\"functions\",\"moving average\",\"Python\",\"SMA\",\"stock\",\"trading\"],\"articleSection\":[\"Knowledge\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/market-and-us.com\/blog\/how-to-code-indicators-117\/#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\/117"}],"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=117"}],"version-history":[{"count":4,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/posts\/117\/revisions"}],"predecessor-version":[{"id":185,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/posts\/117\/revisions\/185"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/media\/121"}],"wp:attachment":[{"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/media?parent=117"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/categories?post=117"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/market-and-us.com\/blog\/wp-json\/wp\/v2\/tags?post=117"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}