{"id":1774,"date":"2023-10-24T14:30:00","date_gmt":"2023-10-24T14:30:00","guid":{"rendered":"https:\/\/www.tejwin.com\/en\/insights\/tquant-lab-aroon-up-down\/"},"modified":"2023-10-24T14:30:00","modified_gmt":"2023-10-24T14:30:00","slug":"tquant-lab-aroon-up-down","status":"publish","type":"insight","link":"https:\/\/www.tejwin.com\/en\/insights\/tquant-lab-aroon-up-down\/","title":{"rendered":"TQuant Lab Aroon Up Down Trading\u00a0Strategy"},"content":{"rendered":"<figure class=\"wp-block-image aligncenter caption-align-center\"><img decoding=\"async\" alt=\"TQuant Lab Aroon Up Down Trading\u00a0Strategy\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/0pa4diVBrvZL8vdLm.jpg\"\/><figcaption class=\"wp-element-caption\">Photo by <a href=\"https:\/\/unsplash.com\/@vladizlo?utm_source=medium&amp;utm_medium=referral\" rel=\"noreferrer noopener\" target=\"_blank\">Vlad Zaytsev<\/a> on\u00a0<a href=\"https:\/\/unsplash.com?utm_source=medium&amp;utm_medium=referral\" rel=\"noreferrer noopener\" target=\"_blank\">Unsplash<\/a><\/figcaption><\/figure>\n<h2 class=\"wp-block-heading\">Highlight<\/h2>\n<ul class=\"wp-block-list\">\n<li>Difficulty: \u2605\u2606\u2606\u2606\u2606<\/li>\n<li>Using Aroon-up\u3001Arron-down as indicators to trigger the action of buy and sell.<\/li>\n<li>This article is revised from Aroon Up Down Strategy via TQuant Lab.<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\">Perface<\/h2>\n<p class=\"wp-block-paragraph\">Aroon Indicator, developed by Tushar Chande in 1995, is typically for measuring market tendency. It consists of two lines\u200a-\u200aAroon Up and Aroon Down.<\/p>\n<ul class=\"wp-block-list\">\n<li>Aroon Up\uff1a((Number of periods\u200a-\u200aNumber of periods since highest high) \/ Number of periods) * 100<\/li>\n<li>This indicator measures the periods since the highest price (high point) occurred within the selected period.<\/li>\n<li>Aroon Down\uff1a((Number of periods\u200a-\u200aNumber of periods since lowest low) \/ Number of periods) * 100<\/li>\n<li>This indicator measures the periods since the lowest price (low point) occurred within the selected period.<\/li>\n<\/ul>\n<p class=\"wp-block-paragraph\">The Aroon Up indicator measures the strength and time since the highest price within a given period (usually 25 periods). In contrast, the Aroon Down indicator measures the strength and time since the lowest price within the same period. These indicators are expressed as percentages and range from 0% to 100%.<\/p>\n<p class=\"wp-block-paragraph\">The crossover of the Aroon Up and Aroon Down lines can be used to signal potential changes in trend direction. For example, when Aroon Up crosses above Aroon Down, it might be seen as a bullish signal, indicating a potential shift towards an upward trend. Conversely, when Aroon Down crosses above Aroon Up, it could be interpreted as a bearish signal, suggesting a potential shift towards a downward trend.<\/p>\n<h2 class=\"wp-block-heading\">Aroon Up Down Trading Strategy<\/h2>\n<p class=\"wp-block-paragraph\">When Aroon Up is greater than 80 and Aroon Down is lesser than 45, which represents a bullish trend. We consider it a buying signal and will acquire one unit at tomorrow\u2019s opening price.<\/p>\n<p class=\"wp-block-paragraph\">When Aroon Up is lesser than 45, Aroon Down is greater than 55, and the gap of two indicators is greater than 15, we regard it as a selling signal and sell the holding position at tomorrow\u2019s opening price.<\/p>\n<p class=\"wp-block-paragraph\">When Aroon Up is greater than 55, Aroon Down is lesser 45, the gap between the two indicators is greater than 15, our invested amount isn\u2019t greater than 20% principal, and we still have plentiful cash. We will acquire one more unit at tomorrow\u2019s opening price.<\/p>\n<h2 class=\"wp-block-heading\">Programming environment and Module\u00a0required<\/h2>\n<p class=\"wp-block-paragraph\">MacOS and Jupyter Notebook is used as editor<\/p>\n<h2 class=\"wp-block-heading\">Data and Module\u00a0Import<\/h2>\n<p class=\"wp-block-paragraph\">The back testing time period is between 2018\/01\/01 to 2020\/12\/31, and we take Hon Hai Precision Industry(2317), Compal Electronics(2324), Yageo Corporation(2327), TSMC(2330), Synnex(2347), Acer(2353), FTC(2354), ASUS(2357)\u3001Realtek(2379), Quanta(2382), and Advantech(2395) to construct the portfolio and compare the performance of portfolio with the benchmark\u2013 Total. Return Index(IR0001),\u00a0.<\/p>\n<pre class=\"wp-block-code\"><code><code>import os\nimport pandas as pd\nimport numpy as np\nimport tejapios.environ['TEJAPI_KEY'] = 'Your key'\nos.environ['mdate'] = '20180101 20201231'\nos.environ['ticker'] = 'IR0001 2317 2324 2327 2330 2347 2353 2354 2357 2379 2382 2395'!zipline ingest -b tquantfrom zipline.api import set_slippage, set_commission, set_benchmark, attach_pipeline, order, order_target, symbol, pipeline_output, record\nfrom zipline.finance import commission, slippage\nfrom zipline.data import bundles\nfrom zipline import run_algorithm\nfrom zipline.pipeline import Pipeline, CustomFactor\nfrom zipline.pipeline.filters import StaticAssets, StaticSids\nfrom zipline.pipeline.factors import BollingerBands, Aroon\nfrom zipline.pipeline.data import EquityPricing\nfrom zipline.pipeline.mixins import LatestMixin\nfrom zipline.master import run_pipeline<\/code><\/code><\/pre>\n<h2 class=\"wp-block-heading\">Setting Benchmark<\/h2>\n<p class=\"wp-block-paragraph\">First, We load the bundle which we just ingest above, and set return index(coid\u00a0: IR0001) as benchmark.<\/p>\n<pre class=\"wp-block-code\"><code><code>bundle = bundles.load('tquant')\nir0001_asset = bundle.asset_finder.lookup_symbol('IR0001',as_of_date = None)<\/code><\/code><\/pre>\n<h2 class=\"wp-block-heading\">Create Pipeline\u00a0function<\/h2>\n<p class=\"wp-block-paragraph\">Pipeline() enables users to quickly process multiple assets\u2019 trading-related data. In today\u2019s article, we use it to process:<\/p>\n<p class=\"wp-block-paragraph\">The calculation of Aroon-up, Aroon-down (built-in factor:<code>Aroon<\/code>)<\/p>\n<pre class=\"wp-block-code\"><code><code>def make_pipeline():<br\/>curr_price = EquityPricing.close.latest<br\/><br\/>alroon = Aroon(inputs = [EquityPricing.low, EquityPricing.high], window_length=25, mask = curr_price &lt; 5000)<br\/>up, down = alroon.up, alroon.down return Pipeline(<br\/>columns = {<br\/>'up': up,<br\/>'down': down,<br\/>'curr_price': curr_price, },<br\/>screen = ~StaticAssets([ir0001_asset])<br\/>)<\/code><\/code><\/pre>\n<h2 class=\"wp-block-heading\">Creating Initialize Function<\/h2>\n<p class=\"wp-block-paragraph\">inintialize enables users to set up the trading environment at the beginning of the back test period. In this article, we set up:<\/p>\n<ul class=\"wp-block-list\">\n<li>Slippage<\/li>\n<li>Commission<\/li>\n<li>Set the return index as the benchmark.<\/li>\n<li>Attach Pipline() function into back testing.<\/li>\n<\/ul>\n<pre class=\"wp-block-code\"><code><code>def initialize(context):\nset_slippage(slippage.VolumeShareSlippage())\nset_commission(commission.PerShare(cost=0.00285))\nset_benchmark(symbol('IR0001'))\nattach_pipeline(make_pipeline(), 'mystrategy')<\/code><\/code><\/pre>\n<h2 class=\"wp-block-heading\">Creating handle_date Function<\/h2>\n<p class=\"wp-block-paragraph\">handle_data is used to process data and make orders daily.<\/p>\n<p class=\"wp-block-paragraph\">Default trading signals buy and sell are False<\/p>\n<ul class=\"wp-block-list\">\n<li><code>buy<\/code>: When today\u2019s indicators matches the buy-in condition, generates buying signal and toggles the boolean value to <em>True<\/em>\u3002<\/li>\n<li><code>sell<\/code>: When today\u2019s indicators matches the sell-out condition, generates selling signal and toggles the boolean value to <em>True<\/em>\u3002<\/li>\n<\/ul>\n<pre class=\"wp-block-code\"><code><code>def handle_data(context, data):<br\/>out_dir = pipeline_output('mystrategy')<br\/>for i in out_dir.index:<br\/>sym = i.symbol # \u6a19\u7684\u4ee3\u78bc<br\/>up = out_dir.loc[i, 'up']<br\/>down = out_dir.loc[i, 'down']<br\/>curr_price = out_dir.loc[i, 'curr_price'] cash_position = context.portfolio.cash<br\/>stock_position = context.portfolio.positions[i].amount buy, sell = False, False record(<br\/>**{<br\/>f'price_{sym}':curr_price,<br\/>f'up_{sym}':up,<br\/>f'down_{sym}':down,<br\/>f'buy_{sym}':buy,<br\/>f'sell_{sym}':sell<br\/>}<br\/>) if stock_position == 0:<br\/>if down &lt; 45 and up &gt; 80:<br\/>order(i, 1000)<br\/>context.last_signal_price = curr_price<br\/>buy = True<br\/>record(<br\/>**{<br\/>f'buy_{sym}':buy<br\/>}<br\/>) elif stock_position &gt; 0:<br\/>if (up - down) &gt; 15 and (down &lt; 45) and (up &gt; 55) and (cash_position &gt;= curr_price * 1000):<br\/>order(i, 1000)<br\/>context.last_signal_price = curr_price<br\/>buy = True<br\/>record(<br\/>#globals()[f'buy_{sym}'] = buy<br\/>**{<br\/>f'buy_{sym}':buy<br\/>}<br\/>) elif (down - up &gt; 15) and (down &gt; 55) and (up &lt; 45):<br\/>order_target(i, 0)<br\/>context.last_signal_price = 0<br\/>sell = True<br\/>record(<br\/>**{<br\/>f'sell_{sym}':sell<br\/>}<br\/>)<br\/>else:<br\/>pass<br\/>else:<br\/>pass<\/code><\/code><\/pre>\n<h2 class=\"wp-block-heading\">Creating Analyze\u00a0Function<\/h2>\n<p class=\"wp-block-paragraph\">analyzefunction is mostly used to visualize the result of backtesting. Since today\u2019s practice will use pyfolio to achieve visualization, we just leave it empty.<\/p>\n<pre class=\"wp-block-code\"><code><code>def analyze(context, perf):<br\/>pass<\/code><\/code><\/pre>\n<h2 class=\"wp-block-heading\">Run Algorithms<\/h2>\n<p class=\"wp-block-paragraph\">We expliot run_algorithm() to execute our strategy. The backtesting time period is set between 2018-01-01 to 2020\u201312\u201331. The data bundle we use is tquant. We assume the initial capital base is 1,000,000. The output of run_algorithm(), which is results, contains information on daily performance and trading receipts.<\/p>\n<pre class=\"wp-block-preformatted\"><code>results = run_algorithm(\nstart = pd.Timestamp('2018-01-01', tz='UTC'),\nend = pd.Timestamp('2020-12-31', tz ='UTC'),\ninitialize=initialize,\nbundle='tquant',\nanalyze=analyze,\ncapital_base=10e6,\nhandle_data = handle_data\n)\nresults<\/code>\n<\/pre>\n<figure class=\"wp-block-image aligncenter size-full is-resized caption-align-center\"><img loading=\"lazy\" decoding=\"async\" alt=\"Transactions record\" class=\"wp-image-18797\" height=\"655\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/image-319.png\" style=\"aspect-ratio:1.2351145038167939;width:809px;height:auto\" width=\"809\"\/><figcaption class=\"wp-element-caption\">Transactions record<\/figcaption><\/figure>\n<h2 class=\"wp-block-heading\">Visualization<\/h2>\n<p class=\"wp-block-paragraph\">Before process visualization, we need to seperate the data of results to three part:<\/p>\n<ul class=\"wp-block-list\">\n<li>returns<\/li>\n<li>positions<\/li>\n<li>transactions<\/li>\n<\/ul>\n<pre class=\"wp-block-code\"><code><code>from pyfolio.utils import extract_rets_pos_txn_from_zipline\nreturns, positions, transactions = extract_rets_pos_txn_from_zipline(results)# \u6642\u5340\u6a19\u6e96\u5316\nreturns.index = returns.index.tz_localize(None).tz_localize('UTC')\npositions.index = positions.index.tz_localize(None).tz_localize('UTC')\ntransactions.index = transactions.index.tz_localize(None).tz_localize('UTC')\nbenchmark_rets.index = benchmark_rets.index.tz_localize(None).tz_localize('UTC')<\/code><\/code><\/pre>\n<p class=\"wp-block-paragraph\">Lastly, pyfolio.tears.create_full_tear_sheet can generate multiple tables and charts to help you evaluate the portfolio\u2019s performance.<\/p>\n<pre class=\"wp-block-code\"><code><code>pyfolio.tears.create_full_tear_sheet(returns=returns,\npositions=positions,\ntransactions=transactions,\nbenchmark_rets=benchmark_rets)<\/code><\/code><\/pre>\n<h2 class=\"wp-block-heading\">Source Code<\/h2>\n<ul class=\"wp-block-list\">\n<li><a class=\"ek-link\" href=\"https:\/\/gist.github.com\/tej87681088\/f6a3132a1fb031a3e469a06c4497e38b\" rel=\"noopener\" target=\"_blank\">Github<\/a><\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n<p class=\"wp-block-paragraph\">In this implementation, we have utilized TQuant Lab to implement the Aron indicator trading strategy. Compared to writing the code without using TQuant Lab, the program\u2019s complexity has significantly decreased, and it offers more detailed parameter settings and evaluation metrics.<\/p>\n<p class=\"wp-block-paragraph\">A friendly reminder that this strategy and the underlying assets are for reference purposes only and do not constitute any recommendations for commodities or investments. In the future, we will also introduce the use of the TEJ database to construct various indicators and backtest their performance. Therefore, we welcome readers interested in various trading backtesting to choose TEJ <a class=\"ek-link\" href=\"https:\/\/eshop.tej.com.tw\/E-Shop\/index\" rel=\"noopener\" target=\"_blank\">E-Shop\u2019s<\/a> relevant solutions and use high-quality databases to create their own trading strategies.<\/p>\n<h2 class=\"wp-block-heading\">Extended Reading<\/h2>\n<ul class=\"wp-block-list\">\n<li><a class=\"ek-link\" href=\"\/en\/insight\/tquant-lab-momentum-trade\/\">TQuant Lab Momentum Trade<\/a><\/li>\n<li><a class=\"ek-link\" href=\"\/en\/insight\/tquant-lab-aroon-up-down\/\">Aroon Up Down\u00a0Strategy<\/a><\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\">Related Links<\/h2>\n<ul class=\"wp-block-list\">\n<li><a class=\"ek-link\" href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\" rel=\"noreferrer noopener\" target=\"_blank\">TQuant Lab Github<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Aroon Indicator, developed by Tushar Chande in 1995, is typically for measuring market tendency. It consists of two lines\u200a-\u200aAroon Up and Aroon Down.<\/p>\n","protected":false},"featured_media":1773,"template":"","tags":[65,70],"insight_category":[16],"class_list":["post-1774","insight","type-insight","status-publish","has-post-thumbnail","hentry","tag-python","tag-tej-api","insight_category-quant-data-science"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/1774","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\/1773"}],"wp:attachment":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media?parent=1774"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/tags?post=1774"},{"taxonomy":"insight_category","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight_category?post=1774"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}