{"id":2191,"date":"2022-12-12T10:09:00","date_gmt":"2022-12-12T10:09:00","guid":{"rendered":"https:\/\/www.tejwin.com\/en\/insights\/lstm-trading-signal-detection\/"},"modified":"2026-09-23T18:16:38","modified_gmt":"2026-09-23T18:16:38","slug":"lstm-trading-signal-detection","status":"publish","type":"insight","link":"https:\/\/www.tejwin.com\/en\/insights\/lstm-trading-signal-detection\/","title":{"rendered":"LSTM Trading Signal Detection"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\" id=\"8f22\">Optimizing Trading Signals Using LSTM Deep Learning Models and Performing Historical Backtesting<\/p>\n<figure class=\"wp-block-image\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1XQlHTmps4Zr6HuRoBFE12A.png\"\/><figcaption class=\"wp-element-caption\">Photo by\u00a0<a href=\"https:\/\/unsplash.com\/@nimisha_mekala\" rel=\"noreferrer noopener\" target=\"_blank\">Nimisha Mekala<\/a>\u00a0on\u00a0<a href=\"https:\/\/unsplash.com\/s\/photos\/finance\" rel=\"noreferrer noopener\" target=\"_blank\">Unsplash<\/a><\/figcaption><\/figure>\n<h2 class=\"wp-block-heading\" id=\"0627\">Highlight<\/h2>\n<p class=\"wp-block-paragraph\" id=\"febe\">Artical Difficulty\uff1a\u2605\u2605\u2605\u2606\u2606<\/p>\n<p class=\"wp-block-paragraph\" id=\"67b2\">Reading Recommendation: This article utilizes an RNN (Recurrent Neural Network) architecture for time series prediction. It is advisable for readers to have a foundational understanding of time series analysis or deep learning. <\/p>\n<h2 class=\"wp-block-heading\" id=\"805b\">Preface<\/h2>\n<p class=\"wp-block-paragraph\" id=\"9eaf\">In the previous article, we used an LSTM model to predict stock price trends by using the past 10 days\u2019 opening prices, highest prices, lowest prices, closing prices, and trading volumes to predict the closing price for the next day. However, we observed that the model\u2019s performance was not very satisfactory when relying solely on yesterday\u2019s stock price to predict tomorrow\u2019s price. Therefore, we have decided to change our approach. This time, we aim to use the model to help us <span class=\"ek-underline\" style=\"text-decoration: underline;\">identify buy and sell points and formulate a trading strategy<\/span>. We have also incorporated more feature indicators, hoping to achieve better results.<\/p>\n<h2 class=\"wp-block-heading\" id=\"4db9\">Characteristic Indicators and Introduction<\/h2>\n<p class=\"wp-block-paragraph\">We have added eight new feature indicators, four of which are technical indicators, and four are macroeconomic indicators, with the hope of enhancing our prediction results using these two facets of feature values.<\/p>\n<h3 class=\"wp-block-heading\">Technical Indicators:<\/h3>\n<p class=\"wp-block-paragraph\">\u25ce<strong>KD (Stochastic Oscillator)<\/strong>: Represents the current price\u2019s relative high-low changes over a specified period, indicating price momentum.<\/p>\n<p class=\"wp-block-paragraph\">\u25ce<strong>RSI (Relative Strength Index)<\/strong>: Measures the strength of price movements, indicating the balance between buying and selling pressures.<\/p>\n<p class=\"wp-block-paragraph\">\u25ce<strong>MACD (Moving Average Convergence Divergence)<\/strong>: Indicates the convergence or divergence of long-term and short-term moving averages, helping identify potential trend changes.<\/p>\n<p class=\"wp-block-paragraph\">\u25ce<strong>MOM (Momentum)<\/strong>: Observes the magnitude of price changes and market trend direction.<\/p>\n<h3 class=\"wp-block-heading\">Macroeconomic Indicators:<\/h3>\n<p class=\"wp-block-paragraph\">\u25ce<strong>Taiwan Economic Composite Index<\/strong>: Represents a crucial macroeconomic variable reflecting economic activity and changes in the business cycle.<\/p>\n<p class=\"wp-block-paragraph\">\u25ce<strong>VIX Index<\/strong>: Reflects market volatility and serves as an indicator of market sentiment and panic.<\/p>\n<p class=\"wp-block-paragraph\">\u25ce<strong>Leading Indicators<\/strong>: Economic indicators that provide early insights into future economic trends, aiding in predicting economic conditions.<\/p>\n<p class=\"wp-block-paragraph\">\u25ce<strong>Taiwan Stock Average P\/E Ratio<\/strong>: Calculates the average P\/E ratio of listed companies, offering insights into overall market sentiment, whether it\u2019s optimistic or pessimistic.<\/p>\n<p class=\"wp-block-paragraph\"><\/p>\n<h2 class=\"wp-block-heading\" id=\"110a\">Editing Environment and Module Requirements<\/h2>\n<p class=\"wp-block-paragraph\" id=\"ee32\">This article is based on the Windows operating system and utilizes Jupyter as the editor.<\/p>\n<pre class=\"wp-block-preformatted\">import tejapi<br\/>import pandas as pd<br\/><br\/>tejapi.ApiConfig.api_key = \"Your Key\"<br\/>tejapi.ApiConfig.ignoretz = True<\/pre>\n<h3 class=\"wp-block-heading\" id=\"39a0\">Database Usage<\/h3>\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">0050 Adjustment of stock price (day) \u2014 ex-dividend adjustment <br\/>Average price-to-earnings ratio of Taiwan stocks \u2013 overall economy<br\/>Taiwan\u2019s Prosperity Countermeasure Signal \u2013 Overall Economy <br\/>Leading Indicators \u2013 General Economy <br\/>Chicago VIX Index \u2014 International Stock Price Index <\/p>\n<\/blockquote>\n<h3 class=\"wp-block-heading\" id=\"0a6b\">Data Loading<\/h3>\n<p class=\"wp-block-paragraph\" id=\"47b4\">The data used includes the ex-dividend and adjusted stock prices, as well as the opening price, closing price, highest price, lowest price, and trading volume for the Taiwan 50 Index (0050) spanning from January 2011 to November 2022.<\/p>\n<pre class=\"wp-block-preformatted\">coid = \"0050\"\nmdate = {'gte':'2011-01-01', 'lte':'2022-11-15'}\ndata = tejapi.get('TWN\/APRCD1',\n                          coid = coid,\n                          mdate = {'gte':'2011-01-01', 'lte':'2022-11-15'},\n                          paginate=True)\n\n\n#Open high, close low, trading volume\ndata = data[[\"coid\",\"mdate\",\"open_adj\",\"high_adj\",\"low_adj\",\"close_adj\",\"amount\"]]\ndata = data.rename(columns={\"coid\":\"coid\",\"mdate\":\"mdate\",\"open_adj\":\"open\",\n                   \"high_adj\":\"high\",\"low_adj\":\"low\",\"close_adj\":\"close\",\"amount\":\"vol\"})<\/pre>\n<p class=\"wp-block-paragraph\" id=\"cd8f\">Besides loading Taiwan 50 Index (0050) adjustment stock price, we also need to consider other indicators in the model, such as Technical indicators(KD\u3001RSI\u3001MACD\u3001MOM) and General economic indicators (Taiwan stock average price-earnings ratio, Taiwan\u2019s business climate countermeasure signal, leading indicators, Chicago VIX index). After eliminating some null values and impractical columns, we could organize the chart below.<\/p>\n<pre class=\"wp-block-preformatted\"><\/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\/135Epj_F7N8hq93CEdzyNTg.png\"\/><figcaption class=\"wp-element-caption\">Data Organization Chart<\/figcaption><\/figure>\n<h3 class=\"wp-block-heading\" id=\"e6ae\">Buy and Sell Signals<\/h3>\n<p class=\"wp-block-paragraph\" id=\"42fd\">We have chosen to define trends by combining moving averages with momentum indicators. A simple criterion for identifying an upward trend is when MA10 &gt; MA20 and RSI10 &gt; RSI20. We labeled an upward trend as 1, otherwise it is marked as 0.<\/p>\n<p class=\"wp-block-paragraph\">Observing the Data Distribution below, we can tell that the data distribution is not overly skewed. Due to the overall upward trend in the market, a higher number of upward trends is a regular occurrence.<\/p>\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\/1YLCkCuQ7TggZqyz1g5JeDQ.png\"\/><figcaption class=\"wp-element-caption\">Data Distribution<\/figcaption><\/figure>\n<div class=\"wp-block-group is-layout-constrained wp-block-group-is-layout-constrained\">\n<h2 class=\"wp-block-heading\" id=\"79bb\">Data Preprocessing and LSTM Model<\/h2>\n<p class=\"wp-block-paragraph\" id=\"02e1\">Before processing, we standardized data by cutting samples into learning and test, whose ratio is 7:3, setting the training data time range as 2011.02.25- 2019.05.08 and the test data time range as 2019.05.09- 2022.11.15. After preparing the data, we reshaped them into three Dimensions to suit the LSTM Model, which includes four layers with Dropout to prevent overfitting. Model Structures can take the figures below as references.<\/p>\n<\/div>\n<pre class=\"wp-block-preformatted\"><\/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\/1zDISKppRDD-I3ItDCy1wnQ.png\"\/><figcaption class=\"wp-element-caption\">Model Structure (Part I)<\/figcaption><\/figure>\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\/1B8kCPFm7dcF3A4awv1u-NQ.png\"\/><figcaption class=\"wp-element-caption\">Model Structure (Part II)<\/figcaption><\/figure>\n<div style=\"border: 1px black; border-style: solid none; text-align: center; border-color: #296580; padding: 24px; margin-top: 24px; margin-bottom: 24px;\">\n<p style=\"margin: 0px; font-size: 24px; font-weight: bold; line-height: 1.5;\">Boost Your Indices universe with TEJ premium Database!<br\/>Build your Quant Data feeds and Transform Insights Into Decisions.<\/p>\n<div style=\"margin-top: 32px;\"><strong><a href=\"\/en\/databank-solution\/economic-data\/\" style=\"border: none; border-radius: 4px; background-color: #296580; color: white; font-size: 20px; width: fit-content; text-decoration: none; padding: 12px 30px 12px 30px;\">TEJ Databank Solutions<\/a><\/strong><\/div>\n<\/div>\n<h2 class=\"wp-block-heading\" id=\"890a\">Model Results (Training Set)<\/h2>\n<p class=\"wp-block-paragraph\" id=\"e06b\">Set the number of epochs to 100. By examining the Model Loss chart, it\u2019s evident that during the training process, the two lines converged, which indicates that the model did not overfit.<\/p>\n<p class=\"wp-block-paragraph\" id=\"bbf4\"><\/p>\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\/1A06Rib6bqwkHIF5es6KSJA.png\"\/><figcaption class=\"wp-element-caption\">Convergence Situation<\/figcaption><\/figure>\n<p class=\"wp-block-paragraph\" id=\"ba28\">In addition, the figure below shows the importance of different feature indicators. It indicates that MACD, Taiwan Stock Average P\/E Ratio, and RSI are essential features in this Model.<\/p>\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\/1qZQCuKbQ-qDbRQNkrCoBYQ.png\"\/><figcaption class=\"wp-element-caption\">Features Importance<\/figcaption><\/figure>\n<h2 class=\"wp-block-heading\" id=\"2ab8\">Model Results (Test Set)<\/h2>\n<p class=\"wp-block-paragraph\" id=\"d82f\">Comparing Real Labels and Model Predictions (Predictions), we found that the test set\u2019s accuracy is as high as 95.49%, indicating that the LSTM model can effectively execute our strategy.<\/p>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1v7h6Ks0EXIYv4oMSf_vcBQ.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"b813\">To better understand the performance, we visualize our strategy in the LSTM Strategy Trend Prediction Chart, where red represents an upward trend, and green represents a downward trend.<\/p>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/14sL-BTuGe6f5pxUyIELLnw.png\"\/><\/figure>\n<h3 class=\"wp-block-heading\" id=\"3cc9\">Strategy Backtesting<\/h3>\n<p class=\"wp-block-paragraph\">Next, we backtested the strategy. When the trend signal is upward, buy one position and hold it. On the other hand, when the trend signal turns downward, sell the original position and take a short one, holding it until the next signal as an upward trend, at which point, close the position. The cumulative return of the LSTM strategy, named \u2018s_return,\u2019 is 82.6%. The actual strategy (MA+MOM) cumulative return, \u2018a_return,\u2019 is 71.3%. The cumulative return for large-cap Buy and Hold, as \u2018m_return,\u2019 is 52%.<br\/>*Note: This strategy does not account for transaction costs; all capital is used for entering and exiting positions.<\/p>\n<p class=\"wp-block-paragraph\">*Note: This strategy does not account for transaction costs, and all capital is used for entering and exiting positions.<\/p>\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\/1TFfntolGIFAmd_zPaKJ22Q.png\"\/><figcaption class=\"wp-element-caption\">Backtesting Result<\/figcaption><\/figure>\n<p class=\"wp-block-paragraph\" id=\"eab9\"><br\/><\/p>\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\/1AfYqnMRvh5p8OPwc5ye-ew.png\"\/><figcaption class=\"wp-element-caption\">Orange: LSTM strategy; Blue: Buy and hold; Green: Actual strategy<\/figcaption><\/figure>\n<h2 class=\"wp-block-heading\" id=\"94a4\">Conclusion<\/h2>\n<p class=\"wp-block-paragraph\">The primary purpose of this study was to examine whether LSTM could accurately identify buy and sell points according to our predefined original strategy.<strong> <mark class=\"has-inline-color has-vivid-green-cyan-color\" style=\"background-color:rgba(0, 0, 0, 0)\">The result was affirmative, with a high accuracy of 95.49% and a cumulative return of 82.6% in backtesting<\/mark>.<\/strong> This performance even outperformed the original strategy and significantly beat the market\u2019s return of 52%. We believe that one reason for outperforming the original strategy is that LSTM generated fewer trading signals during consolidation periods, avoiding the frequent whipsawing that can lead to reduced trading performance.<\/p>\n<p class=\"wp-block-paragraph\">Lastly, we would like to reiterate that the assets mentioned in this article are for illustrative purposes only and do not constitute recommendations or advice regarding any financial products. Therefore, if readers are interested in topics such as strategy development, performance testing, empirical research, etc., you are welcome to explore the solutions available on our website, which provide comprehensive databases and tools for various analyses.<\/p>\n<div class=\"wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button has-custom-width wp-block-button__width-100\"><a class=\"wp-block-button__link has-background has-custom-font-size wp-element-button\" href=\"\/en\/databank-solution\/economic-data\/\" style=\"border-radius:13px;background:linear-gradient(135deg,rgb(233,217,148) 0%,rgb(82,196,165) 50%,rgb(25,111,156) 100%);font-size:23px\"><strong>Boost Your Indices universe with TEJ premium Database!<br\/>Build your Quant Data feeds and Transform Insights Into Decisions.<\/strong><\/a><\/div>\n<\/div>\n<p class=\"wp-block-paragraph\"><\/p>\n<p class=\"wp-block-paragraph\" style=\"font-size:27px\"><strong>Complete Code<\/strong><\/p>\n<ul class=\"wp-block-list\">\n<li><a class=\"ek-link\" href=\"https:\/\/gist.github.com\/tej87681088\/b599c3dc4db9cbd946554226cfdfd513#file-tejapi_python_lstm_strategy-py\" rel=\"noopener\" target=\"_blank\">Click here to <\/a><a class=\"ek-link\" href=\"https:\/\/gist.github.com\/tej87681088\/b599c3dc4db9cbd946554226cfdfd513#file-tejapi_python_lstm_strategy-py\" rel=\"noopener\" target=\"_blank\">Github<\/a><\/li>\n<\/ul>\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-tej-en wp-block-embed-tej-en\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"nxYBKDBtaD\"><a href=\"https:\/\/www.tejwin.com\/en\/insights\/herding-indicators\/\">Herding indicators<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; visibility: hidden;\" title=\"\u201cHerding indicators\u201d \u2014 TEJ\" src=\"https:\/\/www.tejwin.com\/en\/insights\/herding-indicators\/embed\/#?secret=ZMsGyPSzZ5#?secret=nxYBKDBtaD\" data-secret=\"nxYBKDBtaD\" width=\"600\" height=\"338\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-tej-en wp-block-embed-tej-en\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"k34DSKf6BL\"><a href=\"https:\/\/www.tejwin.com\/en\/insights\/monthly-sales-growth-rate-application-strategy\/\">Monthly sales growth rate application strategy<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; visibility: hidden;\" title=\"\u201cMonthly sales growth rate application strategy\u201d \u2014 TEJ\" src=\"https:\/\/www.tejwin.com\/en\/insights\/monthly-sales-growth-rate-application-strategy\/embed\/#?secret=FjGIhogwAC#?secret=k34DSKf6BL\" data-secret=\"k34DSKf6BL\" width=\"600\" height=\"338\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n\n<p class=\"wp-block-paragraph\" style=\"font-size:27px\"><strong>Further Reading<\/strong><\/p>\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-7387b849 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<\/div>\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<\/div>\n<\/div>\n<p class=\"wp-block-paragraph\" style=\"font-size:27px\"><strong>Related Link<\/strong><\/p>\n<ul class=\"wp-block-list\">\n<li><a aria-label=\"TEJ API \u8cc7\u6599\u5eab\u9996\u9801 (opens in a new tab)\" class=\"ek-link\" href=\"https:\/\/api.tej.com.tw\/index.html\" rel=\"noreferrer noopener\" target=\"_blank\">TEJ API Database Homepage<\/a><\/li>\n<li><a class=\"ek-link\" href=\"https:\/\/eshop.tej.com.tw\/E-Shop\/Edata_intro\" rel=\"noopener\" target=\"_blank\">TEJ E-Shop Complete Database Purchase<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>In the previous article, we used an LSTM model to predict stock price trends by using the past 10 days\u2019 opening prices, highest prices, lowest prices, closing prices, and trading volumes to predict the closing price for the next day. However, we observed that the model\u2019s performance was not very satisfactory when relying solely on yesterday\u2019s stock price to predict tomorrow\u2019s price. Therefore, we have decided to change our approach. This time, we aim to use the model to help us identify buy and sell points and formulate a trading strategy. We have also incorporated eight new feature indicators, with four being technical indicators and four being macroeconomic indicators, in the hope of improving our prediction results using these two facets of feature values.<\/p>\n","protected":false},"featured_media":2190,"template":"","tags":[65,70,71,50],"insight_category":[13],"class_list":["post-2191","insight","type-insight","status-publish","has-post-thumbnail","hentry","tag-python","tag-tej-api","tag-quantitative-strategy","tag-market-data","insight_category-quant-research"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/2191","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\/2190"}],"wp:attachment":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media?parent=2191"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/tags?post=2191"},{"taxonomy":"insight_category","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight_category?post=2191"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}