{"id":16995,"date":"2022-09-21T04:02:09","date_gmt":"2022-09-20T20:02:09","guid":{"rendered":"https:\/\/www.tejwin.com\/?post_type=insight&#038;p=16995"},"modified":"2023-08-17T15:37:01","modified_gmt":"2023-08-17T07:37:01","slug":"market-strength-indicators-trade","status":"publish","type":"insight","link":"https:\/\/tejwin20260323.j.webweb.today\/en\/insight\/market-strength-indicators-trade\/","title":{"rendered":"Market strength indicators trade"},"content":{"rendered":"\n<p id=\"7bf9\">Use market strength indicators cross strategy to backtesting<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter caption-align-center\"><img decoding=\"async\" src=\"https:\/\/tejwin20260323.j.webweb.today\/wp-content\/uploads\/1Z6sJfQxPkq6HV_uwFCpfCg.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\">Photo by&nbsp;<a href=\"https:\/\/unsplash.com\/@tprahm?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\" rel=\"noreferrer noopener\" target=\"_blank\">Tyler Prahm<\/a>&nbsp;on&nbsp;<a href=\"https:\/\/unsplash.com\/s\/photos\/s%26p-500?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\" 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-6a12062c59f42\" 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-6a12062c59f42\"  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:\/\/tejwin20260323.j.webweb.today\/en\/insight\/market-strength-indicators-trade\/#Highlights\" >Highlights<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/tejwin20260323.j.webweb.today\/en\/insight\/market-strength-indicators-trade\/#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:\/\/tejwin20260323.j.webweb.today\/en\/insight\/market-strength-indicators-trade\/#The_Editing_Environment_and_Module_Required\" >The Editing Environment and Module Required<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/tejwin20260323.j.webweb.today\/en\/insight\/market-strength-indicators-trade\/#Database\" >Database<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/tejwin20260323.j.webweb.today\/en\/insight\/market-strength-indicators-trade\/#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:\/\/tejwin20260323.j.webweb.today\/en\/insight\/market-strength-indicators-trade\/#Conclusion\" >Conclusion<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/tejwin20260323.j.webweb.today\/en\/insight\/market-strength-indicators-trade\/#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-8\" href=\"https:\/\/tejwin20260323.j.webweb.today\/en\/insight\/market-strength-indicators-trade\/#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-9\" href=\"https:\/\/tejwin20260323.j.webweb.today\/en\/insight\/market-strength-indicators-trade\/#Related_Link\" >Related Link<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\" id=\"e9b4\"><span class=\"ez-toc-section\" id=\"Highlights\"><\/span><strong>Highlights<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p id=\"cd04\">Difficulty\uff1a\u2605\u2605\u2606\u2606\u2606<\/p>\n\n\n\n<p id=\"1259\">Use market strength indicators to do the moving average cross investment strategy<\/p>\n\n\n\n<p id=\"9d4d\">Advice\uff1aWe use various technical indicators and strict long &amp; short filter condition to judge the numbers of stocks strength and calculate market long short indicators. Using moving average cross strategy and visualization trading signal and buy sell point, then using optimal to get the best parameter.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"9fdf\"><span class=\"ez-toc-section\" id=\"Preface\"><\/span><strong>Preface<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p id=\"3d41\">By pulling up the weighted stocks like as TSMC, Media TEK to lead the market index rise, and others stocks fall. It will lead to investors who observe the market index have wrong judgement. We use strict long &amp; short filter condition to construct market strength indicators and design a moving average cross strategy and use optimal to find the best parameter. The following strategies are used to backtesting and adjusted through optimization:<\/p>\n\n\n\n<p id=\"3bb9\">1. entry condition: 20 days moving average of day three lines short indicators more than 20 days moving average of day of three lines long indicators<\/p>\n\n\n\n<p id=\"d1f0\">2. leaving condition: 20 days moving average of day of three lines long indicators more than 20 days moving average of day three lines short indicators<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"303f\"><span class=\"ez-toc-section\" id=\"The_Editing_Environment_and_Module_Required\"><\/span><strong>The Editing Environment and Module Required<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p id=\"2e79\">This article uses Mac OS as system and jupyter as editor.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import pandas as pd<br>import numpy as np<br>import tejapi<br>import matplotlib.pyplot as plt<br>import matplotlib.transforms as transforms<br>from matplotlib.font_manager import FontProperties#Tej Api<br>tejapi.ApiConfig.api_key = \"Your Key\"<br>tejapi.ApiConfig.ignoretz = True<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"aa6a\"><span class=\"ez-toc-section\" id=\"Database\"><\/span><strong>Database<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p id=\"ad6b\"><a href=\"https:\/\/api.tej.com.tw\/columns.html?idCode=TWN%2FANPRCSTD\" rel=\"noreferrer noopener\" target=\"_blank\"><em>Security properties Data Table (TWN\/ANPRCSTD)<br><\/em><\/a><a href=\"https:\/\/api.tej.com.tw\/columns.html?idCode=TWN%2FAVIEW1\" rel=\"noreferrer noopener\" target=\"_blank\"><em>No adjustment of(daily)technical indicators (TWN\/AVIEW1)<\/em><\/a><em><br><\/em><a href=\"https:\/\/api.tej.com.tw\/columns.html?idCode=TWN%2FAFUTR\" rel=\"noreferrer noopener\" target=\"_blank\"><em>Future database (TWN\/AFUTR)<\/em><\/a><\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"b7c0\"><span class=\"ez-toc-section\" id=\"Data_import\"><\/span><strong>Data import<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p id=\"7667\">Due to the large amount of data, we divided it into multiple fetching from TEJ API.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">data=tejapi.get('TWN\/ANPRCSTD' ,chinese_column_name=True )<br>select=data[\"\u4e0a\u5e02\u5225\"].unique()<br>select=select[1:3]<br>condition =(data[\"\u4e0a\u5e02\u5225\"].isin(select)) &amp; ( data[\"\u8b49\u5238\u7a2e\u985e\u540d\u7a31\"]==\"\u666e\u901a\u80a1\" )<br>data=data[condition]<br>twid=data[\"\u8b49\u5238\u78bc\"].to_list()  #\u53d6\u5f97\u4e0a\u5e02\u6ac3\u80a1\u7968\u8b49\u5238\u78bc<br>df = tejapi.get('TWN\/AVIEW1', #\u5f9eTEJ api\u6488\u53d6\u6240\u9700\u8981\u7684\u8cc7\u6599<br>                  chinese_column_name = True,<br>                  paginate = True,<br>                  mdate = {'gt':\"2022-01-01\", 'lt':'2022-08-31'},<br>                  coid=twid,<br>                  opts={'columns':['coid','mdate','close_d','kval','dval', 'dif','macd','a10ma']})<br>df1 = tejapi.get('TWN\/AVIEW1', #\u5f9eTEJ api\u6488\u53d6\u6240\u9700\u8981\u7684\u8cc7\u6599<br>                  chinese_column_name = True,<br>                  paginate = True,<br>                  mdate = {'gt':'2021-01-01', 'lt':'2022-01-01'},<br>                  coid=twid,<br>                  opts={'columns':['coid','mdate','close_d','kval','dval', 'dif','macd','a10ma']})df2 = tejapi.get('TWN\/AVIEW1', #\u5f9eTEJ api\u6488\u53d6\u6240\u9700\u8981\u7684\u8cc7\u6599<br>                  chinese_column_name = True,<br>                  paginate = True,<br>                  mdate = {'gt':'2020-01-01', 'lt':'2021-01-01'},<br>                  coid=twid,<br>                  opts={'columns':['coid','mdate','close_d','kval','dval', 'dif','macd','a10ma']})Y9999 = tejapi.get('TWN\/AFUTR', #\u5f9eTEJ api\u6488\u53d6\u6240\u9700\u8981\u7684\u8cc7\u6599<br>                  chinese_column_name = True,<br>                  paginate = True,<br>                  coid = 'ZTXA', <br>                  mdate = {'gt':'2020-01-01', 'lt':'2022-08-31'},<br>                  opts={'columns':['coid','mdate','close_d']})df3 = pd.merge(df2,df1,how='outer')<br>df4 = pd.merge(df3, df, how='outer') #\u5c07\u6293\u4e0b\u4f86\u7684\u6280\u8853\u6307\u6a19\u5408\u8d77\u4f86<br>df4.set_index(df4[\"\u65e5\u671f\"], inplace=True) <br>df4.drop(columns={'\u65e5\u671f'}, inplace=True)<br>df4<\/pre>\n\n\n\n<p id=\"7e13\">We filter the day go long and go short stocks.<\/p>\n\n\n\n<p id=\"7f84\">Long condition: K&gt; D, diff&gt; MACD, close&gt;10 days moving average<\/p>\n\n\n\n<p id=\"445e\">Short condition: K&lt;D, diff&lt;MACD, close&lt;10 days moving average<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">condition1 = (df4[\"K\u503c\"] &gt; df4[\"D\u503c\"]) &amp;(df4[\"\u5dee\u96e2\u503c\"]&gt; df4[\"MACD\"]) &amp; (df4[\"\u6536\u76e4\u50f9\"] &gt; df4[\"10\u65e5\u79fb\u52d5\u5e73\u5747\"])#\u65e5\u4e09\u7dda\u591a\u6307\u6a19\u7684\u689d\u4ef6<br>condition2 = (df4[\"K\u503c\"] &lt; df4[\"D\u503c\"]) &amp;(df4[\"\u5dee\u96e2\u503c\"] &lt; df4[\"MACD\"]) &amp; (df4[\"\u6536\u76e4\u50f9\"] &lt; df4[\"10\u65e5\u79fb\u52d5\u5e73\u5747\"])#\u65e5\u4e09\u7dda\u7a7a\u6307\u6a19\u7684\u689d\u4ef6long = df4[condition1] #\u628a\u7b26\u5408\u689d\u4ef6\u7684\u7be9\u9078\u51fa\u4f86<br>short = df4[condition2]<\/pre>\n\n\n\n<p id=\"17bd\">The number of stocks that correspond to go long condition divided by the number of samples and multiplied 100 to calculate day three lines long indicators.<\/p>\n\n\n\n<p id=\"d973\">The number of stocks that correspond to go short condition divided by the number of samples and multiplied 100 to calculate day three lines short indicators.<\/p>\n\n\n\n<p id=\"a420\">We merge the day three lines long indicators and the day three lines short indicators.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">long1 = ((long.groupby('\u65e5\u671f')['\u8b49\u5238\u78bc'].count())\/(df4.groupby('\u65e5\u671f')['\u8b49\u5238\u78bc'].count()))*100 #\u8a08\u7b97\u51fa\u65e5\u4e09\u7dda\u591a\u6307\u6a19<br>short1 =((short.groupby('\u65e5\u671f')['\u8b49\u5238\u78bc'].count())\/(df4.groupby('\u65e5\u671f')['\u8b49\u5238\u78bc'].count()))*100 #\u8a08\u7b97\u51fa\u65e5\u4e09\u7dda\u7a7a\u6307\u6a19<br>long1.name = '\u65e5\u4e09\u7dda\u591a\u6307\u6a19' #\u91cd\u65b0\u547d\u540d<br>short1.name = '\u65e5\u4e09\u7dda\u7a7a\u6307\u6a19'<br>result = pd.concat([long1,short1], axis=1) #\u628a\u5169\u8868\u5408\u4f75\u8d77\u4f86<\/pre>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" src=\"https:\/\/tejwin20260323.j.webweb.today\/wp-content\/uploads\/1KePZsAxGztj6ncqcNIydRQ.png\" alt=\"\"\/><\/figure>\n\n\n\n<p id=\"0f24\">We merge the market close price and long short indicators, then calculate 20 days moving average of day three lines long short indicators.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">result1 = result.merge(Y9999[['\u65e5\u671f', '\u6536\u76e4\u50f9']], on='\u65e5\u671f')result1['\u65e5\u591a20ma'] = result1['\u65e5\u4e09\u7dda\u591a\u6307\u6a19'].rolling(20).mean()<br>result1['\u65e5\u7a7a20ma'] = result1['\u65e5\u4e09\u7dda\u7a7a\u6307\u6a19'].rolling(20).mean()result1.set_index(result1['\u65e5\u671f'], inplace=True)<br>result1.drop(columns = {'\u65e5\u671f'}, inplace=True)<\/pre>\n\n\n\n<p id=\"c858\">We draw out the picture to observe the situation, we can find that the day three lines long short indicators are more suitable for reverse strategy. Therefore, the previous entry and leave condition which is refer to the drawing result.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">fig, ax1= plt.subplots(figsize =(20,16))<br>plt.plot(result1.index , result1['\u65e5\u591a20ma'],lw=1.5, label = '\u65e5\u4e09\u7dda\u591a\u6307\u6a19')       <br>plt.plot(result1.index , result1['\u65e5\u7a7a20ma'],lw=1.5, label = '\u65e5\u4e09\u7dda\u7a7a\u6307\u6a19')  <br>plt.xlabel('\u65e5\u671f',fontsize=15)<br>plt.ylabel('\u9ede\u6578', fontsize=15)<br>plt.xticks(fontsize=15)<br>plt.yticks(fontsize=15)<br>plt.title('\u65e5\u4e09\u7dda\u591a\u7a7a\u8207\u5927\u76e4\u6307\u6578',  fontsize=20)<br>plt.legend(loc=1, fontsize=15)ax2 = ax1.twinx() #\u8ddf\u7b2c\u4e00\u5f35ax1\u7684x\u8ef8\u4e00\u6a23<br>plt.plot(result1.index, result1['\u6536\u76e4\u50f9'] , lw=1.5, color='r', label='\u53f0\u6307\u671f')<br>plt.ylabel('\u80a1\u50f9', fontsize=15)<br>plt.yticks(fontsize=15)<br>plt.legend(loc=2, fontsize=15)plt.gcf().autofmt_xdate() #\u8b93x\u8ef8\u7684\u6642\u9593\u8ef8\u6bd4\u8f03\u5bec\u9b06\u3001\u6f02\u4eae<br>plt.show()<\/pre>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" src=\"https:\/\/tejwin20260323.j.webweb.today\/wp-content\/uploads\/17al6PpWuom85JTNBxYdA_Q.png\" alt=\"\"\/><\/figure>\n\n\n\n<p id=\"6d22\">We construct backtesting system and entry&amp;exit point and write the signal and some common performance indicators into function, such as: the numbers of trades, average returns, cumulative returns, win rate and buy&amp;hold returns. It\u2019s convenient for investors to evaluate the trading strategy, and it can also be rewritten according to need. Among them, n1 and n2 are the parameter of the long short indicators, which can be adjusted about optimization later.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def buysell(data,n1,n2):<br>    data =data.copy()<br>    buy=[]<br>    sell=[]<br>    hold=0<br>    data['\u65e5\u591ama'] = data['\u65e5\u4e09\u7dda\u591a\u6307\u6a19'].rolling(n1).mean()<br>    data['\u65e5\u7a7ama'] = data['\u65e5\u4e09\u7dda\u7a7a\u6307\u6a19'].rolling(n2).mean()<br>    data.dropna(inplace=True)<br>    for i in range(len(data)):<br>    <br>        if  data[\"\u65e5\u7a7ama\"][i] &gt; data[\"\u65e5\u591ama\"][i]:<br>            sell.append(np.nan)<br>            if hold !=1:<br>                buy.append(data[\"\u6536\u76e4\u50f9\"][i])<br>                <br>                hold = 1<br>            else: <br>                buy.append(np.nan)<br>        elif data[\"\u65e5\u591ama\"][i] &gt; data[\"\u65e5\u7a7ama\"][i] :<br>            buy.append(np.nan)<br>            if hold !=0:<br>                sell.append(data[\"\u6536\u76e4\u50f9\"][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>    data['Buy_Signal_Price']=a[0]<br>    data['Sell_Signal_Price']=a[1]<br>    data[\"\u8cb7\u8ce3\u80a1\u65781\"]=data['Buy_Signal_Price'].apply(lambda x : 1 if x &gt;0 else 0)<br>    data[\"\u8cb7\u8ce3\u80a1\u65782\"]=data['Sell_Signal_Price'].apply(lambda x : -1 if x &gt;0 else 0  )<br>    data[\"\u8cb7\u8ce3\u80a1\u6578\"]=data[\"\u8cb7\u8ce3\u80a1\u65781\"]+ data[\"\u8cb7\u8ce3\u80a1\u65782\"]<br>    <br>    b = data[['Buy_Signal_Price']].dropna()<br>    c = data[['Sell_Signal_Price']].dropna()<br>    d = pd.DataFrame(index=c.index, columns = {\"Buy_Signal_Price\", 'Sell_Signal_Price'})<br>    for i in range(len(d.index)):<br>        d[\"Buy_Signal_Price\"][i] = b[\"Buy_Signal_Price\"][i]<br>        d['Sell_Signal_Price'][i] = c['Sell_Signal_Price'][i]<br>    d['hold_return'] = (d['Sell_Signal_Price']-d['Buy_Signal_Price'])\/d['Buy_Signal_Price']<br>    win_rate = ((np.where(d['hold_return']&gt;0, 1, 0).sum())\/len(d.index))*100<br>    hold_ret = (d['hold_return'].sum())*100<br>    avg_ret = (d['hold_return'].mean())*100<br>    std = (d['hold_return'].std())*100<br>    <br>    final_equity = 10000<br>    for i in range(len(d.index)):<br>        final_equity = final_equity*(d['hold_return'][i]+1)<br>    cul_ret = ((final_equity-10000)\/10000)*100<br>    y9999 = ((data['\u6536\u76e4\u50f9'][-1] - data['\u6536\u76e4\u50f9'][0])\/data['\u6536\u76e4\u50f9'][0])*100<br>    <br>    #Visually show the stock buy and sell signal<br>    plt.figure(figsize=(20,16))<br>    # ^ = shift + 6<br>    plt.scatter(data.index,data['Buy_Signal_Price'],color='red', label='Buy',marker='^',alpha=1)<br>    #\u5c0f\u5beb\u7684v<br>    plt.scatter(data.index,data['Sell_Signal_Price'],color='green', label='Sell',marker='v',alpha=1)<br>    plt.plot(data['\u6536\u76e4\u50f9'], label='Close Price', alpha=0.35)<br>    plt.title('\u8cb7\u8ce3\u8a0a\u865f', fontsize=20)<br>    #\u5b57\u659c45\u5ea6\u89d2<br>    plt.xticks(rotation=45)<br>    plt.xlabel('Date', fontsize=15)  <br>    plt.ylabel('Price',fontsize=15)<br>    plt.yticks(fontsize=15)<br>    plt.xticks(fontsize=15)<br>    plt.legend(fontsize=15)<br>    plt.grid()<br>    plt.gcf().autofmt_xdate()<br>    return print(\" \u6301\u6709\u671f\u9593\u5831\u916c:\",hold_ret,\"\\n\",\"\u5e73\u5747\u5831\u916c:\",avg_ret,\"\\n\",'\u4ea4\u6613\u6b21\u6578:',len(d.index),'\\n',\"\u52dd\u7387:\",win_rate,\"\\n\",\"\u6a19\u6e96\u5dee:\",std,'\\n','\u6b0a\u76ca\u7e3d\u984d:',final_equity,'\\n','\u7d2f\u7a4d\u5831\u916c\u7387:',cul_ret,'\\n','buy&amp;hold:',y9999), plt.show()<\/pre>\n\n\n\n<p id=\"d458\">We can find that the cumulative returns are about 16.57%, losing to the buy&amp;hold strategy returns 28.95%. The result of these parameter is not a good idea, so we test the new parameter by optimize method.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">buysell(result1,20,20)<\/pre>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/tejwin20260323.j.webweb.today\/wp-content\/uploads\/1QPmwR7nwQ8CCbgqU_g0u0w.png\" alt=\"\"\/><\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" src=\"https:\/\/tejwin20260323.j.webweb.today\/wp-content\/uploads\/1U83JiDDf-M_mJ8mVZIFrOw.png\" alt=\"\"\/><\/figure>\n\n\n\n<p id=\"d438\">The optimize method is check the cumulative returns of different parameters by setting the parameter interval, and select the highest cumulative returns as the optimal parameter.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def optimal(data1,n1:range, n2:range):<br>    set_0 = 0<br>    for i in n1:<br>        for j in n2:<br>            data =data1.copy()<br>            buy=[]<br>            sell=[]<br>            hold=0<br>            data['\u65e5\u591ama'] = data['\u65e5\u4e09\u7dda\u591a\u6307\u6a19'].rolling(i).mean()<br>            data['\u65e5\u7a7ama'] = data['\u65e5\u4e09\u7dda\u7a7a\u6307\u6a19'].rolling(j).mean()<br>            data.dropna(inplace=True)<br>            for k in range(len(data)):if  data[\"\u65e5\u7a7ama\"][k] &gt; data[\"\u65e5\u591ama\"][k]:<br>                    sell.append(np.nan)<br>                    if hold !=1:<br>                        buy.append(data[\"\u6536\u76e4\u50f9\"][k])hold = 1<br>                    else: <br>                        buy.append(np.nan)<br>                elif data[\"\u65e5\u591ama\"][k] &gt; data[\"\u65e5\u7a7ama\"][k]:<br>                    buy.append(np.nan)<br>                    if hold !=0:<br>                        sell.append(data[\"\u6536\u76e4\u50f9\"][k])<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)data['Buy_Signal_Price']=a[0]<br>            data['Sell_Signal_Price']=a[1]<br>            data[\"\u8cb7\u8ce3\u80a1\u65781\"]=data['Buy_Signal_Price'].apply(lambda x : 1 if x &gt;0 else 0)<br>            data[\"\u8cb7\u8ce3\u80a1\u65782\"]=data['Sell_Signal_Price'].apply(lambda x : -1 if x &gt;0 else 0  )<br>            data[\"\u8cb7\u8ce3\u80a1\u6578\"]=data[\"\u8cb7\u8ce3\u80a1\u65781\"]+ data[\"\u8cb7\u8ce3\u80a1\u65782\"]b = data[['Buy_Signal_Price']].dropna()<br>            c = data[['Sell_Signal_Price']].dropna()<br>            d = pd.DataFrame(index=c.index, columns = {\"Buy_Signal_Price\", 'Sell_Signal_Price'})<br>            for l in range(len(d.index)):<br>                d[\"Buy_Signal_Price\"][l] = b[\"Buy_Signal_Price\"][l]<br>                d['Sell_Signal_Price'][l] = c['Sell_Signal_Price'][l]<br>            d['hold_return'] = (d['Sell_Signal_Price']-d['Buy_Signal_Price'])\/d['Buy_Signal_Price']final_equity = 10000<br>            for m in range(len(d.index)):<br>                final_equity = final_equity*(d['hold_return'][m]+1)<br>            cul_ret = ((final_equity-10000)\/10000)*100<br>            if cul_ret&gt;= set_0:<br>                set_0 = cul_ret<br>                n1_new = i<br>                n2_new = j<br>    return print(' n1:',n1_new,'\\n', 'n2:', n2_new,\"\\n\", '\u7d2f\u7a4d\u5831\u916c:', set_0)optimal(result1, n1=range(0,30), n2 =range(0,30) )<\/pre>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/tejwin20260323.j.webweb.today\/wp-content\/uploads\/1e-HNfLb41_AbxqVJ2vXK9w.png\" alt=\"\"\/><\/figure>\n\n\n\n<p id=\"4862\">The new parameters are used to recalculate the backtesting results and the entry&amp;exit points. The holding period returns are better than buy&amp;hold strategy.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" src=\"https:\/\/tejwin20260323.j.webweb.today\/wp-content\/uploads\/10hxt-yNMpVn1gEyO1oMvdg.png\" alt=\"\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"a1a8\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span><strong>Conclusion<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p id=\"f17f\">We can see that the SMA cross strategy only have 12.75% cumulative returns, nearly doubling the loss of the buy&amp;hold strategy in the beginning setting parameter. We can find that during the bull market of 2020\/4 to 2021\/4, our strategy didn\u2019t obtain much of the gains. After optimization, we can see that the cumulative returns are 33.25% and beat the buy&amp;hold strategy. Our strategy also participated in bull market period from 2020\/4 to 2021\/4, and the win rate is about 67%. But there is something to note:<br>1. The backtesting results do not take into account the commission fee.<\/p>\n\n\n\n<p id=\"bf2a\">After all, we will introduce others indicators in the future. As a result, if readers are interested in various of trading strategies, welcome to purchase the plan offered in TEJ E-Shop. Construct trading strategies fitting you with high quality database.<\/p>\n\n\n\n<p id=\"3e2a\">Last but not least, please note that \u201c<strong>Stocks this article mentions are just for the discussion, please do not consider it to be any recommendations or suggestions for investment or products.\u201d<\/strong>&nbsp;Hence, if you are interested in issues like Creating Trading Strategy , Performance Backtesting , Evidence-based research , welcome to purchase the plans offered in&nbsp;<a href=\"https:\/\/eshop.tej.com.tw\/E-Shop\/index\" rel=\"noreferrer noopener\" target=\"_blank\">TEJ E Shop<\/a>&nbsp;and use the well-complete database to find the potential event.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"b77b\"><span class=\"ez-toc-section\" id=\"Source_Code\"><\/span><strong>Source Code<\/strong><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\/660fd59ab43df06a1bc3fe6e20dcc0d9#file-tejapi_python_market_strength-ipynb\" 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\" id=\"0719\"><span class=\"ez-toc-section\" id=\"Extended_Reading\"><\/span><strong>Extended Reading<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/tejwin20260323.j.webweb.today\/en\/insight\/technical-analysis\/\" class=\"ek-link\">Technical Analysis<\/a><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/tejwin20260323.j.webweb.today\/en\/insight\/momentum-trade\/\" class=\"ek-link\">Momentum trade<\/a><\/li>\n<\/ul>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"398b\"><span class=\"ez-toc-section\" id=\"Related_Link\"><\/span><strong>Related Link<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\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\n\n\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 market strength indicators cross strategy to backtesting Highlights Difficulty\uff1a\u2605\u2605\u2606\u2606\u2606 Use market strength indicators to do the moving average cross investment strategy Advice\uff1aWe use various technical indicators and strict long &amp; short filter condition to judge the numbers of stocks strength and calculate market long short indicators. Using moving average cross strategy and visualization trading [&hellip;]<\/p>\n","protected":false},"featured_media":16997,"template":"","tags":[2371,3008,2541],"insight-category":[690,50],"class_list":["post-16995","insight","type-insight","status-publish","has-post-thumbnail","hentry","tag-python","tag-tejapi-quant","tag-2541","insight-category-data-analysis","insight-category-fintech"],"acf":[],"_links":{"self":[{"href":"https:\/\/tejwin20260323.j.webweb.today\/en\/wp-json\/wp\/v2\/insight\/16995","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tejwin20260323.j.webweb.today\/en\/wp-json\/wp\/v2\/insight"}],"about":[{"href":"https:\/\/tejwin20260323.j.webweb.today\/en\/wp-json\/wp\/v2\/types\/insight"}],"version-history":[{"count":1,"href":"https:\/\/tejwin20260323.j.webweb.today\/en\/wp-json\/wp\/v2\/insight\/16995\/revisions"}],"predecessor-version":[{"id":17011,"href":"https:\/\/tejwin20260323.j.webweb.today\/en\/wp-json\/wp\/v2\/insight\/16995\/revisions\/17011"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/tejwin20260323.j.webweb.today\/en\/wp-json\/wp\/v2\/media\/16997"}],"wp:attachment":[{"href":"https:\/\/tejwin20260323.j.webweb.today\/en\/wp-json\/wp\/v2\/media?parent=16995"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/tejwin20260323.j.webweb.today\/en\/wp-json\/wp\/v2\/tags?post=16995"},{"taxonomy":"insight-category","embeddable":true,"href":"https:\/\/tejwin20260323.j.webweb.today\/en\/wp-json\/wp\/v2\/insight-category?post=16995"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}