{"id":18192,"date":"2023-09-19T14:00:00","date_gmt":"2023-09-19T06:00:00","guid":{"rendered":"https:\/\/www.tejwin.com\/?post_type=insight&#038;p=18192"},"modified":"2023-09-19T14:21:40","modified_gmt":"2023-09-19T06:21:40","slug":"tquant-lab-price-deviation-ratio-trading-strategy","status":"publish","type":"insight","link":"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/","title":{"rendered":"TQuant Lab Price Deviation Ratio Trading\u00a0Strategy"},"content":{"rendered":"\n<figure class=\"wp-block-image aligncenter caption-align-center\"><img decoding=\"async\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/1_0VPNogsRljnzIEH-A.jpg\" alt=\"\"\/><figcaption class=\"wp-element-caption\">Photo by <a href=\"https:\/\/unsplash.com\/@lxrcbsv?utm_source=medium&amp;utm_medium=referral\" rel=\"noreferrer noopener\" target=\"_blank\">\u0410\u043b\u0435\u043a\u0441 \u0410\u0440\u0446\u0438\u0431\u0430\u0448\u0435\u0432<\/a> on&nbsp;<a href=\"https:\/\/unsplash.com?utm_source=medium&amp;utm_medium=referral\" rel=\"noreferrer noopener\" target=\"_blank\">Unsplash<\/a><\/figcaption><\/figure>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_81 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-69f4c539c3f1e\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"ez-toc-cssicon\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-69f4c539c3f1e\"  aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Highlight\" >Highlight<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Preface\" >Preface<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Trading_Strategy\" >Trading Strategy<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#The_Editing_Environment_and_Module_Required\" >The Editing Environment and Module\u00a0Required<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Data_Import\" >Data Import<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Module_Import\" >Module Import<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Create_Pipeline_function\" >Create Pipeline\u00a0function<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Creating_Initialize_Function\" >Creating Initialize Function<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Create_Handle_data_Function\" >Create Handle_data Function<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Creating_Analyze_Function\" >Creating Analyze\u00a0Function<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Run_Algorithms\" >Run Algorithms<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Performance_Analysis\" >Performance Analysis<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Daily_Returns\" >Daily Returns<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Holding_Positions\" >Holding Positions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Transaction_Record\" >Transaction Record<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Making_Performance_Table\" >Making Performance Table<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Plot_Accumulated_Return_and_Benchmark_Return\" >Plot Accumulated Return and Benchmark Return<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-18\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Conclusion\" >Conclusion<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-19\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Source_Code\" >Source Code<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-20\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Extended_Reading\" >Extended Reading<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-21\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-price-deviation-ratio-trading-strategy\/#Related_Link\" >Related Link<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Highlight\"><\/span>Highlight<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Difficulty: \u2605\u2606\u2606\u2606\u2606<\/li>\n\n\n\n<li>Determining when to long or short stocks with price deviation ratio.<\/li>\n\n\n\n<li>This article is revised from <a href=\"https:\/\/www.tejwin.com\/en\/insight\/price-deviation-ratio-trading-strategy\/\" class=\"ek-link\">Price Deviation Ratio Trading Strategy <\/a>via TQuant Lab.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Preface\"><\/span>Preface<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The Price Deviation Ratio is a common technical indicator that compares the current stock price to the N-day moving average price, reflecting whether the current price is relatively high or low compared to its historical values. Generally, when the stock price consistently exceeds the moving average price, it\u2019s called a \u2018positive deviation.\u2019 Conversely, it\u2019s called\u2019 negative deviation\u2019 when it consistently falls below the moving average price.\u2019 Therefore, when positive or negative deviation expands, it is interpreted as a sustained overbought or oversold condition in the market, serving as a basis for entry and exit decisions. However, using only the Price Deviation Ratio can generate too many trading signals. Hence, we include the highest and lowest prices over the past N days as a second filter. The actual strategy is as follows:<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Trading_Strategy\"><\/span>Trading Strategy<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>When the closing price is higher than the highest price over the past N days, and the Price Deviation Ratio is negative, enter a long position at the next day&#8217;s opening price.<br><br>When the closing price is lower than the lowest price over the past N days, and the Price Deviation Ratio is positive, exit the position and close the trade at the next day&#8217;s opening price.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_Editing_Environment_and_Module_Required\"><\/span>The Editing Environment and Module\u00a0Required<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>This article uses MacOS and employs Jupyter as the editor.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>import os\nimport pandas as pd\nimport numpy as np\nimport tejapi\nimport matplotlib.pyplot as plt<\/code><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Data_Import\"><\/span>Data Import<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The back testing time period is between 2005\/07\/02 to 2023\/07\/02, and we take TSMC(2330) as an example.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>os.environ&#91;'TEJAPI_BASE'] = 'https:\/\/api.tej.com.tw'\nos.environ&#91;'TEJAPI_KEY'] = 'your_key'\nos.environ&#91;'mdate'] = '20050702 20230702'\nos.environ&#91;'ticker'] = '2330'\n!zipline ingest -b tquant<\/code><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Module_Import\"><\/span>Module Import<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code><code>from zipline.api import (set_slippage,<br>set_commission,<br>set_benchmark,<br>attach_pipeline,<br>symbol,<br>pipeline_output,<br>record,<br>order,<br>order_target<br>)<br>from zipline.pipeline.filters import StaticSids<br>from zipline.finance import slippage, commission<br>from zipline import run_algorithm<br>from zipline.pipeline import CustomFactor, Pipeline<br>from zipline.pipeline.data import EquityPricing<br>from zipline.pipeline.factors import ExponentialWeightedMovingAverage<\/code><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_Pipeline_function\"><\/span>Create Pipeline\u00a0function<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Pipeline() enables users to quickly process multiple assets&#8217; trading-related data. In today&#8217;s article, we use it to process:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>EMA of price of the past 7 days<\/li>\n\n\n\n<li>The highest price of the past 7 days(custom factor: <code>NdaysMaxHigh<\/code>)<\/li>\n\n\n\n<li>The lowest price of the past7 days(custom factor: <code>NdaysMinLow<\/code>)<\/li>\n\n\n\n<li>Current close price<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def make_pipeline():\nema = ExponentialWeightedMovingAverage(inputs = &#91;EquityPricing.close],window_length = 7,decay_rate = 1\/7)\nhigh = NdaysMaxHigh(inputs = &#91;EquityPricing.close], window_length = 8) # window_length \u8a2d\u5b9a\u70ba 8\uff0c\u56e0\u70ba factor \u6703\u5305\u542b\u7576\u65e5\u50f9\u683c\u3002\nlow = NdaysMinLow(inputs = &#91;EquityPricing.close], window_length = 8)\nclose = EquityPricing.close.latest\nreturn Pipeline(\ncolumns = {\n'ema':ema,\n'highesthigh':high,\n'lowestlow':low,\n'latest':close\n}\n)\nclass NdaysMaxHigh(CustomFactor):\ndef compute(self, today, assets, out, data):\nout&#91;:] = np.nanmax(data&#91;:-2], axis=0)\nclass NdaysMinLow(CustomFactor):\ndef compute(self, today, assets, out, data):\nout&#91;:] = np.nanmin(data&#91;:-2], axis=0)<\/code><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_Initialize_Function\"><\/span>Creating Initialize Function<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><code>Initialize()<\/code> enables users to set up the trading environment at the beginning of the back test period. In this article, we set up&nbsp;:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Slippage<\/li>\n\n\n\n<li>Commission<\/li>\n\n\n\n<li>Set the return of buying and holding TSMC as the benchmark.<\/li>\n\n\n\n<li>Attach <code>Pipline()<\/code> function into back testing.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def initialize(context):<br>set_slippage(slippage.VolumeShareSlippage())<br>set_commission(commission.PerShare(cost=0.00285))<br>set_benchmark(symbol('2330'))<br>attach_pipeline(make_pipeline(), 'mystrategy')<\/code><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Create_Handle_data_Function\"><\/span>Create Handle_data Function<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><code>handle_data()<\/code> is used to process data and make orders daily.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Condition1: When current close price is greater than the highest price of last 7 days and the bias is greater than 0, we regard it as a selling signal.<\/li>\n\n\n\n<li>Condition2: When current close price is lower than the lowest price of last 7 days and the bias is lower than 0, we regard it as a buying signal.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def handle_data(context, data):\n\npipe = pipeline_output('mystrategy')\n\nfor i in pipe.index:\nema = pipe.loc&#91;i, 'ema']\nhighesthigh = pipe.loc&#91;i, 'highesthigh']\nlowestlow = pipe.loc&#91;i, 'lowestlow']\nclose = pipe.loc&#91;i, 'latest']\nbias = close - ema\nresidual_position = context.portfolio.positions&#91;i].amount # \u7576\u65e5\u8a72\u8cc7\u7522\u7684\u80a1\u6578\ncondition1 = (close &gt; highesthigh) and (bias &gt; 0) and (residual_position &gt; 0) # \u8ce3\u51fa\u8a0a\u865f\ncondition2 = (close &lt; lowestlow) and (bias &lt; 0) # \u8cb7\u5165\u8a0a\u865f\n\nrecord( # \u7528\u4ee5\u7d00\u9304\u4ee5\u4e0b\u8cc7\u8a0a\u81f3\u6700\u7d42\u7522\u51fa\u7684 result \u8868\u683c\u4e2d\ncon1 = condition1,\ncon2 = condition2,\nprice = close,\nema = ema,\nbias = bias,\nhighesthigh = highesthigh,\nlowestlow = lowestlow\n)\n\nif condition1:\norder_target(i, 0)\nelif condition2:\norder(i, 10)\nelse:\npass<\/code><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_Analyze_Function\"><\/span>Creating Analyze\u00a0Function<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Here, we apply <code>matplotlib.pyplot<\/code> for the trading signals and the portfolio value visualization.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def analyze(context, perf):\nfig = plt.figure()\nax1 = fig.add_subplot(211)\nperf.portfolio_value.plot(ax=ax1)\nax1.set_ylabel(\"Portfolio value (NTD)\")\nax2 = fig.add_subplot(212)\nax2.set_ylabel(\"Price (NTD)\")\nperf.price.plot(ax=ax2)\nax2.plot( # \u7e6a\u88fd\u8cb7\u5165\u8a0a\u865f\nperf.index&#91;perf.con2],\nperf.loc&#91;perf.con2, 'price'],\n'^',\nmarkersize=5,\ncolor='red'\n)\nax2.plot( # \u7e6a\u88fd\u8ce3\u51fa\u8a0a\u865f\nperf.index&#91;perf.con1],\nperf.loc&#91;perf.con1, 'price'],\n'v',\nmarkersize=5,\ncolor='green'\n)\nplt.legend(loc=0)\nplt.gcf().set_size_inches(18,8)\nplt.show()<\/code><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Run_Algorithms\"><\/span>Run Algorithms<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>We expliot <code>run_algorithm()<\/code> to execute our strategy. The backtesting time period is set between 2015\u201301\u201306 to 2022\u201311\u201325. The data bundle we use is <em>tquant<\/em>. We assume the initial capital base is 10,000. The output of <code>run_algorithm()<\/code>, which is <em>result<\/em>s, contains information on daily performance and trading receipts.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>results = run_algorithm(start = pd.Timestamp('20150106', tz='UTC'),\nend = pd.Timestamp('20221125', tz='UTC'),\ninitialize=initialize,\nbundle='tquant',\nanalyze=analyze,\ncapital_base=1e4,\nhandle_data = handle_data\n)<\/code><\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image aligncenter caption-align-center\"><img decoding=\"async\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/1_1BJZW8JsdZLV9cBH5qHkgZg.png\" alt=\"Portfolio value and trading time point\"\/><figcaption class=\"wp-element-caption\">Portfolio value and trading time point<\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter is-resized caption-align-center\"><img fetchpriority=\"high\" decoding=\"async\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/1_1EukbHfeuXN7nZmv32_7GVg.png\" alt=\"Trading record\" style=\"width:800px;height:497px\" width=\"800\" height=\"497\"\/><figcaption class=\"wp-element-caption\">Trading record<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Performance_Analysis\"><\/span>Performance Analysis<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Then, we used <code>Pyfolio <\/code>module which came with TQuant Lab to analyze strategy`s performance and risk. First, we use <code>extract_rets_pos_txn_from_zipline()<\/code> to calculate returns, positions, and trading records.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>import pyfolio as pf\nreturns, positions, transactions = pf.utils.extract_rets_pos_txn_from_zipline(results)<\/code><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Daily_Returns\"><\/span>Daily Returns<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Calculating daily portfolio return.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter caption-align-center\"><img decoding=\"async\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/18SpZCxTnYIIjWEOJA5czDg.png\" alt=\"Daily portfolio return\"\/><figcaption class=\"wp-element-caption\">Daily portfolio return<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Holding_Positions\"><\/span>Holding Positions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Equity(0 [2330]): TSMC<\/li>\n\n\n\n<li>Cash<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image aligncenter caption-align-center\"><img decoding=\"async\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/1-tOQkCkIAveGGLb-Zs4Bg.png\" alt=\"Holding position record\"\/><figcaption class=\"wp-element-caption\">Holding position record<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Transaction_Record\"><\/span>Transaction Record<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>sid: index<\/li>\n\n\n\n<li>symbol: ticker symbol<\/li>\n\n\n\n<li>price: buy\/sell price<\/li>\n\n\n\n<li>order_id: order number<\/li>\n\n\n\n<li>amount: trading amount<\/li>\n\n\n\n<li>commission: commission cost<\/li>\n\n\n\n<li>dt: trading date<\/li>\n\n\n\n<li>txn_dollar: trading dollar volume<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image aligncenter caption-align-center\"><img decoding=\"async\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/12Xs75mm7d1eq4eCxXa61DA.png\" alt=\"Trading record\"\/><figcaption class=\"wp-element-caption\">Trading record<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Making_Performance_Table\"><\/span>Making Performance Table<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>With <code>show_perf_stats()<\/code>, one can easily showcase the performance and risk analysis table.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>import pyfolio as pf\npf.plotting.show_perf_stats(\nreturns,\nbenchmark_rets,\npositions=positions,\ntransactions=transactions)<\/code><\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image aligncenter caption-align-center\"><img decoding=\"async\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/1hVzmGySCXlTTed9ve1x9Hw.png\" alt=\"Performance Table\"\/><figcaption class=\"wp-element-caption\">Performance Table<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Plot_Accumulated_Return_and_Benchmark_Return\"><\/span>Plot Accumulated Return and Benchmark Return<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code><code>benchmark_rets = results&#91;'benchmark_return'] \npf.plotting.plot_rolling_returns(returns, factor_returns=benchmark_rets)<\/code><\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image aligncenter caption-align-center\"><img decoding=\"async\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/1BdXv5h4FZ77IB5v6wDfOIw.png\" alt=\"Figure for strategy returns\"\/><figcaption class=\"wp-element-caption\">Figure for strategy returns<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The strategy introduced in this session is one of the mean-reversion trading strategies. When the market is oversold (Bullish Divergence, BDI &lt; 0), and the closing price is higher than the highest price over a certain period, it\u2019s assumed that the stock price will gradually return to the moving average price, so a long position is entered. Conversely, when the stock price is overbought (Bearish Divergence, BDI > 0), and the closing price is lower than the lowest price over a certain period, it\u2019s believed that the stock price has risen too much and has a downward trend. In this case, the long position is exited. However, it\u2019s important to note that this strategy involves frequent trading, which transaction costs and taxes can erode. Therefore, it\u2019s recommended to combine other technical indicators to optimize entry and exit points.<\/p>\n\n\n\n<p>Finally, it\u2019s worth mentioning again that the stocks discussed in this article are for illustrative purposes only and do not constitute recommendations for any financial products. If readers are interested in topics such as building strategies, performance backtesting, and empirical research, you are welcome to purchase solutions from TEJ E-Shop, which provides comprehensive databases to easily perform various tests and analyses.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Source_Code\"><\/span>Source Code<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/gist.github.com\/tej87681088\/04f7c31fa6d32fa3d04a149f492ff69d\" class=\"ek-link\" target=\"_blank\" rel=\"noopener\">Click here to go Github<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Extended_Reading\"><\/span>Extended Reading<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-bollinger-bands-trading-strategy\/\" class=\"ek-link\">TQuant Lab Bollinger Bands Trading Strategy<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-rookie-manual\/\" class=\"ek-link\">TQuant Lab Rookie Manual<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Related_Link\"><\/span>Related Link<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\" target=\"_blank\" rel=\"noreferrer noopener\">TQuant Lab Github<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>The Price Deviation Ratio is a common technical indicator that compares the current stock price to the N-day moving average price, reflecting whether the current price is relatively high or low compared to its historical values. Generally, when the stock price consistently exceeds the moving average price, it\u2019s called a \u2018positive deviation.\u2019 Conversely, it\u2019s called\u2019 negative deviation\u2019 when it consistently falls below the moving average price.\u2019 Therefore, when positive or negative deviation expands, it is interpreted as a sustained overbought or oversold condition in the market, serving as a basis for entry and exit decisions. However, using only the Price Deviation Ratio can generate too many trading signals. Hence, we include the highest and lowest prices over the past N days as a second filter. The actual strategy is as follows:<\/p>\n","protected":false},"featured_media":18180,"template":"","tags":[2989,2388,2428,2537],"insight-category":[690,885],"class_list":["post-18192","insight","type-insight","status-publish","has-post-thumbnail","hentry","tag-quantitive-analysis","tag-tquant-lab","tag-2428","tag-2537","insight-category-data-analysis","insight-category-tquant-lab"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/18192","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"}],"version-history":[{"count":1,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/18192\/revisions"}],"predecessor-version":[{"id":18194,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/18192\/revisions\/18194"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media\/18180"}],"wp:attachment":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media?parent=18192"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/tags?post=18192"},{"taxonomy":"insight-category","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight-category?post=18192"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}