{"id":2564,"date":"2021-10-26T02:53:34","date_gmt":"2021-10-26T02:53:34","guid":{"rendered":"https:\/\/www.tejwin.com\/en\/insights\/kd-indicator\/"},"modified":"2021-10-26T02:53:34","modified_gmt":"2021-10-26T02:53:34","slug":"kd-indicator","status":"publish","type":"insight","link":"https:\/\/www.tejwin.com\/en\/insights\/kd-indicator\/","title":{"rendered":"KD Indicator"},"content":{"rendered":"<figure class=\"wp-block-image aligncenter caption-align-center\" id=\"fb66\"><a class=\"markup--anchor markup--figure-anchor\" href=\"https:\/\/unsplash.com\/@johnschno?utm_source=medium&amp;utm_medium=referral\" rel=\"photo-creator noopener\" target=\"_blank\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/0Z9W03udo1KmGhbC9.jpg\"\/><\/a><figcaption class=\"wp-element-caption\">Photo by\u00a0<a aria-label=\" (opens in a new tab)\" class=\"ek-link\" href=\"https:\/\/unsplash.com\/photos\/person-using-laptop-FlPc9_VocJ4\" rel=\"noreferrer noopener\" target=\"_blank\">John Schnobrich<\/a>\u00a0on\u00a0<a href=\"https:\/\/unsplash.com\/?utm_source=medium&amp;utm_medium=referral\" rel=\"noreferrer noopener\" target=\"_blank\">Unsplash<\/a><\/figcaption><\/figure>\n<h1 class=\"wp-block-heading\" id=\"0bc1\">Highlights<\/h1>\n<ul class=\"wp-block-list\">\n<li>Difficulty\uff1a\u2605\u2605\u2606\u2606\u2606<\/li>\n<li>Backtesting by KD indicator and relative performance of this strategy<\/li>\n<li>Advice: This article adopts TEJ database to calculate KD indicators, create signals and form the return. Before reading this,\u00a0<a class=\"ek-link\" href=\"https:\/\/medium.com\/tej-api-financial-data-anlaysis\/quant-8-backtesting-by-macd-indicator-f0dc6ceecef2\" rel=\"noopener\" target=\"_blank\">\u3010Quant(8)\u3011Backtesting by MACD Indicator<\/a>\u00a0is recommended to explore to better understand the basic procedure of calculating the costs and the framework of backtesting.<\/li>\n<\/ul>\n<h1 class=\"wp-block-heading\" id=\"ec2b\">Preface<\/h1>\n<p class=\"wp-block-paragraph\" id=\"ca4c\">KD indicator is one of the commonly-used indicators in technical analysis. It\u2019s mainly used for judging the current strength of stock price or possible timing of reversing. Following is the way to calculate this indicator<\/p>\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<ul class=\"wp-block-list\">\n<li><em>RSV = ((today\u2019s closed price \u2014 lowest price in past N days)\/(highest price in past N days \u2014 lowest price in past N days))*100<\/em><\/li>\n<li><em>K = yesterday\u2019s K* (2\/3) + today\u2019s RSV*(1\/3)<\/em><\/li>\n<li><em>D = yesterday\u2019s D* (2\/3) + today\u2019s K*(1\/3)<\/em><\/li>\n<\/ul>\n<\/blockquote>\n<p class=\"wp-block-paragraph\" id=\"bf55\">By observing the formula, we can interpret RSV as the strength of stock price in past N days (we use N=9 in this article). K is also called \u201cfast line\u201d, since it\u2019s highly sensitive to today\u2019s stock price; while D, obtained by using K, is less sensitive given its second smoothing calculation. In this article, we use following strategy to backtesting<\/p>\n<ul class=\"wp-block-list\">\n<li><em>K\u226420,\u00a0<\/em><strong><em>Buy 1000 shares<\/em><\/strong><em>, since it means the investors are overly pessimistic<\/em><\/li>\n<li><em>K\u226580,\u00a0<\/em><strong><em>Sell 1000 shares<\/em><\/strong><em>, because it implies the stock price are overheating<\/em><\/li>\n<\/ul>\n<h1 class=\"wp-block-heading\" id=\"8f07\">The Editing Environment and Modules Required<\/h1>\n<p class=\"wp-block-paragraph\" id=\"9f72\">Windows OS and Jupyter Notebook<\/p>\n<pre class=\"wp-block-preformatted\" id=\"9589\">#\u57fa\u672c\u529f\u80fd\nimport pandas as pd\nimport numpy as np\nimport copy<\/pre>\n<pre class=\"wp-block-preformatted\" id=\"cb27\">#\u7e6a\u5716\nimport plotly.graph_objects as go\nimport plotly.express as px<\/pre>\n<pre class=\"wp-block-preformatted\" id=\"b93c\">#TEJ\nimport tejapi\ntejapi.ApiConfig.api_key = 'Your Key'\ntejapi.ApiConfig.ignoretz = True<\/pre>\n<h2 class=\"wp-block-heading\" id=\"7a87\">Database Used<\/h2>\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/api.tej.com.tw\/columndoc.html?subId=42\" rel=\"noreferrer noopener\" target=\"_blank\">Unadjusted daily stock price<\/a>: the code of this database is \u2018TWN\/APRCD\u2019, covering listed firms\u2019 stock prices<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"e9c4\">Data Processing<\/h2>\n<p class=\"wp-block-paragraph\" id=\"0b29\"><strong>Step 1.\u00a0<\/strong>Obtain the stock price<\/p>\n<pre class=\"wp-block-preformatted\" id=\"69f5\">stock_data = tejapi.get('TWN\/APRCD',\n                  coid= '2002',\n                  mdate={'gte': '2021-01-01'}, \n                  opts={'columns': ['coid', 'mdate', 'open_d', 'close_d']},\n                  chinese_column_name=True,\n                  paginate=True)<\/pre>\n<p class=\"wp-block-paragraph\" id=\"ab60\">We choose China Steel Corporation (2002) as an example and the columns include opening price, which is used to calculate buying and selling price, and closing price that will produce buy and sell signal.<\/p>\n<figure class=\"wp-block-image aligncenter\" id=\"f9e0\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1gwveqVSD1Jmn5JD_vURcNw-2.png\"\/><\/figure>\n<h3 class=\"wp-block-heading has-text-align-left\" id=\"25e7\"><strong>Step 2.\u00a0<\/strong>Calculate KD and trading shares<\/h3>\n<pre class=\"wp-block-preformatted\" id=\"baf0\">kd_data = copy.deepcopy(stock_data)<\/pre>\n<pre class=\"wp-block-preformatted\" id=\"4e23\">#\u8a2d9\u5929\nkd_data['9_high'] = kd_data['\u6536\u76e4\u50f9(\u5143)'].rolling(9).max()\nkd_data['9_low'] = kd_data['\u6536\u76e4\u50f9(\u5143)'].rolling(9).min()<\/pre>\n<pre class=\"wp-block-preformatted\" id=\"a91c\">#rsv \nkd_data['rsv'] = ((kd_data['\u6536\u76e4\u50f9(\u5143)']-kd_data['9_low'])\/(kd_data['9_high']-kd_data['9_low']))*100\nkd_data['rsv'] =  kd_data['rsv'].fillna(50)<\/pre>\n<p class=\"wp-block-paragraph\" id=\"b638\">Since we need a clean\u00a0<code>stock_data<\/code>\u00a0later on, we use\u00a0<code>deepcopy()<\/code>\u00a0to copy its content to variable\u00a0<code>kd_data<\/code>. Then get the highest and lowest closed price over the past 9 days. Finally, RSV can be calculated and the missing value is filled with 50<\/p>\n<figure class=\"wp-block-image aligncenter\" id=\"be4e\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1mW-NInX6IpUAnRsJlIg_6g-2.png\"\/><\/figure>\n<pre class=\"wp-block-preformatted\" id=\"4366\">#\u521d\u59cb\u5316kd\u8207\u8cb7\u8ce3\u80a1\u6578\nkd_data['k'] = 0\nkd_data['d'] = 0\nkd_data['\u8cb7\u8ce3\u80a1\u6578'] = 0<\/pre>\n<pre class=\"wp-block-preformatted\" id=\"3ed9\">#\u8ff4\u5708\u4fee\u6b63k d\u503c\nhold = 0\nfor i in range(len(kd_data)):\n    #\u5148\u7b97\u51fa\u7576\u671f\u7684k d \u503c\n    if i == 0:\n        kd_data.loc[i,'k'] = 50\n        kd_data.loc[i,'d'] = 50\n    else:\n        kd_data.loc[i,'k'] = (2\/3* kd_data.loc[i-1,'k']) + (kd_data.loc[i,'rsv']\/3)\n        kd_data.loc[i,'d'] = (2\/3* kd_data.loc[i-1,'d']) + (kd_data.loc[i,'k']\/3)\n    \n    if kd_data.loc[i, 'k'] &lt;= 20:\n        if hold == 0:                             \n            kd_data.loc[i+1, '\u8cb7\u8ce3\u80a1\u6578'] = 1000        \n            hold = 1                                    \n    elif kd_data.loc[i,'k'] &gt;= 80:\n        if hold &gt; 0:                                    \n            kd_data.loc[i+1,'\u8cb7\u8ce3\u80a1\u6578'] = -1000     \n            hold = 0<\/pre>\n<p class=\"wp-block-paragraph\" id=\"422c\">After initializing KD and trading shares, we get into the loop to calculate KD that we need to produce signals for buy and sell. Because current KD is based on previous KD values, we have to set the first KD as 50 by default. Then\u00a0<code>hold\u00a0<\/code>represents whether we hold the shares (1 = Yes, 0=No). If buy signal(K\u226420) is met and we have no stocks on hand, we\u2019ll buy 1000 shares at the opening of next day. On the other side, if sell signal (K\u226580) is satisfied and we have some shares, then sell it next day at the opening price.<\/p>\n<figure class=\"wp-block-image aligncenter\" id=\"87ef\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1y-ubfvkcTtfITVHAIG8hDA-2.png\"\/><\/figure>\n<h3 class=\"wp-block-heading has-text-align-center\" id=\"1c11\"><strong class=\"markup--strong markup--p-strong\"><strong>Step 3.\u00a0<\/strong>Visualize the trading action (See the details in source code)<\/strong><\/h3>\n<figure class=\"wp-block-image aligncenter\" id=\"f001\"><img decoding=\"async\" alt=\"KD\u6307\u6a19\u8cb7\u9ede\u5206\u5e03\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/19TbkijzYG_0qrd-h9eiYcw-2.png\"\/><\/figure>\n<h1 class=\"wp-block-heading\" id=\"60d0\">Calculate the return<\/h1>\n<p class=\"wp-block-paragraph\" id=\"c590\">In\u00a0<a class=\"ek-link\" href=\"https:\/\/medium.com\/tej-api-financial-data-anlaysis\/quant-8-backtesting-by-macd-indicator-f0dc6ceecef2\" rel=\"noopener\" target=\"_blank\">\u3010Quant(8)\u3011Backtesting by MACD Indicator<\/a>, we have discussed the details in the calculation of frictions cost and the method to calculate return with initial principal. In this article, we use function to achieve all of it.<\/p>\n<pre class=\"wp-block-preformatted\" id=\"a064\">def ret(data, principal):\n    \n    #\u8a08\u7b97\u6210\u672c\n    data['\u624b\u7e8c\u8cbb'] = data['\u958b\u76e4\u50f9(\u5143)']* abs(data['\u8cb7\u8ce3\u80a1\u6578'])*0.001425\n    data['\u624b\u7e8c\u8cbb'] = np.where((data['\u624b\u7e8c\u8cbb']&gt;0)&amp;(data['\u624b\u7e8c\u8cbb'] &lt;20), 20, data['\u624b\u7e8c\u8cbb'])\n    data['\u8b49\u4ea4\u7a05'] = np.where(data['\u8cb7\u8ce3\u80a1\u6578']&lt;0, data['\u958b\u76e4\u50f9(\u5143)']* abs(data['\u8cb7\u8ce3\u80a1\u6578'])*0.003, 0)\n    data['\u6469\u64e6\u6210\u672c'] = (data['\u624b\u7e8c\u8cbb'] + data['\u8b49\u4ea4\u7a05']).apply(np.floor)\n    \n    #\u8a08\u7b97\u8cc7\u7522\u50f9\u503c\n    data['\u80a1\u7968\u50f9\u503c'] = data['\u8cb7\u8ce3\u80a1\u6578'].cumsum() * data['\u6536\u76e4\u50f9(\u5143)']\n    data['\u73fe\u91d1\u50f9\u503c'] = principal - data['\u6469\u64e6\u6210\u672c'] + (data['\u958b\u76e4\u50f9(\u5143)']* -data['\u8cb7\u8ce3\u80a1\u6578']).cumsum() \n    data['\u8cc7\u7522\u50f9\u503c'] = data['\u80a1\u7968\u50f9\u503c'] + data['\u73fe\u91d1\u50f9\u503c']\n    \n    #\u8a08\u7b97\u5831\u916c\u7387\n    data['\u7576\u65e5\u50f9\u503c\u8b8a\u52d5(%)'] = (data['\u8cc7\u7522\u50f9\u503c']\/data['\u8cc7\u7522\u50f9\u503c'].shift(1) - 1)*100\n    data['\u7d2f\u8a08\u5831\u916c(%)'] = (data['\u8cc7\u7522\u50f9\u503c']\/principal - 1)*100\n    \n    return data<\/pre>\n<p class=\"wp-block-paragraph\" id=\"cb70\">With the data containing trading shares and initial principal, we can quickly get the transaction costs and return. In this article, we set 30,000 as our principal<\/p>\n<pre class=\"wp-block-preformatted\" id=\"f41a\">kd_return = ret(data = kd_data, principal = 30000)<\/pre>\n<figure class=\"wp-block-image aligncenter\" id=\"c05f\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1fdkG0Nk-fxVKb1bU-p1Jbg-2.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"0d53\">Besides, to demonstrate whether this strategy performs relatively well, we add buy-and-hold strategy and market performance as our benchmarks<\/p>\n<ul class=\"wp-block-list\">\n<li>The return of buy-and-hold<\/li>\n<li><\/li>\n<\/ul>\n<pre class=\"wp-block-preformatted\" id=\"3d04\">bh_data = copy.deepcopy(stock_data)\nbh_data['\u8cb7\u8ce3\u80a1\u6578'] = 0\nbh_data.loc[0, '\u8cb7\u8ce3\u80a1\u6578'] = 1000\nbh_data.loc[len(bh_data)-1, '\u8cb7\u8ce3\u80a1\u6578'] = -1000\nbh_return = ret(data=bh_data, principal = 30000)<\/pre>\n<p class=\"wp-block-paragraph\" id=\"9afd\">Here we also use\u00a0<code>deepcopy()<\/code>\u00a0to get stock price, and choose to buy at the beginning and sell at the end during the same period with initial principal of 30000.<\/p>\n<figure class=\"wp-block-image aligncenter\" id=\"7d34\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1Si1_-iG-inACqh1tZb8Z6Q-2.png\"\/><\/figure>\n<h3 class=\"wp-block-heading\">Market Performance<\/h3>\n<pre class=\"wp-block-preformatted\" id=\"a22b\">market = tejapi.get('TWN\/APRCD',\n                    coid = 'Y9997',\n                    mdate = {'gte':'2021-01-01'},\n                    opts = {'columns':['coid','mdate', 'roi']},\n                    chinese_column_name = True)\nmarket['\u7d2f\u8a08\u5831\u916c(%)'] = (market['\u5831\u916c\u7387\uff05'].apply(lambda x:0.01*x +1).cumprod() - 1)*100<\/pre>\n<p class=\"wp-block-paragraph\" id=\"d956\">Obtain return of market return index (Y9997) to stands for market performance and calculate the cumulative return<\/p>\n<figure class=\"wp-block-image aligncenter\" id=\"2e33\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1Mi61oG9rLy8soWJROFM_ZQ-2.png\"\/><\/figure>\n<h2 class=\"wp-block-heading\" id=\"7d25\">Performance comparison<\/h2>\n<p class=\"wp-block-paragraph\" id=\"d4e9\"><strong>Step 1.\u00a0<\/strong>Comparison of cumulative return (See the details in source code)<\/p>\n<figure class=\"wp-block-image aligncenter\" id=\"c44a\"><img decoding=\"async\" alt=\"KD\u6307\u6a19\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1P2WsWMIGXdXdeS1qfBcLMQ-2.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"781c\">Here we can see this year\u2019s market performance is relatively weak. The return of buy-and-hold strategy basically follows the stock price, thereby benefitting from upside trend in May. And KD strategy considers not only the stock price, but also positions. For example, there\u2019s no change in cumulative return in May because we hold no stocks in hand and only have cash positions, leading to missing the strong bullish trend.<\/p>\n<p class=\"wp-block-paragraph\" id=\"6df7\"><strong>Step 2.\u00a0<\/strong>Performance table (See the details in source code)<\/p>\n<figure class=\"wp-block-image aligncenter\" id=\"1293\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1N6mJLWZKPh8BugQ_bubpqw-2.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"7181\">Although annualized return of KD and buy-and-hold strategy are quite similar, KD appears to be better than others after taking the risk into consideration<\/p>\n<h2 class=\"wp-block-heading\" id=\"0a82\">Conclusion<\/h2>\n<p class=\"wp-block-paragraph\" id=\"1269\">After reading this article, we believe readers can better understand the definition and limitations of KD indicator. For instance, when stock market seems overly optimistic, the sell signal will pop up. However, if the bullish market remains for quite a long time, using KD strategy to exit the market may not be a smart choice. Overtrading, causing lots of friction costs, may be the common issue in technical analysis that drags down its cumulative return. At the end, its performance may even be worse than just buy-and-holding! Thus, other indicators are still needed to make more proper judgement of buying and selling. If readers are interested in this kind of technical analysis backtesting, welcome to purchase the plan offered in\u00a0<a href=\"https:\/\/eshop.tej.com.tw\/E-Shop\/Edata_intro\" rel=\"noreferrer noopener\" target=\"_blank\">TEJ E-Shop<\/a>, since we all know data of higher quality is the important foundation of the closest-to-real-world backtesting.<\/p>\n<h2 class=\"wp-block-heading\" id=\"7389\">Source Code<\/h2>\n<ul class=\"wp-block-list\">\n<li><a class=\"ek-link\" href=\"https:\/\/gist.github.com\/tej87681088\/85e765bb1e3779867fdf62b5846f0ab4\" rel=\"noopener\" target=\"_blank\">Github<\/a><\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"b58c\">Extended Reading<\/h2>\n<ul class=\"wp-block-list\">\n<li><a class=\"ek-link\" href=\"https:\/\/medium.com\/tej-api-financial-data-anlaysis\/application-5-modular-backtesting-system-ecfbe883899e\" rel=\"noopener\" target=\"_blank\">\u3010Application(5)\u3011Modular Backtesting System<\/a><\/li>\n<li><a class=\"ek-link\" href=\"https:\/\/medium.com\/tej-api-financial-data-anlaysis\/quant-2-technical-analysis-2958435a8922\" rel=\"noopener\" target=\"_blank\">\u3010Quant(2)\u3011- Technical Analysis<\/a><\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"77bf\">Related Link<\/h2>\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/api.tej.com.tw\/index.html\" rel=\"noreferrer noopener\" target=\"_blank\">TEJ API<\/a><\/li>\n<li><a href=\"https:\/\/eshop.tej.com.tw\/E-Shop\/Edata_intro\" rel=\"noreferrer noopener\" target=\"_blank\">TEJ E-Shop<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>KD indicator is one of the commonly-used indicators in technical analysis. It\u2019s mainly used for judging the current strength of stock price or possible timing of reversing. Following is the way to calculate this indicator<\/p>\n","protected":false},"featured_media":2563,"template":"","tags":[50,65,70],"insight_category":[16],"class_list":["post-2564","insight","type-insight","status-publish","has-post-thumbnail","hentry","tag-market-data","tag-python","tag-tej-api","insight_category-quant-data-science"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/2564","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight"}],"about":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/types\/insight"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media\/2563"}],"wp:attachment":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media?parent=2564"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/tags?post=2564"},{"taxonomy":"insight_category","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight_category?post=2564"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}