{"id":2382,"date":"2022-02-22T02:32:59","date_gmt":"2022-02-22T02:32:59","guid":{"rendered":"https:\/\/www.tejwin.com\/en\/insights\/momentum-trade\/"},"modified":"2022-02-22T02:32:59","modified_gmt":"2022-02-22T02:32:59","slug":"momentum-trade","status":"publish","type":"insight","link":"https:\/\/www.tejwin.com\/en\/insights\/momentum-trade\/","title":{"rendered":"Momentum trade"},"content":{"rendered":"<p class=\"wp-block-paragraph\" id=\"52f6\">use volume indicator to backtesting , using 2618<\/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\/1_1NnQgBB4jBN4doLrwAtBwKg.jpg\"\/><figcaption class=\"wp-element-caption\">photo by\u00a0<a href=\"https:\/\/unsplash.com\/@leio\" rel=\"noreferrer noopener\" target=\"_blank\">Leio McLaren<\/a>\u00a0on\u00a0<a href=\"https:\/\/unsplash.com\/\" rel=\"noreferrer noopener\" target=\"_blank\">Unsplash<\/a><\/figcaption><\/figure>\n<h2 class=\"wp-block-heading\" id=\"69f0\"><strong>Highlights<\/strong><\/h2>\n<ul class=\"wp-block-list\">\n<li>Difficulty\uff1a\u2605\u2605\u2606\u2606\u2606<\/li>\n<li>Backtesting by trading volume indicator and relative performance of this strategy<\/li>\n<li>Advice: This article adopts TEJ database to calculate RSI 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-2-technical-analysis-2958435a8922\" rel=\"noopener\" target=\"_blank\">\u3010Quant(2)\u3011Technical Analysis<\/a>\u00a0is recommended to explore to better understand the basic procedure of backtesting.<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"ccaf\"><strong>Preface<\/strong><\/h2>\n<p class=\"wp-block-paragraph\" id=\"4e03\">Nowadays Momentum trade are frequently used to trade strategy,we often talk about the price-volume relationship .So in this article we are going to talk about this strategy which based on abnormal growing of the trading volume.but this strategy doesn\u2019t have the clear definition.so we write the function more flexible.you can change the parameter by yourself ! Following is the way to our set the parameter :<\/p>\n<p class=\"wp-block-paragraph\" id=\"8b15\">1. buy-signal : when the trading volume is 2.5 times more than the average of previous 4 days.<\/p>\n<p class=\"wp-block-paragraph\" id=\"50a8\">2. sell-singal : when the trading volume is 0.75 times less than the average of last 4 days.<\/p>\n<h2 class=\"wp-block-heading\" id=\"cf10\"><strong>The Editing Environment and Modules Required<\/strong><\/h2>\n<p class=\"wp-block-paragraph\" id=\"dfe7\">Window10 Spyder(anaconda31)<\/p>\n<pre class=\"wp-block-preformatted\">##########<br\/>import pandas as pd<br\/>import matplotlib.pyplot as plt<br\/>import numpy as np<br\/>#################TEJ<br\/>import tejapi<br\/>tejapi.ApiConfig.api_key = 'Your Key'<br\/>tejapi.ApiConfig.ignoretz = True<\/pre>\n<h2 class=\"wp-block-heading\" id=\"0efe\"><strong>Database<\/strong><\/h2>\n<p class=\"wp-block-paragraph\" id=\"ffc5\"><a href=\"https:\/\/api.tej.com.tw\/columndoc.html?subId=42\" rel=\"noreferrer noopener\" target=\"_blank\">Security Transaction Data Table<\/a>\uff1aListed securities with unadjusted price and index. Code is \u2018TWN\/EWPRCD\u2019.<\/p>\n<h2 class=\"wp-block-heading\" id=\"d602\"><strong>Data Selection<\/strong><\/h2>\n<pre class=\"wp-block-preformatted\">coid=\"2618\" #### you can replace the stock id what you want<br\/>start=\"2018-01-01\" ### time~<br\/>end= \"2022-03-2\"  ### endopts={'columns': ['coid', 'mdate', 'volume', 'close_adj','close_d','open_d']}  ###<br\/>#############<br\/>fly=tejapi.get('TWN\/EWPRCD',coid=coid, <br\/>                mdate={'gt':start,'lt':end},<br\/>                paginate=True,<br\/>                chinese_column_name=True,<br\/>                opts=opts )<\/pre>\n<p class=\"wp-block-paragraph\" id=\"7963\">we using the popular groups in recent days to demonstrate our code .Time we select is 2018\/1\/1~ 2022~3\/2.After we get the data ,we want to plot the data.<\/p>\n<pre class=\"wp-block-preformatted\">fly.set_index(\"\u65e5\u671f\",drop=True,inplace=True) # set index<br\/>plt.figure(facecolor='white',figsize=(12,8))<br\/>plt.plot(fly['\u6536\u76e4\u50f9'], label='\u6536\u76e4\u50f9')<br\/>plt.title(\"\u98db\u6a5f\u8d77\u98db\u8868\",fontsize=25)<br\/>plt.xticks(rotation=45)<br\/>plt.xlabel('\u65e5\u671f',fontsize=25)<br\/>plt.ylabel('\u80a1\u50f9',fontsize=25)<br\/>plt.grid()<br\/>plt.show()<\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/12v7L_pKtmkynU49usWlgIw.png\"\/><\/figure>\n<h2 class=\"wp-block-heading\" id=\"b6d8\"><strong>Data Processing<\/strong><\/h2>\n<p class=\"wp-block-paragraph\" id=\"4932\"><strong>Step 1. set the indicator<\/strong><\/p>\n<pre class=\"wp-block-preformatted\">def voltrade(df,p,q,r):<br\/>    df =df.copy()<br\/>    df[\"\u7576\u65e5\u4ea4\u6613\u91cf\"]=df[\"\u6210\u4ea4\u91cf(\u5343\u80a1)\"].rolling(p).mean() <br\/>    df[\"\u524d\u4e94\u65e5\u7e3d\u91cf\"]=df[\"\u6210\u4ea4\u91cf(\u5343\u80a1)\"].rolling(q).sum()<br\/>    df[str(r)+\"\u65e5\u5747\u7dda\"]=df[\"\u6536\u76e4\u50f9-\u9664\u6b0a\u606f\"].rolling(r).mean()<br\/>    ####\u6263\u9664\u6389\u7576\u65e5\u4e4b\u5e73\u5747<br\/>    df[\"\u524d\u5e7e\u65e5\u5e73\u5747\"]=(df[\"\u524d\u4e94\u65e5\u7e3d\u91cf\"]-df[\"\u7576\u65e5\u4ea4\u6613\u91cf\"])\/(q-p)<br\/>    <br\/>    return df<\/pre>\n<p class=\"wp-block-paragraph\" id=\"6eeb\">This function we can get previous 4(q) days average tradeing volume ,and the 5(r)ma ( we can change the q r)<\/p>\n<pre class=\"wp-block-preformatted\">r=5<br\/>stock=voltrade(fly, 1, 5, r) # the parameter is which we set in this articlestock<\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1_1Tho8IDMxDLNC46M2CTdw6g.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"291d\"><strong>Step 2 find the buy singal and sell singal<\/strong><\/p>\n<pre class=\"wp-block-preformatted\">def buysell(company,a,b):<br\/>    company =company.copy()<br\/>    buy=[]<br\/>    sell=[]<br\/>    hold=0<br\/>    for i in range(len(company)):<br\/>    <br\/>        if  company[\"\u7576\u65e5\u4ea4\u6613\u91cf\"][i] &gt; company[\"\u524d\u5e7e\u65e5\u5e73\u5747\"][i]*a :<br\/>            sell.append(np.nan)<br\/>            if hold !=1:<br\/>                buy.append(company[\"\u6536\u76e4\u50f9-\u9664\u6b0a\u606f\"][i])<br\/>                <br\/>                hold = 1<br\/>            else: <br\/>                buy.append(np.nan)elif company[\"\u7576\u65e5\u4ea4\u6613\u91cf\"][i]&lt;company[\"\u524d\u5e7e\u65e5\u5e73\u5747\"][i]*b :<br\/>            buy.append(np.nan)<br\/>            if hold !=0:<br\/>                sell.append(company[\"\u6536\u76e4\u50f9-\u9664\u6b0a\u606f\"][i])<br\/>                hold = 0<br\/>            else:<br\/>                sell.append(np.nan)<br\/>        else:<br\/>            buy.append(np.nan)<br\/>            sell.append(np.nan)<br\/>    a=(buy,sell)<br\/>        <br\/>    company['Buy_Signal_Price']=a[0]<br\/>    company['Sell_Signal_Price']=a[1]<br\/>    company[\"\u8cb7\u8ce3\u80a1\u65781\"]=company['Buy_Signal_Price'].apply(lambda x : 1000 if x &gt;0 else 0)<br\/>    company[\"\u8cb7\u8ce3\u80a1\u65782\"]=company['Sell_Signal_Price'].apply(lambda x : -1000 if x &gt;0 else 0  )<br\/>    company[\"\u8cb7\u8ce3\u80a1\u6578\"]=company[\"\u8cb7\u8ce3\u80a1\u65781\"]+ company[\"\u8cb7\u8ce3\u80a1\u65782\"]<br\/>    <br\/>    return companyvol=buysell(stock,2.5,0.75)<br\/>plot(vol)<\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1V7xm6Rc2uApxcR0fw2xZNg.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"b571\">In this stargey ,we have done too much buying and selling which incrase frictional cost.and found that we often sell to early.Therefore we try to increase more restriction like the 5ma stargey,here is the following :<\/p>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1H8iu5WVt_FlPCuTKXoKhCg.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"cd54\">casue we are talking about the indicator ,so we plot it together .<\/p>\n<pre class=\"wp-block-preformatted\">pvtwo(volma) #seprate <br\/>pvsame(volma)#combine <\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1saL6uM9TYFsKwnzKrbGKog.png\"\/><\/figure>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1fNklArHEBbWBKJFQQO3ZeQ.png\"\/><\/figure>\n<h2 class=\"wp-block-heading\" id=\"501f\"><strong>Calculate the return<\/strong><\/h2>\n<p class=\"wp-block-paragraph\" id=\"b4af\">In<a class=\"ek-link\" href=\"https:\/\/medium.com\/tej-api-%E9%87%91%E8%9E%8D%E8%B3%87%E6%96%99%E5%88%86%E6%9E%90\/quant-8-backtesting-by-macd-indicator-f0dc6ceecef2\" rel=\"noopener\" target=\"_blank\"> <\/a><a class=\"ek-link\" href=\"\/en\/insight\/backtesting-by-macd-indicator\/\">Backtesting 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\">def target_return(data, principal):<br\/>    data=data.copy()<br\/>    #\u8a08\u7b97\u6210\u672c<br\/>    data['\u624b\u7e8c\u8cbb'] = data['\u6536\u76e4\u50f9-\u9664\u6b0a\u606f']* abs(data['\u8cb7\u8ce3\u80a1\u6578'])*0.001425<br\/>    data['\u624b\u7e8c\u8cbb'] = np.where((data['\u624b\u7e8c\u8cbb']&gt;0)&amp;(data['\u624b\u7e8c\u8cbb'] &lt;20), 20, data['\u624b\u7e8c\u8cbb'])<br\/>    data['\u8b49\u4ea4\u7a05'] = np.where(data['\u8cb7\u8ce3\u80a1\u6578']&lt;0, data['\u6536\u76e4\u50f9-\u9664\u6b0a\u606f']* abs(data['\u8cb7\u8ce3\u80a1\u6578'])*0.003, 0)<br\/>    data['\u6469\u64e6\u6210\u672c'] = (data['\u624b\u7e8c\u8cbb'] + data['\u8b49\u4ea4\u7a05']).apply(np.floor)<br\/>    <br\/>    #\u8a08\u7b97\u8cc7\u7522\u50f9\u503c<br\/>    data['\u80a1\u7968\u50f9\u503c'] = data['\u8cb7\u8ce3\u80a1\u6578'].cumsum() * data['\u6536\u76e4\u50f9-\u9664\u6b0a\u606f']<br\/>    data['\u73fe\u91d1\u50f9\u503c'] = principal - data['\u6469\u64e6\u6210\u672c'] + (data['\u6536\u76e4\u50f9-\u9664\u6b0a\u606f']* -data['\u8cb7\u8ce3\u80a1\u6578']).cumsum() <br\/>    data['\u8cc7\u7522\u50f9\u503c'] = data['\u80a1\u7968\u50f9\u503c'] + data['\u73fe\u91d1\u50f9\u503c']<br\/>    <br\/>    #\u8a08\u7b97\u5831\u916c\u7387<br\/>    data['\u7576\u65e5\u50f9\u503c\u8b8a\u52d5(%)'] = (data['\u8cc7\u7522\u50f9\u503c']\/data['\u8cc7\u7522\u50f9\u503c'].shift(1) - 1)*100<br\/>    data['\u7d2f\u8a08\u5831\u916c(%)'] = (data['\u8cc7\u7522\u50f9\u503c']\/principal - 1)*100<br\/>    <br\/>    return data<\/pre>\n<p class=\"wp-block-paragraph\" id=\"bc9b\">We only consider the trading of common stock. There is no margin buy or margin sell situation, so we do not have to calculate premium. With the data containing trading shares and initial principal, we can quickly get the transaction costs and return. In this article, we set 16000 as our principal.<\/p>\n<pre class=\"wp-block-preformatted\">volreturn1 = target_return( volma, principal = 16000)##with ma<br\/>volreturn2 = target_return( vol, principal = 16000)##without ma <\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1_1io2RuB_HYfgzfPgCN_YTQw.png\"\/><\/figure>\n<pre class=\"wp-block-preformatted\">we add buy-and-hold strategy as our benchmarks.<\/pre>\n<ul class=\"wp-block-list\">\n<li>The return of buy-and-hold<\/li>\n<\/ul>\n<pre class=\"wp-block-preformatted\">keep=vol.copy()<br\/>keep[\"\u8cb7\u8ce3\u80a1\u6578\"]=0<br\/>keep[\"\u8cb7\u8ce3\u80a1\u6578\"][0]=1000<br\/>keep[\"\u8cb7\u8ce3\u80a1\u6578\"][len(keep)-1]=-1000<br\/>volreturn3 = target_return( keep, principal = 16000)<\/pre>\n<h2 class=\"wp-block-heading\" id=\"6083\"><strong>Performance comparison<\/strong><\/h2>\n<p class=\"wp-block-paragraph\" id=\"0ac5\"><strong>Step 1. Comparison of cumulative return (See the details in source code)<\/strong><\/p>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1B7N_8Ct9PTNKEXNMt8Znkg.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"58d6\"><strong>Step 2. Performance table (See the details in source code)<\/strong><\/p>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1b8s_wifSBplmXAkn3cP-ew.png\"\/><\/figure>\n<h2 class=\"wp-block-heading\" id=\"ad22\"><strong>Conclusion<\/strong><\/h2>\n<p class=\"wp-block-paragraph\" id=\"3f48\">We found that if we only use trading volume as the only indicator\uff0cthe performace will equal to the buy&amp;hold,but when we add the ma,we found that the performace is 2 times than the others ,and the sharp ratio is the highest.But this method also has obvious disadvantages .when we look at the 2018 ~2020 ,in this time period is negative pay.Perhaps the entry conditions can be set more strictly to reduce redundant buying and selling.<\/p>\n<p class=\"wp-block-paragraph\" id=\"8f8b\">There are two special cases to remind the use of this method:<\/p>\n<ol class=\"wp-block-list\">\n<li>This method cannot be used in the face of disposal of stocks, because the trading volume is bound to decline when disposed.<\/li>\n<li>When performing index adjustment, such as FTSE index, msci, etc., the trading volume is easy to enlarge, resulting in wrong judgment of buying and selling points.<\/li>\n<\/ol>\n<p class=\"wp-block-paragraph\" id=\"498c\">In 2021 , \u201c2618\u201d started to growth ,this stargey can find the good position to buy ,and can efficient use your funds ! So we will introduce how to use TEJ -API to find the abnormal increase volume next ,and we can Cooperate with this article.<\/p>\n<p class=\"wp-block-paragraph\" id=\"f3c4\">After all, the application of technical indicator varies from person to person. As a result, if readers are interested in diverse trading 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>. Construct trading strategies fitting you with high quality database.<\/p>\n<h2 class=\"wp-block-heading\" id=\"0e25\"><strong>Source Code<\/strong><\/h2>\n<ul class=\"wp-block-list\">\n<li><a class=\"ek-link\" href=\"https:\/\/gist.github.com\/tej87681088\/d577d55fa8b8fb2d1fed9d8cba660df7#file-tejapi_medium-15-ipynb\" rel=\"noopener\" target=\"_blank\">Click here to go Github<\/a><\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"805a\"><strong>Extended Reading<\/strong><\/h2>\n<ul class=\"wp-block-list\">\n<li><a class=\"ek-link\" href=\"\/en\/insight\/modular-backtesting-system\/\">Modular Backtesting System<\/a><\/li>\n<li><a class=\"ek-link\" href=\"\/en\/insight\/technical-analysis\/\">Technical Analysis<\/a><\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"2009\"><strong>Related Link<\/strong><\/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>use volume indicator to backtesting , using 2618 Highlights Preface Nowadays Momentum trade are frequently used to trade strategy,we often talk about the price-volume relationship .So in this article we are going to talk about this strategy which based on abnormal growing of the trading volume.but this strategy doesn\u2019t have the clear definition.so we write [\u2026]<\/p>\n","protected":false},"featured_media":2372,"template":"","tags":[50,65,70,71],"insight_category":[13],"class_list":["post-2382","insight","type-insight","status-publish","has-post-thumbnail","hentry","tag-market-data","tag-python","tag-tej-api","tag-quantitative-strategy","insight_category-quant-research"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/2382","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\/2372"}],"wp:attachment":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media?parent=2382"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/tags?post=2382"},{"taxonomy":"insight_category","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight_category?post=2382"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}