{"id":15998,"date":"2021-06-22T05:14:12","date_gmt":"2021-06-21T21:14:12","guid":{"rendered":"https:\/\/www.tejwin.com\/?post_type=insight&#038;p=15998"},"modified":"2023-08-10T10:21:37","modified_gmt":"2023-08-10T02:21:37","slug":"the-investment-strategy-of-trinity-investment-management","status":"publish","type":"insight","link":"https:\/\/www.tejwin.com\/en\/insight\/the-investment-strategy-of-trinity-investment-management\/","title":{"rendered":"The investment strategy of Trinity Investment Management"},"content":{"rendered":"\n<figure class=\"wp-block-image size-large\"><img fetchpriority=\"high\" decoding=\"async\" width=\"1024\" height=\"682\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\/image-244-1024x682.png\" alt=\"\" class=\"wp-image-15999\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/image-244-1024x682.png 1024w, https:\/\/www.tejwin.com\/wp-content\/uploads\/image-244-300x200.png 300w, https:\/\/www.tejwin.com\/wp-content\/uploads\/image-244-150x100.png 150w, https:\/\/www.tejwin.com\/wp-content\/uploads\/image-244-768x512.png 768w, https:\/\/www.tejwin.com\/wp-content\/uploads\/image-244.png 1400w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>Fulfill the investing strategy of Trinity Investment Management through python.<\/p>\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-69f0fb47a88a7\" 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-69f0fb47a88a7\"  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\/the-investment-strategy-of-trinity-investment-management\/#Preface\" >Preface<\/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\/the-investment-strategy-of-trinity-investment-management\/#Highlights_of_this_article\" >Highlights of this article<\/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\/the-investment-strategy-of-trinity-investment-management\/#Links_related_to_this_article\" >Links related to this article<\/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\/the-investment-strategy-of-trinity-investment-management\/#Master_Strategy\" >Master Strategy<\/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\/the-investment-strategy-of-trinity-investment-management\/#Description_of_the_Trinity_Investment_Management_strategy\" >Description of the&nbsp;Trinity Investment Management&nbsp;strategy<\/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\/the-investment-strategy-of-trinity-investment-management\/#After_the_explanation_now_lets_coding\" >After the explanation, now let\u2019s coding!!<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.tejwin.com\/en\/insight\/the-investment-strategy-of-trinity-investment-management\/#First_step_%E2%80%94_Import_packages\" >First step \u2014 Import packages<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.tejwin.com\/en\/insight\/the-investment-strategy-of-trinity-investment-management\/#Second_step_%E2%80%94_Data_collection_and_arrangement\" >Second step \u2014 Data collection and arrangement<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.tejwin.com\/en\/insight\/the-investment-strategy-of-trinity-investment-management\/#Third_step_%E2%80%94_Construct_the_master_strategy\" >Third step \u2014 Construct the master strategy<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.tejwin.com\/en\/insight\/the-investment-strategy-of-trinity-investment-management\/#Fourth_step_%E2%80%94_Master_strategy_vs_The_Taiwan_50_index\" >Fourth step \u2014 Master strategy vs The Taiwan 50 index<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.tejwin.com\/en\/insight\/the-investment-strategy-of-trinity-investment-management\/#Fifth_step_%E2%80%94_Data_visualization_and_statistic_indicator\" >Fifth step \u2014&nbsp;Data visualization and statistic indicator<\/a><\/li><\/ul><\/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\/the-investment-strategy-of-trinity-investment-management\/#Conclusion\" >Conclusion<\/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\/the-investment-strategy-of-trinity-investment-management\/#Links_related_to_this_article_again\" >Links related to this article again!<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\" id=\"67f0\"><span class=\"ez-toc-section\" id=\"Preface\"><\/span>Preface<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p id=\"9685\">Trinity Investment Management, founded in 1974, was only provided investment research advice for investment institutional clients, and it has managed investment portfolios for clients since 1980. In 1999, it became a member of Oppenheimer Funds, Inc., one of the largest mutual fund and investment management groups in the United States.<\/p>\n\n\n\n<p id=\"698c\">By the end of the first quarter of 2000, Trinity Investment Management has managed a total of US$4.2 billion for clients. Its investment philosophy was value-oriented and believed that the establishment of a successful value-based investment portfolio only requires simple and simplified concepts and systematic design. However, most fund managers didn\u2019t accept it.<\/p>\n\n\n\n<p id=\"6923\">According to years of research conducted by Trinity Investment Management, the three elements of<strong>&nbsp;P\/E ratio<\/strong>,&nbsp;<strong>P\/B ratio<\/strong>, and&nbsp;<strong>dividend yield<\/strong>&nbsp;are combined to build an investment portfolio.&nbsp;<strong>During the 15 years from 1980 to 1994, the average annual return on investment reached 20.1% and beat the S&amp;P 500 index by 6.8% every year.<\/strong>&nbsp;Stanford Calderwood, President of Trinity Investment Management, particularly emphasized the importance of dividend income to value investors and believed that the predictive data used by growth fund managers had no effect on the performance of the investment portfolio value.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p id=\"343a\">This article might be hard to totally understand. However, don\u2019t worry about it because we have provided you with the full source code and contact information at the bottom of the article.<strong>&nbsp;If you have any problems while this article, please leave a message below or email us!<\/strong><\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0ae0\"><span class=\"ez-toc-section\" id=\"Highlights_of_this_article\"><\/span><strong>Highlights of this article <\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\ud83c\udf1f Master strategy\/ adjusted strategy intro<\/li>\n\n\n\n<li>\ud83c\udf1f Adjusted strategy construct &amp; performance display<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"b219\"><span class=\"ez-toc-section\" id=\"Links_related_to_this_article\"><\/span><strong>Links related to this article<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>1\ufe0f\u20e3 API Official Website:&nbsp;<\/strong><a href=\"https:\/\/api.tej.com.tw\/\" rel=\"noreferrer noopener\" target=\"_blank\"><strong>TEJ API Official Website<\/strong><\/a><\/li>\n\n\n\n<li><strong>2\ufe0f\u20e3 The Product Package:&nbsp;<\/strong><a href=\"https:\/\/eshop.tej.com.tw\/E-Shop\/Edata_caseIntro\/1\" rel=\"noreferrer noopener\" target=\"_blank\"><strong>TEJ E-SHOP<\/strong><\/a><\/li>\n\n\n\n<li><strong>3\ufe0f\u20e3 Source Code:&nbsp;<\/strong><a href=\"https:\/\/github.com\/tejtw\/TEJAPI_Python_Medium_Application\/blob\/main\/TEJAPI_MediumWeek15.ipynb\" rel=\"noreferrer noopener\" target=\"_blank\"><strong>TEJ GITHUB<\/strong><\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6485\"><span class=\"ez-toc-section\" id=\"Master_Strategy\"><\/span><strong>Master Strategy <\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"202f\">(We replaced SP500 with 0050 Taiwan stocks)<\/h4>\n\n\n\n<p id=\"e6b6\"><strong>According to the research of Trinity Investment Management, there are three results:<\/strong><\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p id=\"16e5\"><em>1. From 1980 to 1994, the 30% stocks in the S&amp;P500 with the lowest P\/E ratio were used as the portfolio (updated and replaced every quarter), and the average annual return was 17.5%, while the return of the S&amp;P500 index during the same period was 13.3%.<\/em><\/p>\n\n\n\n<p id=\"9c28\"><em>2. At the same period, the 30% stocks in the S&amp;P500 with the lowest P\/B ratio were used as the portfolio (updated and replaced every quarter), and the average annual return was 18.1%, which was 4.8% higher than the S&amp;P500 index return.<\/em><\/p>\n\n\n\n<p id=\"5fc5\"><em>3. Take the 30% stocks in the S&amp;P500 with the highest dividend yield as the investment portfolio, and the average annual return was 18.3%, which is 5% higher than the return of the S&amp;P500 index.<\/em><\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"c137\"><span class=\"ez-toc-section\" id=\"Description_of_the_Trinity_Investment_Management_strategy\"><\/span>Description of the&nbsp;<strong>Trinity Investment Management<\/strong>&nbsp;strategy<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=\"e889\"><em>1. Sort the companies\u2019 daily P\/E ratio from low to high, and select the lowest 30% of companies.<\/em><\/p>\n\n\n\n<p id=\"4849\"><em>2. Sort the companies\u2019 daily P\/B ratio from low to high, and select the lowest 30% of companies.<\/em><\/p>\n\n\n\n<p id=\"8c78\"><em>3. Sort the companies\u2019 daily dividend yield from high to low, and select the highest 30% of companies.<\/em><\/p>\n\n\n\n<p id=\"bbf5\"><em>4. Finally, we take the union of these three conditions. The reason why we do not take the intersection is that companies with low P\/E and P\/B ratios but with high dividend yields are likely to have long-term business growth problems, and high dividend rates may be a cover for long-term stock prices that may fall below market expectations.<\/em><\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0640\"><span class=\"ez-toc-section\" id=\"After_the_explanation_now_lets_coding\"><\/span><strong>After the explanation, now let\u2019s coding!!<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2bbf\"><span class=\"ez-toc-section\" id=\"First_step_%E2%80%94_Import_packages\"><\/span><strong>First step \u2014 Import packages<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import tejapi \nimport pandas as pd\nimport numpy as np\ntejapi.ApiConfig.api_key = \"your key\"\ntejapi.ApiConfig.ignoretz = True\nimport datetime\nimport matplotlib.pyplot as plt\nfrom datetime import datetime, timedelta\nfrom functools import reduce<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1e1b\"><span class=\"ez-toc-section\" id=\"Second_step_%E2%80%94_Data_collection_and_arrangement\"><\/span><strong>Second step \u2014 Data collection and arrangement<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p id=\"81ed\">First, we could get constitute stocks of Taiwan 50 index from TW50.csv. However, the format of constitute stocks contains both numbers and characters(Ex: 1101 \u53f0\u6ce5), so we could use the second line of code to help us get the numbers only.<\/p>\n\n\n\n<p id=\"f156\">Next, we could get financial data and stock price data through the&nbsp;<strong>TWN\/AIM1A<\/strong>&nbsp;and&nbsp;<strong>TWN\/APRCM<\/strong>&nbsp;databases respectively, and replace the daily data with quarterly data&nbsp;<strong>through the resample function in pandas.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>stk_info = pd.read_csv('TW50.csv',engine='python')\nstk_nums = stk_info&#91;'\u6210\u4efd\u80a1'].apply(lambda x: str(x).split(' ')&#91;0])\nstrategy_cols = &#91;'\u516c\u53f8\u4ee3\u78bc','\u8ca1\u5831\u5e74\u6708','\u7576\u5b63\u5b63\u5e95P\/E', '\u7576\u5b63\u5b63\u5e95P\/B', '\u80a1\u5229\u6b96\u5229\u7387']\n## 2008 to 2020\n# Getting data\ndf_foundamental = pd.DataFrame()\nq_df_stock = pd.DataFrame()\ndf_stock_Qrt = pd.DataFrame()\nfor stk in stk_nums:\ndf_foundamental = df_foundamental.append(tejapi.get('TWN\/AIM1A'\n                        ,coid=stk\n                        ,mdate={'gte':'2008-01-01', 'lte':'2020-12-31'}\n                        ,paginate=True,chinese_column_name=True\n                        ,opts={'pivot':True}\n                        )).reset_index(drop=True)\n    \n    df_stock = tejapi.get('TWN\/APRCM'\n                    ,coid=stk\n                    ,mdate={'gte':'2008-01-01', 'lte':'2020-12-31'}\n                    ,paginate=True,chinese_column_name=True)\nq_df_stock = q_df_stock.append(df_stock.resample('Q', on='\u5e74\u6708').last().reset_index(drop=True))<\/code><\/pre>\n\n\n\n<p>In addition to using TW50.csv here, we provide another method for you to select the 0050 constituent stocks. Through the&nbsp;<strong>TWN\/AIDXS database<\/strong>, we can directly find the constituent stocks of 0050 at the specific time period, and ticks can be found in this method.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">df_indexcomp = tejapi.get('TWN\/AIDXS', coid= 'TWN50', <br>                  opts={'columns':['coid', 'mdate', 'key3']},<br>        mdate='gte':'2021\/02\/25','lte':'2021\/02\/25'},paginate=True)df_indexcomp['stk'] = <br>\u3000\u3000\u3000\u3000\u3000[df_indexcomp.iloc[i,2].split(' ')[0] for i in range(df_indexcomp.shape[0])]df_indexcomp['name'] = <br>         [df_indexcomp.iloc[i,2].split(' ')[1] for i in range(df_indexcomp.shape[0])]ticks = df_indexcomp.stk.unique()<\/pre>\n\n\n\n<figure class=\"wp-block-image aligncenter is-resized caption-align-center\"><img decoding=\"async\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/1ttYjeHcq6YpXvbcDkPtK4Q.png\" alt=\"\" width=\"391\" height=\"379\"\/><figcaption class=\"wp-element-caption\">TWN\/AIDXS Database<\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter caption-align-center\"><img decoding=\"async\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/135QM9WzejahXLlRAfEYypg.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\">Ticks from the database<\/figcaption><\/figure>\n\n\n\n<p id=\"cc55\">Next, because we want to merge the two data tables, we need to<strong>&nbsp;rename the columns<\/strong>&nbsp;in the two tables,<strong>&nbsp;select the data<\/strong>&nbsp;we want, and use&nbsp;<strong>the merge function in pandas<\/strong>&nbsp;to merge.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>##financial report table\ndf_foundamental.rename(columns={'\u516c\u53f8\u4ee3\u78bc':'coid','\u8ca1\u5831\u5e74\u6708':'\u65e5\u671f'},inplace=True)\ndf_foundamental = df_foundamental&#91;&#91;'coid','\u65e5\u671f','\u7576\u5b63\u5b63\u5e95P\/E', '\u7576\u5b63\u5b63\u5e95P\/B', '\u80a1\u5229\u6b96\u5229\u7387']]\n##stock price table\nq_df_stock.rename(columns={'\u8b49\u5238\u4ee3\u78bc':'coid','\u5e74\u6708':'\u65e5\u671f'},inplace=True)\nq_df_stock = q_df_stock&#91;&#91;'coid','\u65e5\u671f','\u6536\u76e4\u50f9(\u5143)_\u6708']]\n##merge\nnew_df = pd.merge(q_df_stock, df_foundamental, on = &#91;'\u65e5\u671f', 'coid'])\nnew_df.sort_values(by='\u65e5\u671f').reset_index(drop=True)<\/code><\/pre>\n\n\n\n<p id=\"4415\">Then, you can see the following data table, the quarterly data of 0050 constituent stocks from 2008 to 2020, and quarterly PE, PB ratios, and dividend yield.<\/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\/15HGoI5SfniiwHwSJojmubQ.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\">Merged Table<\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"c595\"><span class=\"ez-toc-section\" id=\"Third_step_%E2%80%94_Construct_the_master_strategy\"><\/span><strong>Third step \u2014 Construct the master strategy<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p id=\"381a\">Since we will need three main conditions here, namely the P\/E, P\/B ratios, and the dividend yield. Therefore, we will first change the data format from the original 2008\u201303\u2013 01 to 200803, and&nbsp;<strong>use the groupby function<\/strong>&nbsp;in pandas to compare all the same 200803 together, and then present our filtering conditions.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>##data format change\nnew_df&#91;'\u65e5\u671f'] = pd.to_datetime(new_df&#91;'\u65e5\u671f'])\nnew_df&#91;'Month'] = new_df&#91;'\u65e5\u671f'].apply(lambda x:datetime.strftime(x,'%Y%m'))\n##groupby \ndf_pe_quantile = new_df.groupby('Month')&#91;'\u7576\u5b63\u5b63\u5e95P\/E'].quantile(0.3).reset_index().rename(columns={'\u7576\u5b63\u5b63\u5e95P\/E':'PE\u6708quantile'})\ndf_pb_quantile = new_df.groupby('Month')&#91;'\u7576\u5b63\u5b63\u5e95P\/B'].quantile(0.3).reset_index().rename(columns={'\u7576\u5b63\u5b63\u5e95P\/B':'PB\u6708quantile'})\ndf_div_quantile = new_df.groupby('Month')&#91;'\u80a1\u5229\u6b96\u5229\u7387'].quantile(0.7).reset_index().rename(columns={'\u80a1\u5229\u6b96\u5229\u7387':'Div\u6708quantile'})\n##multiple tables merge\ndf_merged = reduce(lambda  left,right: pd.merge(left,right,on=&#91;'Month'],how='outer'), &#91;new_df,df_pe_quantile,df_pb_quantile,df_div_quantile])<\/code><\/pre>\n\n\n\n<p id=\"b32e\">Then, in addition to the original fields, you can see data has added our filter criteria columns.<\/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\/1_1HtY-dWllZgfBiTAcKXATxg.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\">New Table<\/figcaption><\/figure>\n\n\n\n<p id=\"5538\">Next, we can select the constituent stocks that meet our three conditions!<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>##Selection\ndf_filter = df_merged&#91;\n(df_merged&#91;'\u7576\u5b63\u5b63\u5e95P\/E'] &lt; df_merged&#91;'PE\u6708quantile'])|\n(df_merged&#91;'\u7576\u5b63\u5b63\u5e95P\/B'] &lt; df_merged&#91;'PB\u6708quantile'])|\n(df_merged&#91;'\u80a1\u5229\u6b96\u5229\u7387'] &gt; df_merged&#91;'Div\u6708quantile'])]\n.reset_index(drop =True)<\/code><\/pre>\n\n\n\n<p id=\"b165\">After the selection, you can clearly see that our data has reduced from 2,419 to 1,386. Then we will present it to you in two sorted ways, one is by coid and the other one is by date.<\/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\/1_1MtSXOyhDOTsgbC9gdROMtA.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\">Sorted by Coid<\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-image is-resized caption-align-center\"><img decoding=\"async\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/1_1_Ct08HrRaB4e_nioABmZNg.png\" alt=\"\" width=\"840\" height=\"366\"\/><figcaption class=\"wp-element-caption\">Sorted by Date<\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"86fc\"><span class=\"ez-toc-section\" id=\"Fourth_step_%E2%80%94_Master_strategy_vs_The_Taiwan_50_index\"><\/span><strong>Fourth step \u2014 Master strategy vs The Taiwan 50 index<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p id=\"97e7\">(The codes and parameter explanation can mainly refer to the fourth step in&nbsp;<strong>[Application (1)]<\/strong>. Except for the time period and grouping, the remaining&nbsp;<strong>parameters and logical concepts are similar to this strategy.<\/strong>)<\/p>\n\n\n\n<p id=\"6816\">The strategy will change the portfolio every quarter. Since we can directly find the company\u2019s quarterly return through the&nbsp;<strong>TWN\/APRCD2 database<\/strong>&nbsp;in TEJ, we compare the quarterly return of each quarter of the portfolio and the quarterly return of 0050. The code is as follows:<br><strong>\uff0aThis backtest ignores all transaction costs.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import datetime\nreturn_=pd.DataFrame()\ndates = df_filter&#91;'\u65e5\u671f'].astype(str).apply(lambda x: x.split(' ')&#91;0]).unique()\n\nfor date in dates:\n\n    # \u8a2d\u5b9a\u65e5\u671f\n    year = int(date.split('-')&#91;0])\n    month = int(date.split('-')&#91;1])\n    day = 1\n    date1 = str(year)+'-'+str(month)+'-'+str(day)\n    ret = &#91;date1]\n    pf = df_filter&#91;df_filter&#91;'\u65e5\u671f']==date].reset_index(drop=True)\n    print(date1)\n    \n    ## \u5c07\u8cb7\u9032\u65e5\u671f\u8a2d\u5728\u7576\u67081\u65e5\uff0c\u7531\u65bc\u5831\u916c\u7387\u7684\u95dc\u4fc2\u6211\u5011\u8981\u627e\u7684\u6642\u9593\u70ba\u4e00\u5b63\u4e4b\u5f8c\u7684\u5831\u916c\u7387\u7576\u4f5c\u662f\u5728\u539f\u5148\u6642\u9593\u8cfc\u8cb7\u6301\u6709\u7684\u5831\u916c\u7387##\n    buy_date = datetime.datetime(year,month,day) + datetime.timedelta(90)\n    sell_date = buy_date + datetime.timedelta(90) \n    pf_H = pf&#91;'coid'].to_list()\n    print('getting data')\n    data = tejapi.get('TWN\/APRCD2',coid  = pf_H, paginate = True, mdate={'gte':buy_date,'lte':sell_date},chinese_column_name=True)\n    q1_ret = data.groupby(by = '\u8b49\u5238\u4ee3\u78bc').last()&#91;'\u5b63\u5831\u916c\u7387 %'].values\n    \n    # \u8a08\u7b97\u5831\u916c\u7387 #\n    print('calculating return')\n    w = 1\/len(pf_H) # \u7b49\u6b0a\u91cd \n    q1_wret = (w*q1_ret).tolist() # \u52a0\u6b0a\u5e73\u5747\u5831\u916c\n    ret.append(round(sum(q1_wret),2))\n    \n    ## \u6488\u53d6\u53f0\u7063 50\u6307\u6578\u7684\u5e74\u5831\u916c\u7387\uff0c\u65e5\u671f\u8a2d\u5b9a\u70ba buy_date(\u542b)\u81f3 sell_date(\u542b) ##\n    tw0050 = tejapi.get('TWN\/APRCD2',coid ='TRI50' ,paginate = True,mdate={'gte':buy_date,'lte':sell_date},chinese_column_name=True)\n    bm_return = tw0050.groupby(by = '\u8b49\u5238\u4ee3\u78bc').last()&#91;'\u5b63\u5831\u916c\u7387 %'].values\n    if bm_return.size!=0:\n        ret.append(round(bm_return.tolist()&#91;0],2))\n    else:\n        ret.append(None)\n    rets = np.reshape(np.array(ret),(1,3)).tolist()\n    retss = pd.DataFrame(data=rets,columns=&#91;'Date','port_return','twn50_return'])\n    return_ = return_.append(retss).reset_index(drop=True)\n    print(return_)<\/code><\/pre>\n\n\n\n<p id=\"8707\">Then we can watch our return table.<\/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\/1pjN0vT55Aa7c3rHlNaNrGQ.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\">Quarterly Return\uff08Port vs 0050\uff09<\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"fbe7\"><span class=\"ez-toc-section\" id=\"Fifth_step_%E2%80%94_Data_visualization_and_statistic_indicator\"><\/span><strong>Fifth step \u2014&nbsp;Data visualization and statistic indicator<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p id=\"998c\">We will simply present the quarterly return and the cumulative return by the graphs to everyone.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>##Quarterly return and cumulative return\ncum_ret = ((return_&#91;&#91;'port_return', 'twn50_return']].astype(float)*0.01)+1).cumprod()\ncum_ret&#91;'Date'] = return_&#91;'Date']  \ncum_ret = cum_ret&#91;:len(cum_ret)-1]\ncum_ret = cum_ret&#91;&#91;'Date','port_return','twn50_return']]\nquarter_ret = return_&#91;&#91;'port_return', 'twn50_return']].astype(float)\nquarter_ret&#91;'Date'] = return_&#91;'Date']  \nquarter_ret = quarter_ret&#91;:len(quarter_ret)-1]\nquarter_ret = quarter_ret&#91;&#91;'Date','port_return','twn50_return']]<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Quarterly Return<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>plt.style.use('seaborn')\nplt.figure(figsize=(10,5))\nplt.xticks(rotation = 90)\nplt.title('master invest strategy - quarter return',fontsize = 20)\ndate = quarter_ret&#91;'Date']\nplt.plot(date,quarter_ret.port_return,color ='red',label='port_return')\nplt.plot(date,quarter_ret.twn50_return,color = 'black',label='twn50_return')\nplt.legend(fontsize = 15)<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/15_H2wg5-2z2j3Xxa3ZZxWQ.png\" alt=\"\"\/><\/figure>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"8c40\"><strong>Cumulative Return<\/strong><\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>plt.style.use('seaborn')\nplt.figure(figsize=(10,5))\nplt.xticks(rotation = 90)\nplt.title('master invest strategy - cumulative return',fontsize = 20)\ndate = cum_ret&#91;'Date']\nplt.plot(date,cum_ret.port_return,color ='red',label='port_return')\nplt.plot(date,cum_ret.twn50_return,color = 'black',label='twn50_return')\nplt.legend(fontsize = 15)<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/1rGlzLh9gBtbY6ICP8xvDUQ.png\" alt=\"\"\/><\/figure>\n\n\n\n<p id=\"c89d\">The performance of the master\u2019s strategy is very outstanding!<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"a314\">Statistic Indicator<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>Ratio = pd.DataFrame()\nfor col in cum_ret.columns&#91;1:]:\n    \n    ##CAGR\n    cagr = (cum_ret&#91;col].values&#91;-1]) ** (4\/len(cum_ret)) -1\n    \n    ##STD\n    std = return_&#91;col]&#91;:len(return_)-1].astype(float).std()\n    \n    ##Sharpe Ratio(\u5047\u8a2d\u7121\u98a8\u96aa\u5229\u7387\u70ba1%)\n    sharpe_ratio = (cagr-0.01)\/(std*0.01)\n    \n    ##MDD\n    roll_max = cum_ret&#91;col].cummax()\n    monthly_dd =cum_ret&#91;col]\/roll_max - 1.0\n    max_dd = monthly_dd.cummin()\n    \n    ##Table\n    ratio = np.reshape(np.round(np.array(&#91;100*cagr, std, sharpe_ratio, 100*max_dd.values&#91;-1]]),2),(1,4))\n    Ratio = Ratio.append(pd.DataFrame(index=&#91;col], \n      columns=&#91;'\u5e74\u5316\u5831\u916c\u7387(%)', '\u5e74\u5316\u6a19\u6e96\u5dee(%)', '\u590f\u666e\u6bd4\u7387', '\u671f\u9593\u6700\u5927\u56de\u64a4(%)'], \n      data = ratio))\nRatio.T<\/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\/10fm2YrpfELdFpSJ9KamjFA.png\" alt=\"\"\/><figcaption class=\"wp-element-caption\">Indicators<\/figcaption><\/figure>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"b3c5\"><strong>Constituent stocks for 2020\/12<\/strong><\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>pf = df_filter&#91;df_filter&#91;'\u65e5\u671f']== '2020-12-01'].reset_index(drop=True)\nstk_info&#91;'stk_num'] = stk_info&#91;'\u6210\u4efd\u80a1'].apply(lambda x: str(x).split(' ')&#91;0])\nstk_info&#91;'stk_cname'] = stk_info&#91;'\u6210\u4efd\u80a1'].apply(lambda x: str(x).split(' ')&#91;1])\nstk_info&#91;'\u6210\u4efd\u80a1']&#91;stk_info&#91;'stk_num'].isin(pf&#91;'coid'].tolist())].to_list()<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image aligncenter is-resized caption-align-center\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/1WNkKRYgYag-WvyVrsdCF8Q.png\" alt=\"\" width=\"131\" height=\"358\"\/><figcaption class=\"wp-element-caption\">Constituent stocks<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ccae\"><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=\"3e2b\">We have implemented several master strategies through python. In addition to data collation, we also backtested them and presented the results through tables and visualizations. Hope everyone can be satisfied with our articles.<\/p>\n\n\n\n<p id=\"1f37\"><strong>To make successful backtesting, we still need to pay attention to things such as the data quality, the length of data, whether there are bugs in your program, whether too many transaction costs are ignored, etc.<\/strong>&nbsp;As long as there is a mistake in these problems,&nbsp;<strong>it will cause the distortion of the backtesting and lose money!!&nbsp;<\/strong>As a result, you have to pay attention to our backtesting result again\ufe0f\ufe0f\ufe0f\ufe0f\ufe0f\ufe0f\ufe0f\ufe0f\ufe0f\ufe0f\ufe0f every time.<\/p>\n\n\n\n<p id=\"b41f\">Finally, if you like this topic, please click below, giving us more support and encouragement.&nbsp;<strong>Then, we will still work on financial data analysis and applications in the following articles, please look forward to them<\/strong> Besides, if you have any questions or suggestions, please leave a message or email us, we will try our best to reply to you.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p id=\"9e96\"><strong>Question:<br>Where could I get the data with a stable, high quality, and the time length is sufficient? TEJ API is your best choice!!<\/strong><\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"8eeb\"><span class=\"ez-toc-section\" id=\"Links_related_to_this_article_again\"><\/span><strong>Links related to this article again!<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>API Official Website:&nbsp;<\/strong><a href=\"https:\/\/api.tej.com.tw\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>TEJ API Official Website<\/strong><\/a><\/li>\n\n\n\n<li><strong>The Product Package:&nbsp;<\/strong><a href=\"https:\/\/eshop.tej.com.tw\/E-Shop\/Edata_caseIntro\/1\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>TEJ E SHOP<\/strong><\/a><\/li>\n\n\n\n<li><strong>Source Code:&nbsp;<\/strong><a href=\"https:\/\/github.com\/tejtw\/TEJAPI_Python_Medium_Application\/blob\/main\/TEJAPI_MediumWeek15.ipynb\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>TEJ GITHUB<\/strong><\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Fulfill the investing strategy of Trinity Investment Management through python. Preface Trinity Investment Management, founded in 1974, was only provided investment research advice for investment institutional clients, and it has managed investment portfolios for clients since 1980. In 1999, it became a member of Oppenheimer Funds, Inc., one of the largest mutual fund and investment [&hellip;]<\/p>\n","protected":false},"featured_media":15999,"template":"","tags":[2371,3005],"insight-category":[690,50,3509],"class_list":["post-15998","insight","type-insight","status-publish","has-post-thumbnail","hentry","tag-python","tag-tejapi-application","insight-category-data-analysis","insight-category-fintech","insight-category-fintech-en"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/15998","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":0,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/15998\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media\/15999"}],"wp:attachment":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media?parent=15998"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/tags?post=15998"},{"taxonomy":"insight-category","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight-category?post=15998"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}