{"id":2824,"date":"2021-05-04T02:22:24","date_gmt":"2021-05-04T02:22:24","guid":{"rendered":"https:\/\/www.tejwin.com\/en\/insights\/technical-analysis\/"},"modified":"2021-05-04T02:22:24","modified_gmt":"2021-05-04T02:22:24","slug":"technical-analysis","status":"publish","type":"insight","link":"https:\/\/www.tejwin.com\/en\/insights\/technical-analysis\/","title":{"rendered":"Technical Analysis"},"content":{"rendered":"<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" alt=\"\" class=\"wp-image-15623\" height=\"682\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/image-227.png\" width=\"1024\"\/><\/figure>\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\" id=\"2154\">Most investors mainly do their investment from<strong>\u00a0the technical analysis, the fundamental analysis and the chip analysis.\u00a0<\/strong>The technical analysis will use a lot of historical data among these 3 methods. Therefore, we are going to\u00a0<strong>use Python to share some technical analysis indicators<\/strong>\u00a0which investors used frequently this week.<\/p>\n<\/blockquote>\n<h2 class=\"wp-block-heading\" id=\"afda\"><strong>Highlights of this article <\/strong><\/h2>\n<ul class=\"wp-block-list\">\n<li>\ud83c\udf1f Technical Analysis Intro\/Indicators Intro<\/li>\n<li>\ud83c\udf1f Backtesting Sample<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"209c\"><strong>Links related to this article<\/strong><\/h2>\n<ul class=\"wp-block-list\">\n<li><strong>1\ufe0f\u20e3 API Official Website:\u00a0<\/strong><a href=\"https:\/\/api.tej.com.tw\/\" rel=\"noreferrer noopener\" target=\"_blank\"><strong>TEJ API Official Website<\/strong><\/a><\/li>\n<li><strong>2\ufe0f\u20e3 The Product Package:\u00a0<\/strong><a href=\"https:\/\/eshop.tej.com.tw\/E-Shop\/Edata_caseIntro\/1\" rel=\"noreferrer noopener\" target=\"_blank\"><strong>TEJ E-SHOP<\/strong><\/a><\/li>\n<li><strong>3\ufe0f\u20e3 Source Code:\u00a0<\/strong><a href=\"https:\/\/github.com\/tejtw\/TEJAPI_Python_Medium_Quant\" rel=\"noreferrer noopener\" target=\"_blank\"><strong>TEJ GITHUB<\/strong><\/a><\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"67c1\">What is technical analysis(TA)?<\/h2>\n<p class=\"wp-block-paragraph\" id=\"bdfc\"><strong>The technical analysis mainly uses past information such as historical data to explain the trends or determining the timing of investment.<\/strong>\u00a0However, the past is the past. But when you want to have a quantitative understanding of the current market situations, technical analysis can provide some indicators for investors to\u00a0<strong>simplify the past information<\/strong>\u00a0for them to reference.<\/p>\n<p class=\"wp-block-paragraph\" id=\"95c5\"><strong>We are not going to compare the pros and cons of the technical analysis in this article. How to use codes to have a further understanding of the commonly used technical indicators is the main goal this time!<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>Example of TA\uff1aMoving Average, KD Indicators, RSI, MACD, etc.<\/code><\/pre>\n<h2 class=\"wp-block-heading\" id=\"e0ca\">TA Indicators Introduction<\/h2>\n<p class=\"wp-block-paragraph\" id=\"7039\">Before we start the introduction, let\u2019s get the data for our TEJ API first! We are going to use the historical data of UMC(2303) this time.<\/p>\n<pre class=\"wp-block-code\"><code>import tejapi \nimport pandas as pd\nimport numpy as np\nimport datetime\ntejapi.ApiConfig.api_key = \"your key\"\nUMC = tejapi.get( \n    'TWN\/EWPRCD', \n    coid = '2303',\n    mdate={'gte':'2020-04-01', 'lte':'2021-04-25'},\n    opts={'columns': ['mdate','open_d','high_d','low_d','close_d',              'volume']}, \n    paginate=True)\nUMC = UMC.set_index('mdate')<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter caption-align-center\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1aVwit6o_jPRvB1XqYspFRQ.png\"\/><figcaption class=\"wp-element-caption\">UMC Historical Data<\/figcaption><\/figure>\n<p class=\"wp-block-paragraph\" id=\"96d6\">After getting the historical data, now we can enter our next step!<\/p>\n<h2 class=\"wp-block-heading\" id=\"3f56\">MACD(Moving Average Convergence Divergence)<\/h2>\n<p class=\"wp-block-paragraph\" id=\"6e33\">MACD compares the exponential moving average(EMA) of long(26) and short(12) days, subtracts to find the difference(DIF), and then calculates the difference again on the EMA. To put it simply,\u00a0<strong>MACD is used to judge the trading timing of the target through the staggered condition between the EMA of long and short days.<\/strong><\/p>\n<p class=\"wp-block-paragraph\" id=\"a8b7\"><strong>EMA:<\/strong>\u00a0The difference between the simple moving average is that EMA places a greater weight and significance on the most recent data points.<br \/><strong>DIF(Short-term):<\/strong>\u00a0The subtraction of short-term and long-term EMA, which usually represents a short-term trend.<br \/><strong>MACD(Long-term):<\/strong>\u00a0Taking the EMA of DIF again, which usually can judge the long-term trend.<\/p>\n<pre class=\"wp-block-code\"><code>def MACD(DF, a = 12, b =26, c =9):\n    '''\n    SMA: rolling\n    EMA: ewm\n    '''\n    df = DF.copy()\n    df[\"EMA_Fast\"] = \n         df['open_d'].ewm(span = a, min_periods = a).mean()\n    df[\"EMA_Slow\"] = \n         df['open_d'].ewm(span = b, min_periods = b).mean()\n    df[\"DIF\"] = df[\"EMA_Fast\"] - df[\"EMA_Slow\"]\n    df[\"MACD\"] = df['MACD'].ewm(span = c, min_periods = c).mean()\n    \n    return df<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1QI3JbBugCvOUK75pnSz_Rg.png\"\/><\/figure>\n<h2 class=\"wp-block-heading\" id=\"1857\">Bollinger Bands<\/h2>\n<p class=\"wp-block-paragraph\" id=\"53d4\">The Bollinger Bands are made by the combination of 3 lines, which are\u00a0<strong>the simple moving average, the upper standard deviation line, and the lower standard deviation line<\/strong>\u00a0to show the safe area of the stock price.<\/p>\n<p class=\"wp-block-paragraph\" id=\"26f8\">The reason for using 2 standard deviations is that in the statistical normal distribution, there is a 95% probability that it will fall between the 2 standard deviations. Although the market may not completely follow the normal distribution, it will still fall between 2 standard deviations most of the time.<\/p>\n<pre class=\"wp-block-code\"><code>def BollingerBand(DF, n=20):\n    '''\n    Standard Deviation: std\n    '''\n    df = DF.copy()\n    df['SMA'] = df['close_d'].rolling(window = n).mean()\n    df['BB_20dstd_up'] = \n         df['SMA'] + 2*df['close_d'].rolling(window = n).std(ddof=0)\n    df['BB_20dstd_down'] = \n         df['SMA'] - 2*df['close_d'].rolling(window = n).std(ddof=0)\n    df['BB_width'] = df['BB_20dstd_up'] - df['BB_20dstd_down']\n    df.dropna(inplace = True)\n    \n    return df<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/10vNfxhlJVEEAQI34ki7Qgw.png\"\/><\/figure>\n<h2 class=\"wp-block-heading\" id=\"0dfa\">RSI(Relative Strength Index)<\/h2>\n<p class=\"wp-block-paragraph\" id=\"a40a\"><strong>The Relative Strength Index is mainly used to access the \u201cstrength of the buyer\u2019s and seller\u2019s strength\u201d<\/strong>\u00a0in the stock market, and to access the overbought\/oversold situation through the recent price changes. The value of\u00a0<strong>RSI is within 0 to 100. The larger or smaller the value, the stronger the strength.<\/strong>\u00a0Usually, below 30 means oversold, over 70 means overbought.<\/p>\n<pre class=\"wp-block-code\"><code>def RSI(DF, n=14):\n    '''\n    n-day avarage increase = sum of n-day total daily increase \u00f7 n\n    n-day avarage decrease = sum of n-day total daily decrease \u00f7 n\n    '''\n    df = DF.copy()\n    df['daliy_change'] = \n         df['close_d'] - df['close_d'].shift(1)\n    df['dUp'] = \n         np.where(df['daliy_change'] &gt;= 0, df['daliy_change'], 0)\n    df['dDown'] = \n         np.where(df['daliy_change'] &lt; 0, -df['daliy_change'], 0)\navg_dUp = []\n    avg_dDown = []\n    dUp = df['dUp'].tolist()\n    dDown = df['dDown'].tolist()\n    \n    for i in range(len(df)):\n        if i &lt; n:\n            avg_dUp.append(0)\n            avg_dDown.append(0)\n        elif i == n:\n            avg_dUp.append(df['dUp'].ewm(span = n).mean()[n])\n            avg_dDown.append(df['dDown'].ewm(span = n).mean()[n])\n        else:\n            avg_dUp.append(((n-1)*avg_dUp[i-1] + dUp[i])\/n)\n            avg_dDown.append(((n-1)*avg_dDown[i-1] + dDown[i])\/n)\n    \n    df['avg_dUp'] = np.array(avg_dUp)\n    df['avg_dDown'] = np.array(avg_dDown)\ndf['RS'] = df['avg_dUp']\/df['avg_dDown']\n    df['RSI'] = df['RS'].apply(lambda x: x\/(1+x) * 100)\n        \n    return df<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1_1-kfnbSMY7IjneYlEXP8niw.png\"\/><\/figure>\n<h2 class=\"wp-block-heading\" id=\"3954\">ATR(Average True Range)<\/h2>\n<p class=\"wp-block-paragraph\" id=\"da12\"><strong>ATR refers to the true range of the stock price fluctuations within a period of time(14 days used in this article), which is a measure of the volatility of the target.<\/strong><\/p>\n<p class=\"wp-block-paragraph\" id=\"89af\">In order to calculate the ATR, we must first calculate the TR, and<strong>\u00a0the TR refers to the largest number among the following 3 numbers:<\/strong><br \/><strong>1. H-L:<\/strong>\u00a0Today\u2019s high minus today\u2019s low.<br \/><strong>2. H-PC:<\/strong>\u00a0The absolute value of today\u2019s high minus yesterday\u2019s close.<br \/><strong>3. L-PC:<\/strong>\u00a0The absolute value of today\u2019s low minus yesterday\u2019s close.<\/p>\n<pre class=\"wp-block-code\"><code>def ATR(DF, n=14):\n    '''\n    Close Price of Previous Day: close.shift()\n    '''\n    df = DF.copy()\n    df['H-L'] = abs(df['high_d'] - df['low_d'])\n    df['H-PC'] = abs(df['high_d'] - df['close_d'].shift())\n    df['L-PC'] = abs(df['low_d'] - df['close_d'].shift())\n    df['TR'] = df[['H-L', 'H-PC', 'L-PC']].max(axis =1, skipna =False)\n    df['ATR'] = df['TR'].ewm(span =n, min_periods=n).mean()\n    \n    return df<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1Ms7HuU9yElF2c_rghiIX7g.png\"\/><\/figure>\n<h2 class=\"wp-block-heading\" id=\"dc1c\">KD Indicator<\/h2>\n<p class=\"wp-block-paragraph\" id=\"7125\"><strong>The KD Indicator is mainly used to show the trend of the asset\u2019s price in the past period of time.<\/strong>\u00a0The 2 values of K and D are used to find possible price turning points as trading signals. The concept of the KD indicator is similar to RSI,\u00a0<strong>but the difference is that the KD indicator is based on the relative high or low of the latest price, while the RSI comparing the ratio of the strength of the buy\/sell.<\/strong><\/p>\n<p class=\"wp-block-paragraph\" id=\"5d9b\"><strong>Calculation:<br \/>RSV:\u00a0<\/strong>(Today\u2019s close -14day LOW)\uff0f(14day High -14day Low) * 100<strong><br \/>K:\u00a0<\/strong>Yesterday\u2019s K*(2\/3)\uff0bToday\u2019s RSV*(1\/3)<strong><br \/>D:\u00a0<\/strong>Yesterday\u2019s D*(2\/3)\uff0bToday\u2019s K*(1\/3)<\/p>\n<pre class=\"wp-block-code\"><code>def KD(DF, n = 14):\n    '''\n    function to calculate KD\n    '''\n    df = DF.copy()\n    df['High_9D'] = df['high_d'].rolling(n).max()\n    df['Low_9D'] = df['low_d'].rolling(n).min()\n    df['RSV'] = \n        (df['close_d'] - df['Low_9D']) \/ (df['High_9D'] - df['Low_9D']) * 100\ndf = df.dropna()    \n    df['K'] = np.zeros(len(df))\n    df['D'] = np.zeros(len(df))\n    \n    for i in range(len(df)):\n        if i == 0:\n            df['K'][i] = 50\n            df['D'][i] = 50\n        else:\n            df['K'][i] = df['K'][i-1]*(2\/3) + df['RSV'][i]*(1\/3)\n            df['D'][i] = df['D'][i-1]*(2\/3) + df['K'][i]*(1\/3)\n    \n    return df<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1U1gM3WXdD-9GZF98sK3Q-Q.png\"\/><\/figure>\n<h2 class=\"wp-block-heading\" id=\"3fc7\">Using TA Indicators to perform backtesting<\/h2>\n<p class=\"wp-block-paragraph\" id=\"592d\">We are going to use some indicators we\u2019ve mentioned above to construct our strategy.\u00a0<strong>Notice!! The signals are built without serious testing. The purpose is only to introduce how to applicate those indicators, so even if the results are not bad, you shouldn\u2019t use them directly!!<\/strong><\/p>\n<ul class=\"wp-block-list\">\n<li><strong>Strategy Example<\/strong><br \/>\u2013 Buy Signal:<br \/>MACD Increase and K &gt; 70 and Today\u2019s K &gt; Yesterday\u2019s K<br \/>\u2013 Sell Signal:<br \/>Today\u2019s Low &lt; (Yesterday\u2019s Close \u2014 Yesterday\u2019s ATR)<\/li>\n<li><strong>Strategy Assumption<\/strong><br \/>\u2013 We invest NT$1 dollar to buy when the buying signal appears and hold till the selling point appears.<br \/>\u2013 We ignore the transaction fees and security tax.<\/li>\n<\/ul>\n<pre class=\"wp-block-code\"><code>print(\"Calculating returns for \",\"UMC\")\nret = []\nfor i in range(1,len(UMC)):\n    buy_signal = UMC[\"DIF\"][i]&gt; UMC[\"MACD\"][i] and \\\n                 UMC[\"K\"][i]&gt; 70 and \\\n                 UMC[\"K\"][i] &gt; UMC[\"K\"][i-1]\nsell_signal = \n\u3000\u3000\u3000\u3000\u3000UMC[\"low_d\"][i] &lt; UMC[\"close_d\"][i-1] - UMC[\"ATR\"][i-1]\nif tickers_signal[\"UMC\"] == \"\":\n        tickers_ret[\"UMC\"].append(0)\n        if buy_signal:\n            tickers_signal[\"UMC\"] = \"Buy\"\nelif tickers_signal[\"UMC\"] == \"Buy\":\n        if sell_signal:\n            tickers_signal[\"UMC\"] = \"\"\n            tickers_ret[\"UMC\"].append(\n    ((UMC[\"close_d\"][i] - UMC[\"close_d\"][i-1])\/UMC[\"close_d\"][i-1]))\n        else:\n            tickers_ret[\"UMC\"].append(\n      (UMC[\"close_d\"][i]\/UMC[\"close_d\"][i-1])-1)\nUMC['ret'] = np.array(tickers_ret[\"UMC\"])\n<\/code><\/pre>\n<p class=\"wp-block-paragraph\" id=\"fef6\">After finding the signal points and the rate of return, let\u2019s make a simple plot to see how this strategy performs!<\/p>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1ljI7T7Pm1A5MZozlvIQAMw.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"4b1c\">It seems that our performance is acceptable, but we have ignored many possible costs of course. However, we could understand that if<strong>\u00a0we use the technical analysis indicators properly, investors can indeed simplify a lot of past information\u00a0<\/strong>and find the trading signals.<\/p>\n<h2 class=\"wp-block-heading\" id=\"f1aa\">Conclusion<\/h2>\n<p class=\"wp-block-paragraph\" id=\"19ae\"><strong>Different people will have different opinions toward the same data, but the indicators created from the data could still be used as a tool for investors to judge whether to buy or sell.\u00a0<\/strong>This article is to share how to build these indicators through Python by yourself. Of course, there are many packages that have included these indicators, but through these processes, you will understand more about these indicators and can adjust the parameters by yourself in the future!\ud83d\udcaa\ud83d\udcaa<\/p>\n<p class=\"wp-block-paragraph\" id=\"c514\"><strong>If you like this topic, please click \ud83d\udc4f below, giving us more support and encouragement. Additionally, if you have any questions or suggestions, please leave a message or email us, we will try our best to reply to you.\ud83d\udc4d\ud83d\udc4d<\/strong><\/p>\n<h2 class=\"wp-block-heading\" id=\"d9f0\">Links related to this article again!<\/h2>\n<ul class=\"wp-block-list\">\n<li><strong>1\ufe0f\u20e3 API Official Website:\u00a0<\/strong><a class=\"ek-link\" href=\"https:\/\/api.tej.com.tw\/\" rel=\"noreferrer noopener\" target=\"_blank\"><strong>TEJ API Official Website<\/strong><\/a><\/li>\n<li><strong>2\ufe0f\u20e3 The Product Package:\u00a0<\/strong><a href=\"https:\/\/eshop.tej.com.tw\/E-Shop\/Edata_caseIntro\/1\" rel=\"noreferrer noopener\" target=\"_blank\"><strong>TEJ E-SHOP<\/strong><\/a><\/li>\n<li><strong>3\ufe0f\u20e3 Source Code:\u00a0<\/strong><a href=\"https:\/\/github.com\/tejtw\/TEJAPI_Python_Medium_Quant\" rel=\"noreferrer noopener\" target=\"_blank\"><strong>TEJ GITHUB<\/strong><\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Most investors mainly do their investment from\u00a0the technical analysis, the fundamental analysis and the chip analysis.\u00a0The technical analysis will use a lot of historical data among these 3 methods. Therefore, we are going to\u00a0use Python to share some technical analysis indicators\u00a0which investors used frequently this week. Highlights of this article Links related to this article [\u2026]<\/p>\n","protected":false},"featured_media":2823,"template":"","tags":[70,50,65],"insight_category":[16],"class_list":["post-2824","insight","type-insight","status-publish","has-post-thumbnail","hentry","tag-tej-api","tag-market-data","tag-python","insight_category-quant-data-science"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/2824","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\/2823"}],"wp:attachment":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media?parent=2824"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/tags?post=2824"},{"taxonomy":"insight_category","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight_category?post=2824"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}