<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by TEJ 台灣經濟新報 on Medium]]></title>
        <description><![CDATA[Stories by TEJ 台灣經濟新報 on Medium]]></description>
        <link>https://medium.com/@tejapi?source=rss-6b49fe7bddc1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oVbGQBHNClWZtM811mB5jg.png</url>
            <title>Stories by TEJ 台灣經濟新報 on Medium</title>
            <link>https://medium.com/@tejapi?source=rss-6b49fe7bddc1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 13:16:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tejapi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[【重要公告】TEJ Medium 停止更新！歡迎至TEJ官方網站閱讀最新文章]]></title>
            <link>https://tejapi.medium.com/%E9%87%8D%E8%A6%81%E5%85%AC%E5%91%8A-tej-medium-%E5%81%9C%E6%AD%A2%E6%9B%B4%E6%96%B0-%E6%AD%A1%E8%BF%8E%E8%87%B3tej%E5%AE%98%E6%96%B9%E7%B6%B2%E7%AB%99%E9%96%B1%E8%AE%80%E6%9C%80%E6%96%B0%E6%96%87%E7%AB%A0-acbd098d952d?source=rss-6b49fe7bddc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/acbd098d952d</guid>
            <dc:creator><![CDATA[TEJ 台灣經濟新報]]></dc:creator>
            <pubDate>Fri, 11 Apr 2025 01:39:59 GMT</pubDate>
            <atom:updated>2025-04-11T01:48:27.577Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LEkkhAuETnvW2DQ2yEm7BA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nordwood?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">NordWood Themes</a> on <a href="https://unsplash.com/photos/person-wearing-watch-near-laptop-kRNZiGKtz48?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Hello, 各位TEJ專欄的讀者夥伴們！</p><p>感謝大家長期以來對 TEJ Medium 的支持與關注！</p><p>經過團隊仔細的考量與評估，為了提供更完整的閱讀體驗，自即日起，TEJ 將停止在 Medium 平台更新文章，未來所有的內容將統一發布於 TEJ 官方網站。</p><p>👉 前往 TEJ 官方網站閱讀最新文章與觀點：<a href="https://www.tejwin.com/insight-home/"><strong>[前往TEJ官方網址]</strong></a></p><p>我們將持續分享市場觀察、產業分析、產品應用與數據洞察，歡迎您追蹤我們的網站，不錯過任何一篇精彩內容！</p><p>但Medium這邊也別急著取消關注，日後如果有重大消息或是分析資訊，也還是有機會回到Medium平台與讀者分享～</p><p>再次感謝您的陪伴與支持，期待在新的平台也能與您相見！</p><p><strong><em>－2025.04.11 TEJ 台灣經濟新報－</em></strong></p><p>－－－</p><p>Hello to all our TEJ column readers!</p><p>Thank you for your continued support and attention to TEJ’s Medium content over the years.</p><p>After careful consideration and evaluation, we have decided to stop updating our Medium platform in order to provide a more complete and seamless reading experience. Starting today, all new articles and updates will be exclusively published on the <strong>TEJ official website</strong>.</p><p>👉 Check out our latest articles and insights here: <a href="https://www.tejwin.com/en/insight-home/"><strong>[Visit TEJ Official Website]</strong></a></p><p>We will continue to share market observations, industry analysis, product applications, and data-driven insights — so be sure to follow us on our official site and never miss a great read!</p><p>That said, don’t unfollow our Medium just yet — we may still return occasionally with major updates or special analysis worth sharing with our readers here.</p><p>Thank you once again for your support and companionship. We look forward to seeing you on our new platform!</p><p><strong><em>— April 11, 2025 TEJ (Taiwan Economic Journal)</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acbd098d952d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Application】MasterLink Securities API Beginner’s Guide： How to Use TQuant Lab Strategies for…]]></title>
            <link>https://medium.com/tej-api-financial-data-anlaysis/application-masterlink-securities-api-beginners-guide-how-to-use-tquant-lab-strategies-for-b1e2e194afb6?source=rss-6b49fe7bddc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1e2e194afb6</guid>
            <category><![CDATA[tej]]></category>
            <category><![CDATA[automated]]></category>
            <category><![CDATA[tej-api]]></category>
            <category><![CDATA[tquant-lab]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[TEJ 台灣經濟新報]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 15:41:35 GMT</pubDate>
            <atom:updated>2025-02-06T15:41:35.913Z</atom:updated>
            <content:encoded><![CDATA[<h3>【Application】MasterLink Securities API Beginner’s Guide： How to Use TQuant Lab Strategies for Automated Trading</h3><p>Nov 08 2024</p><figure><img alt="Automated Trading" src="https://cdn-images-1.medium.com/max/1024/0*N81ttLYejHl4hnu0.jpeg" /><figcaption>Photo by<a href="https://unsplash.com/@walkator"> Walkator</a> on<a href="https://unsplash.com/"> Unsplash</a></figcaption></figure><h3>Preface</h3><p>In modern financial markets, algorithmic trading is increasingly becoming essential for investors to enhance efficiency and reduce risk. More and more brokerage firms offer API services, enabling investors to automate order placement and quickly respond to market changes. This article will demonstrate using MasterLink Securities API for automated trading while integrating strategies from TQuant Lab. Through a practical example, we’ll show how a systematic approach can optimize investment decisions, helping investors seize market opportunities and improve performance.</p><h3>Strategy Example</h3><p>This guide uses Warren Buffett’s corporate investment principles as an example. Refer to <strong>TQuant Lab’s Warren Buffett Corporate Investment Rules</strong> for a detailed introduction.</p><h3>Example Summary</h3><p>The quantitative indicators used in this strategy include:</p><ol><li>Recent Annual Return on Equity (ROE) &gt; Industry Average</li><li>3-Year Average ROE &gt; 15%</li><li>Recent Annual Gross Profit Margin &gt; Industry Average</li><li>7-Year Market Value Growth / 7-Year Retained Earnings Growth &gt; 1</li><li>(Recent Annual Free Cash Flow / Free Cash Flow from 7 Years Ago) — 1 &gt; 1</li></ol><p>Since ROE can be boosted by increased debt, industries with high leverage, such as the financial sector, are excluded. Additionally, Buffett expects companies to generate more than one unit of market value for every unit of retained earnings. This involves filtering companies listed for over 7 years, as a more extended listing history is necessary for this evaluation.</p><h3>Fetch the required financial data using the TejToolAPI</h3><p>According to the stock selection criteria in the corporate investment rules, we require the following 7 financial items:</p><ul><li>Primary Industry (Chinese)</li><li>Consistent ROE</li><li>Operating Gross Margin</li><li>Individual Stock Market Value (in NT$)</li><li>Retained Earnings</li><li>Cash Flow from Operations</li><li>Cash Flow from Investments</li></ul><p>The cash flow from operations and the cash flow from investments can be used to calculate the free cash flow.</p><p><strong>Free Cash Flow = Cash Flow from Operations + (-) Cash Flow from Investments</strong></p><p>Note that the cash flow from investments is often a negative number.</p><p>p.s.</p><p>Detailed instructions for using the <strong>TejToolAPI</strong> can be found on the <strong>TQuant Lab GitHub</strong>: <a href="https://github.com/tejtw/TQuant-Lab/blob/main/lecture/Data%20Preprocess%20-%20tejtoolapi.ipynb">TejToolAPI Documentation</a>.</p><p>The datasets provided by the <strong>TejToolAPI</strong> can be referenced on the <strong>TQuant Lab official website</strong>: <a href="https://tquant.tejwin.com/%e8%b3%87%e6%96%99%e9%9b%86/">TQuant Lab Datasets</a>.</p><h3>Extract targets that meet the 5 stock selection criteria.</h3><p>We select stocks meeting the criteria as of <strong>2015–12–31</strong>. For each condition, a separate set is created, and the final step involves taking the intersection of these sets to identify the targets that satisfy all the conditions.</p><p>By taking the intersection of stocks meeting the 5 stock selection criteria, we can determine our targets. It is evident that the majority of these stocks belong to the <strong>Electronic Components</strong> and <strong>Semiconductor</strong> industries.</p><figure><img alt="Automated Trading" src="https://cdn-images-1.medium.com/max/313/0*qgp1qqKXPO_jnELt.png" /><figcaption>Targets that meet the 5 stock selection criteria.</figcaption></figure><p>This gives us the stock pool selected using this strategy. Next, we proceed to the formal order placement stage.</p><h3>Environment Setup and Package Installation</h3><p>The verification process includes the following steps:</p><p><strong>STEP 1:</strong><br>Download the API component and use your program to log in to the MasterLink Securities API. Log in to the test environment.</p><p><strong>STEP 2:</strong><br>Place, modify, and cancel ROD orders (verify the order details on the Digital API website and execute the order through your program).</p><p><strong>STEP 3:</strong><br>Place IOC orders (verify the order details on the Digital API website and execute the order through your program).</p><p><strong>STEP 4:</strong><br>Place FOK orders (verify the order details on the Digital API website and execute the order through your program).</p><p><strong>STEP 5:</strong><br>After placing the order, enter the order number on the Digital API website verification page.</p><p><strong>STEP 6:</strong><br>For Steps 3, 4, and 5, after entering the order number, click “Verify” on the Digital API website verification page.</p><p><strong>STEP 7:</strong><br>Once the verification is successful, the process is complete. Please wait for the manual review to finalize the approval process before gaining access.</p><p>First, you must install <strong>MasterTradePy</strong>, which can help you implement automated trading strategies.</p><p>Use the cd command in the terminal to navigate to the <strong>MasterTradePy</strong> folder.</p><pre>cd MasterTradePy <br>pip install MasterTradePy-0.0.15-py3-none-win_amd64.whl</pre><h3>Importing Packages</h3><p>Return to your code editor and load the required packages for the API.</p><pre>import threading<br>from MasterTradePy.api import MasterTradeAPI<br>from MasterTradePy.model import *<br>from MasterTradePy.constant import PriceType, OrderType, TradingSession, Side, TradingUnit, RCode</pre><h3>Initialization Settings</h3><p>Set up your account credentials (account and password) and specify the target stock codes.</p><p>Here, we create a list of stock codes selected based on the <strong>Buffett Strategy</strong>, representing the stock pool.</p><pre>username = &#39;your_username&#39;<br>password = &#39;your_password&#39;<br>stock_id_list = [<br>    1476, 1477, 2467, 3006, 3014, 3034, <br>    3042, 3413, 3533, 3557, 5234, 5269, <br>    6202, 8016, 8046, 8081, 9906<br>]</pre><p><strong>event = threading.Event() Explanation</strong></p><p><strong>event = threading.Event()</strong> manages synchronization between multiple threads. This is particularly important when using the API for trading, as it ensures that certain events (e.g., successful connection) occur before other program parts proceed.</p><pre>event = threading.Event()</pre><h3>Execute Orders</h3><p>We will place market orders to buy all the stocks in the stock pool.</p><pre>def execute_order(api, stock_id_list):<br>account = &#39;your_account&#39;<br>price = &#39;&#39;  # Leave blank for market order<br>qtr = &#39;1000&#39;  # For 1 lot, enter 1000<br>orderType = OrderType.ROD<br>if not price:<br>    priceType = PriceType.MKT<br>else:<br>    priceType = PriceType.LMT<br>for stock_id in stock_id_list:<br>    symbol = stock_id<br>    order = Order(tradingSession=TradingSession.NORMAL,<br>                  side=Side.Buy,<br>                  symbol=symbol,<br>                  priceType=priceType,<br>                  price=price,<br>                  tradingUnit=TradingUnit.COMMON, <br>                  qty=qty,<br>                  orderType=orderType,<br>                  tradingAccount=account,<br>                  userDef=&#39;&#39;)<br>    rcode = api.NewOrder(order)<br>    if rcode == RCode.OK:<br>        print(f&#39;Order sent successfully: {symbol}&#39;)<br>    else:<br>        print(f&#39;Order failed! Stock symbol: {symbol}. Please run the program again and adjust <br>the input based on the returned data.&#39;)</pre><h3>Main Program Flow for Automated Order Placement</h3><p>The primary flow of the automated order placement program is as follows:</p><pre>def main():<br>    trader = ConcreteMarketTrader()<br>    api = MasterTradeAPI(trader)<br>    api.SetConnectionHost(&#39;solace140.masterlink.com.tw:55555&#39;)<br>    # Log in to the trading server<br>    rc = api.Login(username, password, True, True, True)<br>    if rc == RCode.OK:<br>        print(&#39;Successfully connected to the trading server, proceeding with two-factor authentication&#39;)<br>        # Retrieve accounts and perform verification<br>        accounts = [x[4:] for x in api.accounts]<br>        rcc = api.CheckAccs(tradingAccounts=accounts)<br>        if rcc == RCode.OK:<br>           print(&#39;Verification passed, API trading functions are available&#39;)<br>    execute_order(api, stock_id_list)<br>    input(&quot;Press Enter to finish...\n&quot;)<br>main()</pre><h3>Conclusion</h3><p>This article demonstrates how to use MasterLink Securities’ API for automated order placement, applying Buffett’s value investing strategy in practical scenarios. We covered how to set up the trading environment, execute the strategy, and follow the order placement process. By utilizing programmatic trading, investors can enhance trading efficiency. In the next article, we will introduce the usage and examples of the SinoPac API, guiding readers further into the field of algorithmic trading.</p><p><strong>Note:</strong> The Buffett stock selection rules and API automation program in this article are for demonstration purposes only and do not guarantee profitability. Investing involves risks, and strategies may result in gains or losses. When referencing this article to develop investment strategies, it is recommended to incorporate both personal and external information, specify the quantity and price for each stock order, and strictly manage risk.</p><p>In the future, TEJ will continue using its database and TQuant Lab to construct various indicators and backtest their performance. Readers interested in trading backtesting are encouraged to explore <a href="https://tquant.tejwin.com/"><strong>TQuant Lab</strong></a>‘s offerings. With a high-quality database, you can build a trading strategy tailored to your needs.</p><p><a href="https://tquant.tejwin.com/">TQuant Lab｜一站式量化研究，打造專屬於你的投資研究金鑰</a></p><h3>Source Code</h3><p><a href="https://github.com/tejtw/TEJAPI_Python_Medium_Quant/blob/main/%E5%85%83%E5%AF%8C%20API%20%E4%B8%8B%E5%96%AE%E4%BB%8B%E7%B4%B9.ipynb">Github</a></p><h3>Further Reading</h3><ul><li><a href="https://www.tejwin.com/en/insight/counter-indicator/">Counter-Indicator Analysis: Using TEJ API to Examine the Relationship Between Stock Prices and Counter-Indicators Issued By Authority”</a></li><li><a href="https://www.tejwin.com/en/insight/election-market-trend/">Is There an Election Market Trend ? Research on Presidential Elections Using TEJ API</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1e2e194afb6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tej-api-financial-data-anlaysis/application-masterlink-securities-api-beginners-guide-how-to-use-tquant-lab-strategies-for-b1e2e194afb6">【Application】MasterLink Securities API Beginner’s Guide： How to Use TQuant Lab Strategies for…</a> was originally published in <a href="https://medium.com/tej-api-financial-data-anlaysis">TEJ-API Financial Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Application】What are Treasury Stock?]]></title>
            <link>https://medium.com/tej-api-financial-data-anlaysis/application-what-are-treasury-stock-e9dfd4d3aff9?source=rss-6b49fe7bddc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9dfd4d3aff9</guid>
            <category><![CDATA[tej-api]]></category>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[treasury-stock]]></category>
            <category><![CDATA[treasury]]></category>
            <category><![CDATA[tej]]></category>
            <dc:creator><![CDATA[TEJ 台灣經濟新報]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 14:42:14 GMT</pubDate>
            <atom:updated>2025-02-06T14:42:14.721Z</atom:updated>
            <content:encoded><![CDATA[<h3>【Application】What are Treasury Stock? TEJ Will Tell You Treasury Stocks’ Advantages, Disadvantages, And Inquiry Channels.</h3><p>Oct 23 2024</p><figure><img alt="國庫存量" src="https://cdn-images-1.medium.com/max/817/0*I-Emo-4_tfjtogOH.png" /><figcaption>Photo by <a href="https://unsplash.com/@jp_shoots"><strong>Pamela Buenrostro</strong></a> on <a href="https://unsplash.com/">unsplash</a></figcaption></figure><p>Have you ever heard someone say that a particular company is about to repurchase its treasury stock, prompting friends around you to shout: “Hurry and join the buyers! The stock is about to soar, and if you don’t get in now, when will you?” Have you ever wondered why they say that? What exactly is treasury stock, and how is it different from outstanding shares? Why would a company buy back its stock?</p><p>Don’t worry; this article will reveal everything step by step. Today, let TEJ guide you through understanding what treasury stock is from the beginning!</p><h3>What is a treasury stock? What is the difference between treasury stock and outstanding stock?</h3><p>Before introducing treasury stock, let me introduce you to a company in Taiwan that is applying for a listing. The company’s paid-in capital must reach NT$600 million or more, and the number of common shares to be issued must reach 30 million or more. After listing or listing on the Taiwan Stock Exchange, these shares will be circulated to the secondary market, where we usually place our orders and become the so-called ‘Outstanding Stocks’!</p><p>What are treasury stocks? Simply put, treasury stock is when a company uses cash to buy back its shares! Imagine a company is like a shopkeeper who likes his products, and when he sees that they are selling well, he chooses to repurchase some of them. There are many reasons for doing this, such as to increase earnings per share, to increase shareholder value, or because the company thinks its stock is undervalued and wants to buy it at a lower price.</p><p>When a company announces that it will take money to buy back its shares, and the repurchased shares are not canceled, they are called treasury shares. A company that announces a treasury stock program usually sets a purchase limit, but how much is repurchased? That’s where the execution rate comes in! The execution rate is the number of shares bought back as a percentage of the total number of shares in the plan. If the execution rate is high, the company is actively buying back shares; if it is low, it may have reservations about the market.</p><h3>Why would a company buy back treasury stocks?</h3><p>To serve as a source of conversion for preferred shares or corporate bonds.</p><h3>1. To serve as a conversion source for preferred shares or corporate bonds.</h3><p>When a company buys back its shares, they are recorded in its account and can be converted to preferred shares or bonds at any time. Why is this so? Preferred shares and corporate bonds usually have unique conversion options that allow the holder to convert these financial instruments into common stock, also known as convertible corporate bonds.</p><p>Companies can use treasury shares to adjust their capital structure, ensuring market liquidity and boosting investor confidence. This makes treasury shares a powerful tool for navigating market volatility and responding to various situations.</p><h3>2. Encourage employee morale.</h3><p>The company can buy back treasury shares as part of the employee incentives, such as stock options or employee bonuses, which not only allows employees to feel that the company values their efforts but also has more confidence in the future of the company, more committed to work, and grow together with the company because they know that they have the opportunity to share the fruits of the company’s growth, and also can effectively solve the ‘agent problem’ between the company and the employees. The agency problem between the company and its employees can be solved simultaneously.</p><h3>3. Protecting Company Autonomy: A Shield Against Takeovers</h3><p>Lastly, treasury stock can be necessary for safeguarding a company’s autonomy! When there is a potential risk of a hostile takeover in the market, a company can opt to repurchase its shares, thereby reducing the number of outstanding shares and increasing the shareholding proportion of internal shareholders, thus strengthening management’s control. This prevents external investors from using considerable shareholdings to initiate takeovers or alter the company’s management.</p><p>In such situations, treasury stock acts as a “shield” against external threats, protecting the company from hostile takeover attempts. It also allows the management to focus more resources on the company’s long-term growth and value creation.</p><h3>What Should I Be Aware of When a Company Repurchases Treasury Stock?</h3><figure><img alt="國庫存量" src="https://cdn-images-1.medium.com/max/898/0*b2jguRs9DJWjuIhH.png" /><figcaption>Schematic illustration of Key Considerations for Treasury Stock</figcaption></figure><p>Is a company’s buyback of treasury stock excellent or bad? After the buyback, investors need to consider the following factors carefully:</p><h3>1. Concerns About Liquidity</h3><p>When a company decides to repurchase treasury stock, it often requires a significant cash outlay. This expenditure can impact the company’s liquidity, particularly in the short term, as cash flow may become tighter. If the buyback is substantial, the company might need to readjust its capital allocation, possibly even reducing other operational or investment projects to support the buyback plan.<br>Moreover, if the market environment is unstable or the company needs funds for its operations, holding a large amount of treasury stock could add financial pressure. Therefore, companies usually conduct a careful cash flow assessment before deciding on a buyback to ensure that core operations won’t be affected and that unexpected funding needs can be met.</p><h3>2. Risks Following Stock Price Rise</h3><p>When a company announces a treasury stock buyback plan, the market often views it as positive news, interpreting it as a sign that the stock is undervalued. This perception may lead to a short-term increase in stock price. However, this rise, driven by the buyback, is usually short-lived and may not be sustainable in the long run. The stock may eventually decline if the company’s operational performance doesn’t improve or earnings cannot support the increased stock price.</p><p>Investors should be cautious in this situation. While a buyback may temporarily boost the stock price, only improvements in financial performance and business fundamentals can genuinely support sustained stock growth. Otherwise, once market enthusiasm fades, the stock price could return to levels that reflect the company’s actual performance — or even drop below the pre-buyback level — rendering the short-term “buyback effect” a fleeting phenomenon.</p><h3>Frequently Asked Questions about Treasury Stocks</h3><p>After mentioning so many functions that treasury shares can play, do you know what companies need to pay attention to when buying treasury shares? Below is a list of frequently asked questions about treasury stocks!</p><h3>1. How is the buyback price of treasury stocks set? Are there any restrictions?</h3><p>First, listed companies must report and announce the information of share repurchase to the FSC by the ‘<a href="https://law.moj.gov.tw/ENG/LawClass/LawAll.aspx?pcode=G0400061">Regulations on Share Repurchase by Listed Companies</a>‘ and input it into the Market Observation Post System (MOPS). The content of the announcement must include the purpose of the repurchase, the type of shares, the maximum total amount of shares to be repurchased, the scheduled period and amount of shares to be repurchased, the range of prices for the repurchase, and the method of the repurchase, etc. Among this information, the cost of the repurchase should be determined by the FSC.</p><p>Among them, setting the buyback price is a critical concern for the market! There are many factors that a company needs to consider when setting the buyback range price, such as the current share price, the average and volatility of the recent share price, the Company’s reason for buying back the shares, and the timing of the planned buyback, etc. These considerations can help the Company avoid setting a high buyback price for the market. These considerations can help the Company avoid setting a price range that is too unreasonable and misleading to investors.</p><p>According to the FSC’s recommendation, after considering the above factors, it is appropriate to set the buyback range between 150% of the average closing price the ten business days or 30 business days before the board of directors’ resolution, whichever is higher, and 70% of the closing price of the date of the board of directors’ resolution. If the Company finds that the share price exceeds the set range when buying back shares, whether above or below the range, the Company must stop buying back. However, the Company can reassess the situation, revise the range, announce, and continue to buy back. An exception is made if the board of directors has already resolved to ‘continue to buy back even if the share price is below the lower limit of the range!</p><h3>2. Do I need to announce the progress during the treasury stock buyback period?</h3><p>Yes, we do! When the number of shares repurchased reaches 2% of the total number of issued shares or the amount reaches NT$300 million, the company must immediately make an announcement! When the number of shares repurchased reaches 2% of the total number of issued shares or the amount reaches NT$300 million, the company must immediately make an announcement! Therefore, during the buyback period, the company has to keep reporting the progress to the outside world so that everyone can keep up with the latest developments of the treasury shares! In addition, if the buyback is not completed during the execution period, according to Article 5 of the ‘Regulations on the <a href="https://law.moj.gov.tw/ENG/LawClass/LawAll.aspx?pcode=G0400061">Buyback of the Company’s Shares by Listed and OTC Companies’</a>, the buyback must be conducted again by the board of directors’ resolution, and therefore, the company still needs to make announcements and reports by the regulations.</p><h3>3. How often should treasury stocks be canceled?</h3><p>According to Article 28–2 of <a href="https://law.moj.gov.tw/ENG/LawClass/LawAll.aspx?pcode=G0400001">the Securities and Exchange Act</a>, when a company repurchases treasury shares, it must transfer them to its employees within five years of repurchasing. If the shares are not transferred within five years, they are considered unissued and subject to change registration.</p><h3>How to buy treasury stocks? 2 major channels tell you!</h3><p>How can an investor find out if a company has treasury shares? There are two main channels for the relevant information.</p><h3>Treasury Stocks Enquiry Pipeline 1: Market Observation Post System</h3><p>The most common way is to go to the <a href="https://emops.twse.com.tw/server-java/t58query">Market Observation Post System (MOPS</a>) and look for it directly! Click on ‘Information for Treasury Stocks’ under ‘Investment Section’ → ‘Company Stock Buyback Data For Listed Company’ on the MOPS, and you can see the basic information about treasury stocks such as the purpose, type, total amount limit, scheduled buyback period and quantity, etc. as mentioned in the previous section!</p><figure><img alt="國庫存量" src="https://cdn-images-1.medium.com/max/1024/0*TGhNrosKSBl86YxA.png" /><figcaption>Market Observation Post System (MOPS) Treasury Stock Information</figcaption></figure><p>Treasury Stocks Enquiry Pipeline 2: TEJ PRO</p><p>If you want to use treasury stocks to analyze the company’s share price in more detail, you can check <a href="https://www.tejwin.com/en/service-provide-method/">TEJ PRO</a>! Log in to TEJ PRO and click ‘Treasury Stock Information’ in the database of listed and former listed companies; you can quickly get all the relevant and more detailed information. In addition to the basic information provided in the Market Observation Post System (MOP), TEJ also provides the start and end date of the actual buyback, the number of shares held at the time of the resolution (%), and the amount of the application as a percentage of the current assets (%), etc., which allows you to feel at ease and use TEJ’s data to conduct quantitative analysis. You can use TEJ’s data to conduct quantitative analyses with peace of mind and make your experimental results more accurate!</p><p>TEJ’s data is updated every day before 10:00 pm, and it also provides a period condition query function, which makes it more convenient for you to filter the trading information you need!</p><figure><img alt="國庫存量" src="https://cdn-images-1.medium.com/max/1024/0*Z7FONQTyFfxbzyXm.png" /><figcaption>TEJ Treasury Stocks Information</figcaption></figure><h3>The Friendliest Financial Data Tool｜TEJ Database</h3><p>Through the introduction of this article, you should understand that treasury stock is not only an investment strategy for companies but also a versatile tool to respond flexibly to market changes, enhance company value, and motivate employees. However, treasury shares also have risks, especially regarding liquidity and short-term stock price fluctuations. Therefore, when investors see a company announcing a treasury stock program, they should consider the company’s motivation and the market situation rather than unthinkingly following the trend.</p><h3>Extended Reading</h3><ul><li>More on treasury stocks-related regulations:</li><li><a href="https://www.sfb.gov.tw/en/home.jsp?id=26&amp;parentpath=0,9">Treasury Shares Q&amp;A Compendium</a></li><li><a href="https://law.moj.gov.tw/ENG/LawClass/LawAll.aspx?pcode=G0400061">Measures for the Buyback of the Company’s Shares by Listed and OTC Companies</a></li><li>More articles on financial literacy:</li><li><a href="https://www.tejwin.com/en/insight/directors-supervisors-remunerations/">Directors &amp; Supervisor’s Remunerations</a></li><li><a href="https://www.sfb.gov.tw/en/home.jsp?id=26&amp;parentpath=0,9">What is Zero Stock Trading? TEJ will introduce you to it from the very beginning.</a></li><li>More on TEJ Financial Data:</li><li><a href="https://www.tejwin.com/en/insight/financial-data-sourcing-strategic-guide/">Mastering the Dynamics of Financial Data Sourcing: A Strategic Guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9dfd4d3aff9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tej-api-financial-data-anlaysis/application-what-are-treasury-stock-e9dfd4d3aff9">【Application】What are Treasury Stock?</a> was originally published in <a href="https://medium.com/tej-api-financial-data-anlaysis">TEJ-API Financial Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Financial Data Analysis】“Unlocking Market Insights: Comparing Three Strategies Based on Directors’…]]></title>
            <link>https://medium.com/tej-api-financial-data-anlaysis/financial-data-analysis-unlocking-market-insights-comparing-three-strategies-based-on-directors-8bc69c8e2d50?source=rss-6b49fe7bddc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bc69c8e2d50</guid>
            <category><![CDATA[shareholding]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[tej-api]]></category>
            <category><![CDATA[directors]]></category>
            <category><![CDATA[tej]]></category>
            <dc:creator><![CDATA[TEJ 台灣經濟新報]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 09:02:18 GMT</pubDate>
            <atom:updated>2025-02-06T09:02:18.832Z</atom:updated>
            <content:encoded><![CDATA[<h3>【Financial Data Analysis】“Unlocking Market Insights: Comparing Three Strategies Based on Directors’ Shareholding Data”</h3><p>Nov 29 2024</p><figure><img alt="Directors’ Shareholding Data" src="https://cdn-images-1.medium.com/max/1024/0*qU41F85dBd_5lA_j" /><figcaption><strong>Photo by </strong><a href="https://unsplash.com/@hush52"><strong>Hush Naidoo Jade</strong></a><strong> on </strong><a href="https://unsplash.com/"><strong>unsplash</strong></a></figcaption></figure><h3>Preface</h3><p>In the stock market, the shareholding ratio of directors has always been a key indicator for investors. Changes in insider holdings often signal <strong>their confidence in the company’s future development</strong> and have potential impacts on stock prices. However, identifying meaningful changes in shareholding ratios from vast data can be challenging for investors.</p><p>To address this issue, we filter out companies with significant changes in the shareholding ratios of directors and conduct backtesting in Taiwan stock market. Through TEJ Director’s Holding database, we can efficiently uncover the potential relationship between management’s actions and stock price movements, and evaluate the performance of this strategy to help investors capture hidden opportunities in the market.</p><p>In this article, we will give you a comprehensive introduction to Directors’ Holdings and the comparison of three strategies based on the change of shareholdings. Curious about how to use director shareholding ratios to predict stock price trends and gain an edge in your investments? Let’s explore the secret of it in the following.</p><h3>What is the Director Holding Ratio and its Regulations in Taiwan?</h3><p>The directors’ and supervisors’ shareholding ratio refers to <strong>the proportion of shares held by the company’s directors and supervisors relative to the company’s total capital</strong>. The level of this ratio serves as one of the indicators of top management’s confidence in the company’s prospects. According to Article 2 of the “Regulations Governing the Shareholding Ratio of Directors and Supervisors of Public Companies and the Verification of Compliance”, companies are required to <strong>maintain a specific shareholding ratio for directors and supervisors based on their capital size</strong>. This legal restriction ensures that the interests of directors and supervisors align with those of the company, preventing decisions detrimental to the company’s long-term development and addressing <strong>agency problems</strong>.</p><figure><img alt="Directors’ Shareholding Data" src="https://cdn-images-1.medium.com/max/1024/1*09JZa5LJRfddhynYKVULIA.png" /><figcaption>Table 1. Shareholding ratios compiled by TEJ</figcaption></figure><h3>The Implication of the Level of Director’s and Supervisors’ Holding Ratio</h3><h3>High Directors’ and Supervisors’ Shareholding Ratio</h3><p>When the shareholding ratio of a company’s directors and supervisors is high, it is often seen as a sign of the management’s active involvement in the company’s operations. This is because their financial interests are closely tied to the company’s performance. Moreover, it enhances external investors’ confidence in the company’s future, contributing to the stability of the internal management team. External investors are likely to have a more optimistic outlook on the company’s long-term development when they see management <strong>“standing with the company.”</strong> This trust can lead to <strong>positive</strong> market reactions, potentially driving the stock price higher.</p><p>In addition, a high directors’ and supervisors’ shareholding ratio may indicate that management has a stronger voice in corporate governance, enabling them to more effectively implement strategic decisions. For a company with a clear development direction, this can enhance its competitiveness in the market.</p><h3>Low Directors’ and Supervisors’ Shareholding Ratio</h3><p>When the directors’ and supervisors’ shareholding ratio is low or significantly decreases, the market may interpret this <strong>negatively</strong>. A reduction in management’s shareholding can be seen as a lack of confidence in the company’s future prospects or even as a sign of adverse changes within the company. In such cases, external investors may grow concerned about the company’s future performance and may choose to reduce their investments or withdraw entirely.</p><p>This shift in market sentiment often has a negative impact on the company’s stock price. Particularly in cases where directors and supervisors significantly reduce their holdings, panic selling may occur, causing the stock price to plummet rapidly. Furthermore, a low shareholding ratio among directors and supervisors could mean weaker management influence in corporate governance, making the company more susceptible to external interference — a potential risk to the company’s long-term stable operations.</p><p>After understanding the shareholding ratio restrictions in Taiwan and how the level of shareholding ratio may reflect management’s confidence in their own company, this article will outline three investment strategies based on the TEJ shareholding ratio database. These strategies will then be evaluated using a backtesting system to assess their strengths and weaknesses, providing investors with guidance on how to use directors’ shareholding data to develop effective strategies.</p><h3>Stock Selection Based on Directors’ Holdings</h3><h3>Trading Logic</h3><p>We analyze changes in director shareholding using three strategies, with the backtesting period set from January 1, 2020, to December 31, 2023. According to <strong>Article 25, Paragraph 2 of the Securities and Exchange Act</strong>, the shareholding ratios of directors must be disclosed by <strong>the 15th</strong> of each month for the preceding month. Therefore, we set the rebalancing date for these strategies on the 16th of each month.</p><h3>Strategy Selection Criteria</h3><p>Here are three strategies according to different criteria:</p><ul><li><strong>Shareholding ratio above 40%</strong>: Ensure that the shareholding ratio of directors and supervisors meets a certain threshold, filtering for companies with high shareholding levels.</li><li><strong>Top 30 shareholding ratios</strong>: Leverage the momentum effect by selecting the top 30 companies for investment to identify potentially higher returns.</li><li><strong>Shareholding ratio increases for two consecutive months</strong>: Indicates strong expectations for the future by insiders, as reflected in their consecutive monthly increases in shareholding ratios.</li></ul><p>These strategies will be referred to as <strong>Strategy 1</strong>, <strong>Strategy 2</strong>, and <strong>Strategy 3</strong> in the following analysis. To enhance the realism of the strategies, we incorporate <strong>slippage</strong> and <strong>transaction fees</strong> into the model. This allows us to simulate the impact of price friction on trading outcomes during order execution.</p><h3>How to Implement the Shareholding Strategy</h3><p>The following demonstrates how we will generate the trading signals required for the Shareholding Strategy.</p><h3>Backtesting with TEJ Director’s Shareholding Data</h3><p>We set the following data and rule to backtest:</p><ul><li>Stock pool: Taiwan listed companies, Including both common stocks and KY stocks. Considering that <strong>smaller-cap companies typically have higher director shareholding ratios</strong>, the strategy does not specifically focus on the top 200 highly liquid stocks in Taiwan, which allows for more precise targeting of small to mid-cap stocks that meet the strategy’s criteria.</li><li>Backtesting period：From 2020–01–01 to 2023–12–31</li><li>Trading set：Liquidity slippage and transaction fees</li><li>Benchmark：TAIEX-Total Return Index ( IR0001 )</li><li>Data Source：</li><li><a href="https://www.tejwin.com/en/databank-solution/fundamental-data/">Director’s Shareholding Ratio from TEJ Director’s Holding database</a></li><li><a href="https://www.tejwin.com/en/databank-solution/market-data/">Stock price and trading volume from TEJ Stock Price database</a></li><li>Initial capital of 1,000,000 NTD, Max leverage 1</li></ul><h3>Construct the Trading Signal</h3><p>After obtaining price-volume and historical data, we set up the 3 strategies:</p><ul><li>Strategy 1: Input shareholding ratio data; buy when the board of directors and supervisors’ shareholding ratio <strong>exceeds 40%</strong>, and sell otherwise.</li><li>Strategy 2: Input shareholding ratio data; buy when the shareholding ratio ranks among <strong>the top 30</strong>, and sell otherwise.</li><li>Strategy 3: Input consecutive two-month shareholding ratio change data; buy when the changes for t<strong>wo consecutive periods are both greater than zero</strong>, and sell otherwise.</li></ul><p>According to Article 25, Paragraph 2 of the “Securities and Exchange Act”, the shareholding ratios of directors and supervisors must be disclosed before the 15th of each month for the previous month’s data. Therefore, the strategy rebalancing date is set as the 15th of each month.</p><h3>Key Observations in Backtesting</h3><figure><img alt="Directors’ Shareholding Data" src="https://cdn-images-1.medium.com/max/917/0*u9NAr9SHudPgWIE1.png" /><figcaption>Table 2. The comparison of three strategies</figcaption></figure><p>From the data above, the <strong>annualized returns</strong> for the three strategies are <strong>17.3%, 18.87%, and 19.64%</strong>, all outperforming the market. However, observing the performance charts reveals that Strategy 1 l underperformed the market for most of the time before 2023, while Strategy 2 and Strategy 3 experienced fluctuations, achieving noticeably superior performance only in the later stages. This indicates that these strategies may struggle to outperform the market in the short term and require long-term holding to fully realize their advantages.</p><p>Furthermore, the <strong>Sharpe ratios</strong> for the three strategies are <strong>1.09, 1.24, and 1.27</strong>, showing that Strategy 3 delivers the best risk-adjusted returns. This further confirms that the ratio of director holding possesses predictive power. However, these strategies still require the patience of long-term holding to unlock their full investment potential.</p><p>Finally, the <strong>maximum drawdowns</strong> are –<strong>29.9%, -21.95%, and -28.29%</strong>. For conservative investors, it is recommended to assess their risk tolerance to ensure they can maintain a stable mindset and respond appropriately during significant market fluctuations, avoiding adverse impacts on investment decisions caused by emotional stress.</p><figure><img alt="Directors’ Shareholding Data" src="https://cdn-images-1.medium.com/max/937/0*PfKMxfRqm42QKWqj.png" /><figcaption>Figure 1. The results of Strategy 1</figcaption></figure><figure><img alt="Directors’ Shareholding Data" src="https://cdn-images-1.medium.com/max/954/0*qVS4TmlVsca344DA.png" /><figcaption>Figure2. The results of Strategy 2</figcaption></figure><figure><img alt="Directors’ Shareholding Data" src="https://cdn-images-1.medium.com/max/950/0*kLbLUaQVqGojAvqd.png" /><figcaption>Figure 3. The results of Strategy 3</figcaption></figure><figure><img alt="Directors’ Shareholding Data" src="https://cdn-images-1.medium.com/max/1024/0*hNOyqGWL5RBoQvUa.jpg" /><figcaption>Figure 4. The number of months with negative returns</figcaption></figure><p>From the chart, it can be observed that t<strong>he number of months with negative returns</strong> for the three strategies are <strong>14, 17, and 10</strong> months, respectively. Strategy 1 and Strategy 2 experienced more months of negative returns, which could expose investors to greater fluctuations during the holding period, potentially affecting their confidence and patience in executing the strategies. In contrast, Strategy 3 had the fewest negative return months at just 10, achieving stable returns with fewer loss months, thereby reducing stress for investors.</p><p>Additionally, the <strong>Sortino ratios</strong> for the three strategies are <strong>1.4, 1.67, and 1.65</strong>, indicating that Strategy 2 and Strategy 3 provide better risk-adjusted returns. Strategy 3 not only has the fewest months with negative returns but also maintains a high Sortino ratio, highlighting its risk management advantages. This allows investors to remain confident in following the strategy even during periods of downside risk.</p><figure><img alt="Directors’ Shareholding Data" src="https://cdn-images-1.medium.com/max/1024/0*zmijnn20HjR4U85d.png" /><figcaption>Figure 5: TOP 10 stock exposures for each strategy</figcaption></figure><p>Further analysis of the <strong>TOP 10 stock exposures</strong> for each strategy reveals that the average single-stock exposure is <strong>0.004, 0.035, and 0.0125</strong>, respectively. This indicates that Strategy 1 holds the largest number of stocks, followed by Strategy 3, and lastly Strategy 2.</p><p>However, the <strong>maximum drawdowns</strong> for Strategies 1 to 3 are <strong>-29.9%, -21.95%, and -28.29%</strong>, respectively. Although Strategy 1 attempts to mitigate risk by holding more stocks, it still fails to reduce its downside risk. This also results in Strategy 1 having the lowest Sortino ratio among the three strategies.</p><figure><img alt="Directors’ Shareholding Data" src="https://cdn-images-1.medium.com/max/1024/0*kFpOpsKIS45KtxDY.png" /><figcaption>Figure 6: Maximum drawdowns for each strategy</figcaption></figure><p>Finally, we analyze the top five drawdowns using the chart. The data shows that the <strong>average drawdown durations </strong>are <strong>118.4 days, 117.8 days, and 99.8 days</strong>, with the longest drawdown periods concentrated in 2022. Over the approximately 1,000 trading days spanning four years, the days with significant drawdowns account for around 10% to 12%. This highlights that investors executing such strategies must be mentally prepared and ready to handle potential long-term fluctuations.</p><h3>Conclusion</h3><p>From the results of the three strategies, each strategy exhibits different risk and return characteristics. <strong>Strategy 3</strong> demonstrates <strong>greater stability</strong>, while <strong>Strategy 2</strong> achieves the <strong>smallest drawdown</strong>. Notably, all three strategies, constructed by the shareholding ratio of directors, outperform the market in terms of returns with Sharpe ratios exceeding 1, confirming the predictive power of this approach.</p><p>Among the three strategies, we consider <strong>Strategy 2 and Strategy 3 as reliable options</strong>. Their entry and exit conditions can be further tailored to meet investors’ preferences. In contrast, Strategy 1, based on high shareholding ratios, still has room for improvement.</p><p>Applying the shareholding ratio of directors can achieve superior risk-adjusted returns over the long term, making it suitable for conservative investors seeking stable performance. However, the length and frequency of drawdown periods emphasize that these strategies are not short-term arbitrage tools but better suited for investors with patience.</p><h3>TEJ Database: Comprehensive Fundamental Data for Informed Investment in Taiwan</h3><p>Making informed investment decisions in Taiwan’s stock market requires access to reliable and detailed data. TEJ’s Fundamental Data service, which includes extensive director and supervisor shareholding information, provides investors with the tools needed to develop precise and effective strategies.</p><p>With features like Point-in-Time Data, TEJ ensures that all historical information is time-accurate and free from lookahead bias, enabling the creation of trustworthy investment models. This level of data precision helps investors gain deeper insights into market dynamics and uncover valuable opportunities with confidence.</p><p>For those focused on building long-term, stable strategies, TEJ’s database is an indispensable resource. From director shareholding ratios to broader financial and corporate data, TEJ offers a robust platform tailored to the nuances of Taiwan’s market.</p><p>Discover how TEJ’s Fundamental Data can elevate your investment strategies: <a href="https://www.tejwin.com/en/databank-solution/fundamental-data/">TEJ Fundamental Data</a>.</p><h3>Further Reading</h3><p><a href="https://www.tejwin.com/en/insight/2024-new-independent-director-regulations-hits-the-road-what-impacts-may-be-led-to/">2024 New Independent Director Regulations hits the road! What impacts may be led to?</a></p><p><a href="https://www.tejwin.com/en/insight/insider-transfers/">“Block Trades” as Warning Signals? Analyzing Insider Transfers and Changes in Stock Prices Using TEJ API</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bc69c8e2d50" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tej-api-financial-data-anlaysis/financial-data-analysis-unlocking-market-insights-comparing-three-strategies-based-on-directors-8bc69c8e2d50">【Financial Data Analysis】“Unlocking Market Insights: Comparing Three Strategies Based on Directors’…</a> was originally published in <a href="https://medium.com/tej-api-financial-data-anlaysis">TEJ-API Financial Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Financial Data Analysis】Analyzing Factor Performance with Alphalens: Foreign Capital Factor…]]></title>
            <link>https://medium.com/tej-api-financial-data-anlaysis/financial-data-analysis-analyzing-factor-performance-with-alphalens-foreign-capital-factor-0153707908b9?source=rss-6b49fe7bddc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0153707908b9</guid>
            <category><![CDATA[alphalens]]></category>
            <category><![CDATA[factor]]></category>
            <category><![CDATA[tej-api]]></category>
            <category><![CDATA[tej]]></category>
            <category><![CDATA[edition]]></category>
            <dc:creator><![CDATA[TEJ 台灣經濟新報]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 02:37:17 GMT</pubDate>
            <atom:updated>2025-02-06T02:37:17.562Z</atom:updated>
            <content:encoded><![CDATA[<h3>【Financial Data Analysis】Analyzing Factor Performance with Alphalens: Foreign Capital Factor Edition</h3><p>Nov 15 2024</p><figure><img alt="阿爾法倫斯" src="https://cdn-images-1.medium.com/max/1024/0*kZl6Jq5cQt9Qf3_f.jpg" /><figcaption>Photo by<a href="https://unsplash.com/@lealea_leaa"> <strong>Behnam Norouzi</strong></a> on<a href="https://unsplash.com/photos/black-leather-zip-up-jacket-on-white-textile-nsRBbE6-YLs?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash"> Unsplash</a></figcaption></figure><h3>Key Highlights of This Article</h3><ul><li>Basic Introduction to Alphalens</li><li>Overview of Foreign Capital Factors</li></ul><h3>Preface</h3><p>You’ll inevitably encounter numerous factor strategies, whether you are an experienced trader or a beginner. By selecting factors that closely correlate with market performance, investors can more effectively predict asset returns and find stable sources of income in uncertain market environments. The essence of factor strategies lies in simplifying complex market phenomena into a few quantifiable drivers, helping us understand capital flows and risk distribution. These factors reveal the roots of market volatility and provide practical decision-making tools for investors.</p><p>This series of articles will use Alphalens to explore several key factors, gradually analyzing their impact on market performance. The first article focuses on “foreign capital,” examining the effects of foreign capital flows into the market. Next, we’ll delve into “value factors,” studying how they reflect a company’s intrinsic value. Finally, the last article will analyze “price-volume factors,” uncovering the interplay between price and trading volume.</p><p>If you’re interested in conducting similar factor analyses, you can use the <em>alphalens-tej</em> tool in TQuant Lab. By seamlessly integrating TEJ data and eliminating the need for complex data processing, this tool enables you to quickly evaluate factor performance and further support the development of your investment strategies.</p><h3>What is Foreign Capital Factor</h3><p>In China’s A-share market, “northern-bound funds,” entering the Chinese market through the Shanghai-Hong Kong Stock Connect and Shenzhen-Hong Kong Stock Connect, are regarded as direct indicators of foreign investors’ sentiment toward the Chinese market. These capital flows are often used to monitor market trends and have demonstrated significant influence in related studies. Consequently, northern-bound factors receive considerable attention and application in the Chinese market.</p><p>When analyzing northern-bound factors in Taiwan’s stock market, we can observe the changes in foreign holdings across different industries or individual stocks. Foreign investors account for a relatively high proportion of trading volume in the Taiwan market and have a notable impact on market movements. Due to the substantial scale of foreign capital, their buying and selling activities often drive short-term market fluctuations. This is particularly evident in specific industries or leading stocks, where these activities better reflect foreign investors’ preferences and capital flows. By tracking the changes in foreign capital factors, we can more accurately identify trends for asset allocation and even capture early warning signals of market risks.</p><p><strong>Factors Used in This Article:</strong></p><p><strong>5-Day Change in Foreign Ownership Ratio</strong></p><ul><li><strong>Formula:</strong> The change in “foreign ownership ratio” over the past 5 days.</li></ul><p><strong>5-Day Net Inflows</strong></p><ul><li><strong>Formula:</strong> The total “foreign buying amount” over the past 5 days.</li></ul><p><strong>Data Source:</strong></p><p>The data used in this article is sourced from the TEJAPI “Transaction Data — Chip Data (Daily)” table (TWN/APISHRACT). The fields utilized are “foreign ownership ratio” and “foreign buying amount (in TWD).”</p><h3>Introduction to Alphalens</h3><p>The Alphalens-tej package in TQuant Lab is a Python toolkit for factor analysis. Its core functionality assists investors in reviewing and evaluating factor performance, thereby formulating more effective factor strategies. For detailed instructions, refer to <a href="https://github.com/tejtw/TQuant-Lab/blob/main/lecture/Alphalens%20.ipynb"><strong>Alphalens. ipynb</strong></a>.</p><p>In quantitative investing, factors are indicators used to explain and predict asset returns. Common factors include the price-to-earnings ratio (P/E), price momentum, trading volume, etc.</p><p>Alphalens provides a series of powerful visualization tools and metrics, such as:</p><ul><li><strong>Mean Period Wise Return by Factor Quantile</strong></li><li><strong>Information Coefficient (IC)</strong></li><li><strong>Cumulative Returns by Quantile</strong></li></ul><p>These features help investors better understand a factor’s predictive power and stability. With Alphalens, investors can quickly analyze the performance of various factors under different market conditions and identify the factor combinations or strategies most suitable for them.</p><p>Furthermore, Alphalens integrates seamlessly with TEJ data, making it ideal for conducting factor backtesting and visualization analysis using TQuant Lab. This integration dramatically enhances the convenience and efficiency of factor research.</p><h3>Single Factor Analysis</h3><p>Due to space constraints, this section focuses only on calculating the factor’s IC (Information Coefficient) and IR (Information Ratio, i.e., risk-adjusted IC) and plotting bar charts of the average returns for each factor quantile.</p><p>The data sample period used in this article spans from 2014 to 2024, and the stock pool consists of the top 100 market-cap stocks among all listed companies.</p><figure><img alt="阿爾法倫斯" src="https://cdn-images-1.medium.com/max/540/0*ImctTh6PyLhKHoTn.png" /><figcaption>IC, IR Values, and Average Returns for Each Factor<br>(Holding Period: 1 Month)</figcaption></figure><p><strong>Mean Return</strong></p><ul><li>This column shows the average return for each factor.</li><li>A negative value indicates that the factor’s overall performance during the holding period resulted in a negative return.</li></ul><p><strong>IC Mean</strong></p><ul><li>Represents the average Information Coefficient (IC), reflecting the correlation between the factor values and asset returns.</li><li>A positive IC Mean indicates a positive correlation, while a negative value indicates an inverse correlation.</li><li>Generally, the higher the absolute value of IC Mean, the stronger the factor’s predictive power.</li></ul><p><strong>IC Std</strong></p><ul><li>Refers to the standard deviation of IC values, indicating the volatility of IC.</li><li>A higher IC Std suggests lower stability in the factor’s predictions, whereas a lower IC Std indicates more consistent predictive performance.</li></ul><p><strong>IR (Information Ratio)</strong></p><ul><li>Calculated as the ratio of IC Mean to IC Std, representing the risk-adjusted performance of the factor.</li><li>The higher the absolute value of IR, the more stable and reliable the factor is in predicting asset returns.</li></ul><p><strong>IC &gt; 0.03</strong></p><ul><li>This column represents the proportion of times the factor’s absolute IC value exceeds 0.03.</li><li>A higher proportion indicates a greater likelihood of the factor demonstrating stable correlations over time, confirming its predictive effectiveness across various periods.</li></ul><figure><img alt="阿爾法倫斯" src="https://cdn-images-1.medium.com/max/602/0*Mia33EDrwLXZ7ufS.png" /><figcaption>Average Returns By Factor Quantile (5-Day Change in Foreign Ownership Ratio)</figcaption></figure><figure><img alt="阿爾法倫斯" src="https://cdn-images-1.medium.com/max/602/0*FHgXfuP3CQOC8ybu.png" /><figcaption>Average Returns By Factor Quantile (5-Day Net Inflow)</figcaption></figure><ul><li><strong>Horizontal Axis:</strong> The horizontal axis represents the factor groups (Quantiles), which are divided into ten groups based on the size of the factor values. Group 1 contains the stocks with the lowest factor values, while Group 10 contains those with the highest.</li><li><strong>Vertical Axis:</strong> The vertical axis represents the average return of each group, measured in basis points (bps), which is one ten-thousandth of a percent. This value reflects the average return over a specific holding period (in this case, 1 day).</li><li><strong>Explanation:</strong> This chart illustrates the average return for each group during a one-day holding period. If the factor has predictive power, we generally expect the returns to show a monotonic trend, with Group 10 having higher average returns and Group 1 having lower average returns. This pattern can be used to construct a long-short portfolio.</li></ul><p>Based on the table “IC, IR Values, and Average Returns for Each Factor,” neither of these factors demonstrates strong IC or IR values. Generally, a good factor should have an IC greater than 0.05 and an IR greater than 0.3. Therefore, these two factors show a low correlation with asset returns and need more stable predictive ability.<br>The “Average Returns by Factor Quantile Bar Chart “ also shows that these two factors are unable to effectively predict or indicate asset return trends. Typically, in the bar chart, we aim to see monotonicity in the factor, meaning that larger factor values correlate with higher returns or smaller factor values correlate with lower returns. Factors with this characteristic can support the construction of investment strategies with more stable and consistent returns.</p><h3>Factor Synthesis</h3><p>In the previous section, we observed that the predictive effectiveness of the “5-day holding proportion change” and “5-day net inflow” factors was suboptimal. Therefore, this section will attempt to synthesize these two factors and examine whether the predictive power improves after synthesis.</p><h3>Calculating Factor Weights</h3><p>When synthesizing multiple factors, assigning appropriate weights to each factor is crucial due to their varying explanatory power for future returns. Proper weighting enhances both the predictive performance and stability of the composite factor.</p><p>In this article, <strong>rank IC_IR</strong> is used to calculate factor weights. The <strong>rank IC_IR</strong> is determined by dividing the IR ratio of an individual factor (calculated over the past month) by the sum of the IR ratios for all factors. This provides the relative weight of each factor. Based on risk-adjusted IC, this weighting method assigns greater weight to factors with higher predictive power and stability.</p><p>To simulate the delay of factor signals in real-world trading, the final weight data is <strong>lagged</strong> (shifted) by one day. This ensures that only data from the previous period is used, thereby avoiding the use of future information in the model.</p><p>This approach aligns the synthesized factor with practical trading scenarios, improving its robustness and applicability in real-world investment strategies.</p><figure><img alt="阿爾法倫斯" src="https://cdn-images-1.medium.com/max/375/0*xrOoh2qdOqfq263O.png" /><figcaption>Daily Factor Weight</figcaption></figure><h3>Factor Synthesis Methodology</h3><p>Calculating the composite factor involves generating a single composite factor by taking a weighted average of each factor based on its assigned weight, representing the overall effect of all aspects.</p><p>Detailed Steps:</p><ol><li><strong>Align Data: </strong>First, align the raw factor data with the index of the weight data. Fill any missing values with 0 to ensure data completeness.</li><li><strong>Weight Factors: </strong>Calculate each factor’s weighted value by multiplying its raw value by the corresponding pre-computed weight.</li><li><strong>Compute the Weighted Average: </strong>Specifically, the weighted average is calculated by multiplying each factor’s original value by its corresponding weight and then summing these values to produce the composite factor.</li><li><strong>Resulting Composite Factor: </strong>The composite factor generated through this process accounts for the relative importance of each factor, providing a more stable predictive effect in multi-factor strategies.</li></ol><p>Using this method, the composite factor reflects the relative significance of the individual factors and their collective predictive power, enhancing stability and effectiveness in multi-factor strategies.</p><figure><img alt="阿爾法倫斯" src="https://cdn-images-1.medium.com/max/438/0*2oGQIqQEoa6d_GMV.png" /><figcaption>Raw Factor Data</figcaption></figure><figure><img alt="阿爾法倫斯" src="https://cdn-images-1.medium.com/max/1024/0*0ZePwdwzYYbUiBHe.png" /><figcaption>Composite Factor Data</figcaption></figure><h3>Analysis of Composite Factors</h3><p>Similar to single-factor analysis, we will also import the new composite factor data into <strong>Alphalens</strong> for evaluation.</p><figure><img alt="阿爾法倫斯" src="https://cdn-images-1.medium.com/max/602/0*DL6WDVXqhuWPinRr.png" /><figcaption>Average Returns By Composite Factor Quantile</figcaption></figure><ul><li><strong>Horizontal Axis:</strong> Represents the quantiles (1 to 10), where higher quantiles indicate larger composite factor values.</li><li><strong>Vertical Axis:</strong> Represents the average return for each quantile in basis points (bps).</li><li><strong>Color Labels:</strong> Different colors indicate the holding periods, showing how the composite factor’s performance varies over time.</li></ul><figure><img alt="阿爾法倫斯" src="https://cdn-images-1.medium.com/max/602/0*d4N4VDeiRZI9XZeD.png" /><figcaption>Cumulative Returns By Holding Period</figcaption></figure><ul><li><strong>Horizontal Axis:</strong> Represents the years, showing the time evolution of cumulative returns.</li><li><strong>Vertical Axis:</strong> Displays the log cumulative returns, where higher values indicate greater accumulated returns.</li><li><strong>Color Labels:</strong> Different colored lines represent the cumulative returns for specific quantiles (e.g., Quantile 1, Quantile 5, Quantile 10).</li></ul><p>Due to the calculation method of cumulative returns in Alphalens, only the cumulative returns for a 1-day holding period are presented in the line chart. These charts show that the composite factor’s predictive power significantly surpasses that of the individual factors before synthesis.<br>The results show that the 10th quantile achieves the highest returns, while the 1st quantile has the lowest returns. Furthermore, the returns across quantiles exhibit a clear monotonic increasing trend.<br>Based on these findings, we can further explore constructing a long-short hedge portfolio by going long on stocks in the 10th and shorting stocks in the 1st quantile. This approach aims to maximize returns through effective portfolio hedging.</p><h3>Conclusion</h3><p>Through the analysis in this article, we demonstrated how to use Alphalens to evaluate factor performance and apply it in practical investment strategies. Initially, the IC and IR analyses of single factors revealed that the “5-day holding proportion change” and “5-day net inflow” factors performed poorly in predicting asset returns. The quantitative results also indicated a need for more stable monotonicity, making constructing effective long-short hedge strategies challenging. However, we observed a significant improvement in predictive power by synthesizing these factors into a composite factor.<br>In the composite factor analysis, a clear monotonic relationship between factor values and asset returns was evident, with higher quantiles achieving higher average returns. This monotonicity makes the composite factor well-suited for long-short hedge strategies, enhancing investment portfolios’ stability and return potential. Overall, this article illustrated the process from single-factor analysis to composite factor construction and backtesting, strengthening factor predictive power while reducing strategy risk to some extent.<br>In the future, practical applications could explore more advanced factor integration methods and alternative weight calculation approaches. Additionally, incorporating considerations such as slippage and transaction costs would further assess the strategy’s real-world feasibility. With these refinements, multi-factor strategies will be better equipped to adapt to market volatility and consistently create value in dynamic market environments!</p><p><strong>Start Building Portfolios That Outperform the Market!</strong></p><p><a href="https://www.tejwin.com/en/databank-solution/market-data/"><strong>TEJ Market Databank</strong></a></p><h3>Extended Reading</h3><ul><li><a href="https://www.tejwin.com/en/insight/seeking-alpha/">Seeking Alpha</a></li><li><a href="https://www.tejwin.com/en/insight/stock-selection-factors-research-combining-insider-ownership-and-momentum-factors/">Stock Selection Factors Research: Combining Insider Ownership and Momentum Factors</a></li></ul><h3>Relevant Links</h3><ul><li><a href="https://github.com/tejtw/TQuant-Lab">TQuant Lab Github</a></li><li><a href="https://tquant.tejwin.com/">TQuant Lab</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0153707908b9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tej-api-financial-data-anlaysis/financial-data-analysis-analyzing-factor-performance-with-alphalens-foreign-capital-factor-0153707908b9">【Financial Data Analysis】Analyzing Factor Performance with Alphalens: Foreign Capital Factor…</a> was originally published in <a href="https://medium.com/tej-api-financial-data-anlaysis">TEJ-API Financial Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【TEJ Dictionary】What is Day Trading ? TEJ Guides You Through The Basics From The Ground Up]]></title>
            <link>https://medium.com/tej-can-help/tej-dictionary-what-is-day-trading-tej-guides-you-through-the-basics-from-the-ground-up-15f4bb8e4cca?source=rss-6b49fe7bddc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/15f4bb8e4cca</guid>
            <category><![CDATA[tquant-lab]]></category>
            <category><![CDATA[day-trading]]></category>
            <category><![CDATA[tej-api]]></category>
            <category><![CDATA[tej]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[TEJ 台灣經濟新報]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 01:42:13 GMT</pubDate>
            <atom:updated>2025-02-06T01:42:13.681Z</atom:updated>
            <content:encoded><![CDATA[<h3>【TEJ Dictionary】What is Day Trading ? TEJ Guides You Through The Basics From The Ground Up</h3><p>Oct 02 2024</p><figure><img alt="Day Trading" src="https://cdn-images-1.medium.com/max/1024/0*qvIFjLKMpVuljgg9.jpg" /><figcaption>Photo by <a href="https://unsplash.com/@jp_shoots">Austin Distel</a> on <a href="https://unsplash.com/">unsplash</a></figcaption></figure><p>Preface</p><p>Have you ever heard friends excitedly discuss: “Today is perfect for day trading! Stock prices will have big intraday swings, hurry and jump in to make a profit!” Such enthusiasm might tempt you, but also leave you wondering: What exactly is day trading? Is it really that easy to make money, or is there hidden risk behind it?</p><p>Don’t worry, this article will unveil the mystery of day trading. TEJ will take you through the mechanisms and risks of day trading, and explain why this “buy and sell within a day” strategy attracts so many eager traders.</p><h3>What is Day Trading?</h3><p>In fact, “Day Trading” includes the meaning of “Same-Day write off “! The term “write off ” refers to offsetting positions, a common concept in accounting. For example, when a company finds an accounting entry was incorrect, it uses an offsetting entry to correct the mistake.</p><p>The concept of day trading is somewhat similar: In the stock market, day trading refers to buying and selling the same stock within the same trading day, either buying first and selling later, or selling first and buying later. In regular stock trading, you’re required to wait until the next trading day to sell after buying, which highlights the advantage of day trading.</p><h3>Does Day Trading Have Advantages? Why Do So Many Follow It?</h3><h3>No Capital Required</h3><p>In the day trading strategy, you don’t need to have cash or stock at the start. If your judgment is accurate, you can leverage market volatility to earn the spread.</p><p>For example, let’s say you believe a stock will drop today, and it is currently priced at NT$100 per share. You sell 100 shares, gaining NT$10,000 in cash. By the afternoon, the price drops to NT$95 per share, and you use the NT$10,000 to buy back the 100 shares for only NT$9,500. After subtracting your buyback cost, you’ve made NT$500. This is a classic “no-capital trade,” as you didn’t use your own money. Of course, in reality, you still need to consider transaction fees and liquidity.</p><p><strong>Half Tax Reduction</strong></p><p>To stimulate the stock market, the government introduced a policy halving the transaction tax. Normally, the transaction tax is 0.3% in Taiwan, but for day trading, it’s reduced to 0.15%. This significantly lowers trading costs, which is crucial for day traders, as day trading often involves high leverage, increasing transaction amounts and tax burden. If taxes are too high, they will gradually eat into profits, shrinking what could have been a good return. Thus, this tax reduction is a major benefit for day traders!</p><h3>What Are the Disadvantages of Day Trading?</h3><h3>High Time Investment</h3><p>Day trading requires close monitoring of market fluctuations and staying on top of trends. Professional day traders often watch 1-minute or 5-minute Candlestick, which consumes a lot of time and can be mentally exhausting. Sometimes, day traders are so focused that they barely have time for breaks during market hours. Moreover, the potential rewards are directly proportional to the risks, and trading costs like transaction fees and stock borrowing fees can add up.</p><h3>Lack of Risk Awareness</h3><p>Traders with insufficient capital often resort to no-capital day trading, which can lead to overlooking risks. Given their limited ability to bear losses, this can result in failed settlements or credit issues. If unfortunate Credit Default Swap, brokers can charge up to 7% of the transaction value as a penalty, and pursue debt recovery and related costs. Such defaults will leave a mark on the defaulter’s credit record, making it harder to get a credit card or mortgage in the future.</p><p><strong>Limited Stock Selection</strong></p><p>In Taiwan, Day trading is restricted to stocks that are part of the Taiwan Stock Exchange’s “FTSE TWSE Taiwan 50 Index,” the “TSEC Taiwan Mid-Cap 100 Index,” and the Taipei Exchange’s “TPEx 50 Index.”</p><p>Additionally, stocks that undergo trading method changes, disciplinary actions, or are listed on the Innovation Board or registered on the Strategic New Board are not eligible for day trading.</p><h3>Types and Qualifications for Day Trading</h3><p>Given the inherent risks of day trading, the Taiwan Stock Exchange (TWSE) only allows investors with sufficient trading experience to engage in day trading. Day trading is further divided into <strong>regular stock day trading</strong> and <strong>margin day trading</strong>, where margin refers to margin financing and short selling, which carries higher risks compared to regular stock trading. Therefore, the qualifications are stricter. Below are the qualifications based on<a href="https://www.twse.com.tw/en/products/system/day-trading.html"> TWSE regulations</a>:</p><h3>Regular Stock Day Trading</h3><ul><li>The trading account must have been open for at least three months.</li><li>At least 10 completed trades within the past year.</li><li>Day trader must sign a “General Authorization Agreement” and a “Risk Disclosure Statement” with the brokerage firm in advance.</li></ul><h3>Margin Day Trading</h3><ul><li>The trading account must have been open for at least three months.</li><li>At least 10 completed trades within the past year.</li><li>The total trading amount in the past year must exceed NT$250,000.</li><li>The investor must open a margin account.</li></ul><p><strong>Note</strong>: The tax reduction benefit only applies to regular stock day trading, not margin day trading.</p><h3>Does Day Trading Really Make Money?</h3><figure><img alt="Day Trading" src="https://cdn-images-1.medium.com/max/1024/0*xOt5tduf-0TrUEdc.png" /><figcaption>TPEx Day Trading Statistics</figcaption></figure><p>Does day trading really generate profit? The answer varies from person to person. However, looking at the data from the Taipei Exchange (TPEx), in 2023, the total amount bought in day trading was NT$7.33 trillion, while the total amount sold was NT$7.34 trillion. At first glance, the return seems positive, but let’s break down the fees and taxes:</p><ul><li><strong>Purchase</strong>: NT$7,333,678,450,980 * 0.1425% = NT$10,450,491,793</li><li><strong>Sale</strong>: NT$7,347,038,506,870 * (0.1425% + 0.15%) = NT$21,490,087,633</li><li><strong>Total cost</strong>: NT$7,333,678,450,980 + NT$10,450,491,793 + NT$21,490,087,633 = NT$7,365,619,030,406</li><li><strong>Net earnings</strong>: NT$7,347,038,506,870 — NT$7,365,619,030,406 = -NT$18,580,523,536</li></ul><p>Based on this data, we can roughly see that the majority of people lose money when engaging in day trading. Of course, if you can secure lower transaction fees from a broker, your chances of making a profit may increase slightly. However, day trading remains a highly speculative and risky activity, and investors should evaluate it carefully.</p><p>Does calculating all these fees manually sound exhausting? Don’t worry, TEJ has already organized everything for you! Just log into<strong> </strong>TEJ PRO<strong> </strong>and select “Day Trading Statistics” from the capital database, and you’ll have access to all the relevant data. The data is updated daily before 10 PM, with additional filtering options to make finding the information you need even easier!</p><figure><img alt="Day Trading" src="https://cdn-images-1.medium.com/max/1024/0*WJFhhBnZ_cVpi0JO.png" /><figcaption>TEJ PRO Day Trading Statistics</figcaption></figure><p><a href="https://tquant.tejwin.com/">TQuant Lab｜一站式量化研究，打造專屬於你的投資研究金鑰</a></p><h3>Conclusion</h3><p>Day trading has undeniably increased market activity, boosting the liquidity of many stocks. This article has explained that day trading offers advantages such as tax reductions and the ability to trade without significant capital. However, making money through day trading requires attention to many factors, especially considering that the daily movement of Taiwan’s stock market is often limited. In this context, transaction fees and taxes play a critical role in profitability. Ultimately, day trading is a high-risk strategy and one of the most challenging approaches, requiring careful consideration of market conditions, intraday information releases, and technical analysis.</p><h3>Further Reading</h3><ul><li>More Day Trading Legislation</li><li><a href="https://www.selaw.com.tw/English/LawArticle/Index/62550">TWSE Day Trading Section</a></li><li><a href="https://www.tpex.org.tw/web/stock/trading/intraday_stat/intraday_trading_stat.php?l=en-us">Taipei Exchange (TPEx) Intraday Trading Statistics</a></li><li>More Articles on Financial Knowledge</li><li><a href="https://www.tejwin.com/en/insight/what-is-odd-lot-trading/">What Is Odd Lot Trading? TEJ Guides You Through The Basics From The Ground Up</a></li><li><a href="https://www.tejwin.com/en/?post_type=insight&amp;p=27973">What are treasury stocks? TEJ will tell you treasury stocks’ advantages, disadvantages, and inquiry channels.</a></li><li>More about TEJ Financial Data</li><li><a href="https://www.tejwin.com/en/insight/financial-data-sourcing-strategic-guide/">Mastering the Dynamics of Financial Data Sourcing: A Strategic Guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15f4bb8e4cca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tej-can-help/tej-dictionary-what-is-day-trading-tej-guides-you-through-the-basics-from-the-ground-up-15f4bb8e4cca">【TEJ Dictionary】What is Day Trading ? TEJ Guides You Through The Basics From The Ground Up</a> was originally published in <a href="https://medium.com/tej-can-help">TEJ Dictionary</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【TEJ知識集】庫藏股是什麼？公司為何而買？TEJ 告訴你庫藏股優缺點及查詢管道]]></title>
            <link>https://medium.com/tej-%E7%9F%A5%E8%AD%98%E9%9B%86/tej%E7%9F%A5%E8%AD%98%E9%9B%86-%E5%BA%AB%E8%97%8F%E8%82%A1%E6%98%AF%E4%BB%80%E9%BA%BC-%E5%85%AC%E5%8F%B8%E7%82%BA%E4%BD%95%E8%80%8C%E8%B2%B7-tej-%E5%91%8A%E8%A8%B4%E4%BD%A0%E5%BA%AB%E8%97%8F%E8%82%A1%E5%84%AA%E7%BC%BA%E9%BB%9E%E5%8F%8A%E6%9F%A5%E8%A9%A2%E7%AE%A1%E9%81%93-0620b2bf610b?source=rss-6b49fe7bddc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0620b2bf610b</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[tej-api]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tej]]></category>
            <category><![CDATA[medium]]></category>
            <dc:creator><![CDATA[TEJ 台灣經濟新報]]></dc:creator>
            <pubDate>Tue, 21 Jan 2025 09:11:41 GMT</pubDate>
            <atom:updated>2025-01-21T09:11:41.438Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="庫藏股" src="https://cdn-images-1.medium.com/max/817/1*oOr7Il03Xp4hd5F_5Z_Jkg.png" /><figcaption>Photo by <a href="https://www.shutterstock.com/zh-Hant/g/Armsamui">Primrose89</a> on <a href="https://www.shutterstock.com/zh-Hant/image-photo/miniature-peoplebusinessman-gathered-around-stack-thai-1083353861">shutterstock</a></figcaption></figure><p>你是否曾經聽過某某公司，正要買回庫藏股，因此身邊友人開始呼喊大家：「趕緊一起加入買方的行列，股票就要水漲船高了，現在不入場何時該入場！」你有想過他為什麼會這樣講嗎 ? 而庫藏股是什麼跟流通在外股票有什麼不同？公司為什麼要買回庫藏股？</p><p>別擔心， TEJ 台灣經濟新報將帶你從頭認識庫藏股是什麼、優缺點，以及如何查詢庫藏股的相關資訊！</p><h3>庫藏股是什麼？跟流通在外股票有什麼不同？</h3><p>在介紹庫藏股之前，先帶大家認識台灣一家公司在申請上市時，公司的實收資本額必須需達新台幣 6 億元以上，且募集發行普通股股數達 3000 萬股以上。成功上市或上櫃後，這些股票將會流通到我們平常下單的股市也就是<a href="https://zh.wikipedia.org/zh-tw/%E4%BA%8C%E7%BA%A7%E5%B8%82%E5%9C%BA">次級市場</a>，成為所謂的「<strong>流通在外股票</strong>」！</p><p>那庫藏股票是什麼呢 ? 簡單來說，庫藏股<strong>（Treasury stock）就是公司使用現金回購自家的股票</strong>！想像一下，公司就像是一位喜歡自家商品的店主，看到商品賣得不錯，就會選擇買回一些。這樣做的原因有很多，比如提升每股盈利、增加股東價值，或者是公司認為自己的股票被低估了，想逢低買入。</p><p>當公司宣布要拿錢買回自家股票，而被回購的股票未進行註銷時就稱之為庫藏股。當公司宣布庫藏股計劃時，他們通常會設置一個購買上限，但實際上回購多少呢？這就涉及到<strong>執行率</strong>啦！執行率就是實際回購的股票數量佔計劃總量的比例。如果執行率高，表示公司積極回購；如果低，則可能是公司對市場行情有所保留。</p><h3>公司為什麼要買回庫藏股？</h3><p>公司買回庫藏股，通常有以下幾個常見目的：</p><h3>1.作為穩定資本結構的利器！</h3><p>當公司回購自家的股票，這些股票就會被收錄在公司帳戶內，並且可以隨時被用來轉換成以下金融工具，如：配合附認股權公司債、附認股權特別股、<strong>可轉換公司債（Convertible Bond )</strong>、<strong>可轉換特別股（Convertible preferred stock）</strong>或認股權憑證。為什麼會這樣呢？其實，不論是特別股、公司債還是權證，通常都會有一些特別的轉換選項，讓持有人可以將這些金融工具與公司兌換成普通股，如果找到合適的轉換時機，就可以將持有人的利益最大化！而公司為了避免轉換時產生虧損，就會事前先回購股票，作為轉換的來源。</p><p>這種做法不僅可以避免虧損，更使公司可以用庫藏股靈活調整資本結構，並確保市場流動性，進一步提升投資者的信心。因此，庫藏股成為一種公司在面對市場波動時，靈活應對各種狀況的利器！</p><h3>2.激勵員工士氣，解決代理人問題！</h3><p>公司可以將回購的庫藏股作為員工獎勵的一部分，像是股票選擇權或是員工分紅，這樣做不僅讓員工感受到自己的努力得到公司的重視，還會對公司的未來更有信心，更加投入工作，與公司一起成長，因為他們知道有機會分享公司成長的成果，同時也可以有效地解決公司與員工之間的「代理人問題」。</p><h3>3.守護公司自主權，抵抗併購的護身符</h3><p>最後，庫藏股還可以是一項保護公司自主權的重要工具！當市場中出現潛在的敵意併購風險時，公司可以選擇回購自家股票，減少流通在外的股數，進而提升內部股東的持股比例，強化管理層的控制權。有效避免外部投資人藉由大量持股來進行併購或改變公司管理層。</p><p>在這樣的情況下，庫藏股成為了抵禦外來威脅的“護身符”，保護公司免受惡意併購的干擾，同時也讓管理層能夠將更多資源專注於公司的長期成長與價值創造。</p><h3>公司買回庫藏股我該注意些什麼？</h3><figure><img alt="庫藏股" src="https://cdn-images-1.medium.com/max/898/1*1K9rqLX3_hqknDPzrX8ooA.png" /><figcaption>庫藏股注意事項的示意圖</figcaption></figure><p>公司回購庫藏股到底是好還是不好呢？在買完後，投資人還需要仔細考量什麼因素：</p><h3>1.資金流動性的隱憂</h3><p>當公司決定回購庫藏股時，往往需要投入大量現金。這種資金的支出可能會影響公司的流動資金運用，特別是在短期內，公司現金流可能變得更加緊張。如果回購規模較大，公司可能需要重新調整資金分配，甚至壓縮其他營運或投資項目，以確保資金可以支持庫藏股的回購計畫。</p><p>此外，當市場環境不穩定或公司營運需要資金時，持有大量庫藏股反而可能帶來壓力。因此，公司在決策回購前，通常需要仔細評估現金流狀況，以避免影響核心業務的正常運行或無法應對突發的資金需求。</p><h3>2. 股價回升後的風險</h3><p>當公司宣布回購庫藏股計畫，市場往往會對此解讀為利多消息，認為公司股價被低估，因此可能出現股價上漲。然而，這種由庫藏股帶動的上漲屬於短期效應，並不一定能長期維持。如果公司的經營狀況未見改善，業績無法支撐股價的增長，那麼股價在一段時間後可能會出現回落。</p><p>投資者在這種情況下需要謹慎，因為回購行為所傳遞的市場信號在短期內有助於提升股價，但只有公司的財務數據和經營基本面向好，才能真正支持股價穩定向上。否則，一旦市場熱情消退，股價可能會回歸到與公司實際經營狀況相符的水平，甚至可能低於回購前的價格，讓短期的「回購效應」淪為曇花一現。</p><h3>庫藏股常見問題</h3><p>上面提了這麼多庫藏股能發揮的作用後，那你知道公司在購買庫藏股時需要注意什麼事情呢？以下整理一些庫藏股常見的問題，為你提供解答！</p><h3>1.庫存股買回價格如何制定？有限制嗎？</h3><p>首先，上市櫃公司必須依據「<a href="https://law.moj.gov.tw/LawClass/LawAll.aspx?pcode=G0400061">上市上櫃公司買回本公司股份辦法</a>」向金管會申報並公告買回股份之相關訊息，並且輸入至公開資訊觀測站資訊系統。<strong>公告的內容</strong>須包含：買回股份之目的、種類、總金額上限、預定買回之期間與數量、買回之區間價格及買回方式等。</p><p>那其中，買回的價格該如何制定是市場所關注的重點！ 公司在設定買回區間價格時，需要考慮很多因素，比如當前的股價、近期股價的平均值和波動情況、公司買回股票的原因，以及計劃回購的時間等等。這些考量能幫助公司避免設定過於不合理的價格範圍，避免誤導投資者。</p><p>依據金管會建議經考量上述因素，所定買回<strong>區間價格</strong>介於董事會決議前 10 個營業日或 30 個營業日之<strong>平均收盤價</strong>（二者取高）之 <strong>150％</strong>與董事會<strong>決議當日收盤價之 70％間</strong>為適。如果公司在買回股票時，發現股價<strong>超出了設定的區間</strong>，無論是高於還是低於區間，公司都必須<strong>停止回購</strong>。不過，公司可以重新評估後，再次修正區間價格並進行公告，然後繼續回購。但如果董事會早就決議「股價低於區間下限時仍繼續買回」，那就可以例外！</p><h3>2.庫藏股買回期間需要公告進度嗎？</h3><p>是的！當公司買回的股票數量達到已發行<strong>股份總數的 2%</strong>或金額達到新台幣 <strong>3 億元</strong>時以上其中一項條件時，即應於事實發生之即日起算 <strong>2 日內</strong>，由公司進行公告！而且後續買回的股票再次累積達到相同的標準（再累積 2% 或 3 億元），公司也需要再次公告。因此在買回期間，公司要不斷地向外界報告進度，讓大家都能跟上庫藏股的最新動態！另外若在執行期間未執行完畢，依據「<a href="https://law.moj.gov.tw/LawClass/LawAll.aspx?pcode=G0400061">上市上櫃公司買回本公司股份辦法</a>」第五條規定，須重新依照董事會決議再行買回，故仍須依規定公告、申報。</p><h3>3.庫藏股多久要註銷？</h3><p>根據《<a href="https://law.moj.gov.tw/LawClass/LawSingle.aspx?pcode=G0400001&amp;flno=28-2">證券交易法</a>》第 28 條之 2 的規定，當公司回購庫藏股時，必須在回購後的 5 年內把這些股份轉讓給員工。如果 5 年內沒有轉讓，這些股份就會被視為未發行股份，並需要進行變更登記。</p><h3>庫藏股怎麼買? 2 大管道告訴你！</h3><p>投資者如何得知公司有庫藏股的消息呢？其實有兩個主要管道可以獲取相關資訊。</p><h3>庫藏股查詢管道 1：公開資訊觀測站</h3><p>最常見的作法當然是到<a href="https://mops.twse.com.tw/mops/web/index">公開資訊觀測站</a>直接尋找！點選公開資訊觀測站「投資專區」→「庫藏股資訊專區」選項下的「庫藏股統計彙總表」，就可以看到前項所說的目的、種類、總金額上限、預定買回之期間與數量等庫藏股相關的基本資訊！</p><figure><img alt="庫藏股" src="https://cdn-images-1.medium.com/max/1024/1*_YYP5QjZ9qp1ogByTOhoBg.jpeg" /><figcaption>公開資訊觀測站的庫藏股資料</figcaption></figure><h3>庫藏股查詢管道 2：TEJ PRO</h3><p>如果想利用庫藏股對公司股價進行更詳密的分析，可以至 <a href="https://www.tejwin.com/service-provide-method/">TEJ PRO</a> 查詢！只要登入 TEJ PRO，點選上市櫃+曾經上市櫃公司資料庫中的「庫藏股資料」，你就能輕鬆獲得所有相關更詳細的資料，相比公開資訊觀測站的基本資料外，TEJ 還提供實際買回的起迄日、決議時已持有股數 ( % ) 、本次申請金額占流動資產 ( % ) 等，可以安心使用 TEJ 的數據來進行量化分析，讓你的實驗結果更加準確！</p><p>而 TEJ 的資料每天晚上 10 點前更新，還提供期間條件查詢功能，讓你更加方便地篩選所需的交易資訊！</p><figure><img alt="庫藏股" src="https://cdn-images-1.medium.com/max/1024/1*EdrCCvv2MiOB5q8DfJDorg.jpeg" /><figcaption>TEJ 庫藏股資料</figcaption></figure><h3>最友善的金融數據工具｜TEJ 資料庫</h3><p>透過本文的介紹，你應該了解到庫藏股不僅僅是公司的一種投資策略，更是一種靈活應對市場變動、提升公司價值、激勵員工士氣的多功能工具。然而，庫藏股也有其風險，特別是在資金流動性和短期股價波動方面。因此，投資者在看到公司宣布庫藏股計劃時，應該綜合考量公司背後的動機和市場情況，而不是盲目跟風。</p><p><a href="https://tquant.tejwin.com/?source=post_page-----78a3a4b005a3--------------------------------">TQuant Lab｜一站式量化研究，打造專屬於你的投資研究金鑰</a></p><h3>延伸閱讀</h3><ul><li>更多庫藏股相關法規：</li><li><a href="https://www.fsc.gov.tw/fckdowndoc?file=/%E5%BA%AB%E8%97%8F%E8%82%A1%E7%96%91%E7%BE%A9%E5%95%8F%E7%AD%94%E5%BD%99%E6%95%B4%E7%89%88(108_4_25%E6%96%B0%E5%A2%9E%E7%AC%AC%E4%BA%8C%E5%8D%81%E4%B9%9D%E4%B9%8B%E4%B8%80%E9%A1%8C)(1).pdf&amp;flag=doc">庫藏股疑義問答彙整版</a></li><li><a href="https://law.moj.gov.tw/LawClass/LawAll.aspx?pcode=G0400061">上市上櫃公司買回本公司股份辦法</a></li><li>更多關於財金知識的文章：</li><li><a href="https://www.tejwin.com/insight/%E3%80%90tej%E7%9F%A5%E8%AD%98%E9%9B%86%E3%80%91%E8%91%A3%E7%9B%A3%E4%BA%8B%E9%85%AC%E5%8B%9E/">透過董監事酬勞，揪出企業肥貓！</a></li><li><a href="https://www.tejwin.com/insight/%E9%9B%B6%E8%82%A1%E4%BA%A4%E6%98%93%E6%98%AF%E7%94%9A%E9%BA%BC%EF%BC%9F/">零股交易是什麼？ TEJ 帶你從零開始認識</a></li><li>更多關於 TEJ 金融數據的介紹：</li><li><a href="https://www.tejwin.com/insight/%E5%A6%82%E4%BD%95%E6%89%BE%E5%88%B0%E5%A5%BD%E7%9A%84%E9%87%91%E8%9E%8D%E6%95%B8%E6%93%9A%E4%BE%86%E6%BA%90/">找不到好的金融數據來源？一文搞懂取得高品質數據的關鍵！</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0620b2bf610b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tej-%E7%9F%A5%E8%AD%98%E9%9B%86/tej%E7%9F%A5%E8%AD%98%E9%9B%86-%E5%BA%AB%E8%97%8F%E8%82%A1%E6%98%AF%E4%BB%80%E9%BA%BC-%E5%85%AC%E5%8F%B8%E7%82%BA%E4%BD%95%E8%80%8C%E8%B2%B7-tej-%E5%91%8A%E8%A8%B4%E4%BD%A0%E5%BA%AB%E8%97%8F%E8%82%A1%E5%84%AA%E7%BC%BA%E9%BB%9E%E5%8F%8A%E6%9F%A5%E8%A9%A2%E7%AE%A1%E9%81%93-0620b2bf610b">【TEJ知識集】庫藏股是什麼？公司為何而買？TEJ 告訴你庫藏股優缺點及查詢管道</a> was originally published in <a href="https://medium.com/tej-%E7%9F%A5%E8%AD%98%E9%9B%86">TEJ 知識集</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【Application】Differences Among TEJ API, TEJ Tool API, and TQuant Lab]]></title>
            <link>https://medium.com/tej-api-financial-data-anlaysis/application-differences-among-tej-api-tej-tool-api-and-tquant-lab-78a3a4b005a3?source=rss-6b49fe7bddc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/78a3a4b005a3</guid>
            <category><![CDATA[tej-api]]></category>
            <category><![CDATA[tquant]]></category>
            <category><![CDATA[tej]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tejapi-application]]></category>
            <dc:creator><![CDATA[TEJ 台灣經濟新報]]></dc:creator>
            <pubDate>Tue, 21 Jan 2025 05:32:05 GMT</pubDate>
            <atom:updated>2025-01-21T05:32:05.271Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="TEJ API" src="https://cdn-images-1.medium.com/max/1024/0*L-PuDbrVwG3tNKgi.jpg" /><figcaption>Photo from <a href="https://www.pexels.com/zh-tw/photo/356079/">Pexels</a></figcaption></figure><h3>Introduction:</h3><p>TEJ (Taiwan Economic Journal) is a renowned financial information service platform in Taiwan. It provides a wide range of data and analysis tools covering various aspects such as economics, finance, stock markets, bond markets, and futures. With its extensive database and professional analytical features, the TEJ platform is widely used by financial institutions, research units, and investors to access real-time, accurate market data and conduct in-depth data analysis to support decision-making.</p><p>As financial markets evolve and data analysis demands grow, TEJ offers diverse economic data services, enabling investors to better organize and analyze data in this era of big data, and even to engage in profitable asset trading.</p><p>Among TEJ’s many services and products, <strong>TEJ API</strong>, <strong>TEJ Tool API</strong>, and <strong>TQuant Lab</strong> are tools designed for data retrieval and analysis. While they all provide robust data integration tools and analysis capabilities, they differ in specific applications. This article will delve into the main features, usage scenarios, and advantages and disadvantages of these three tools, helping users better understand their distinctions and choose the most suitable one for their needs, ultimately enhancing efficiency in data analysis and investment decision-making.</p><h3>TEJ API:</h3><p>As mentioned above, TEJ focuses on acquiring diverse data from economic markets. From basic stock trading data to detailed accounting items, TEJ API encompasses a wide range of content. Users can retrieve specific stock data by selecting the desired database.</p><p><strong>Example:</strong>By specifying different databases, users can access various datasets. The following example demonstrates using the monthly revenue database (TWN/APISALE) to retrieve the monthly revenue data of Taiwanese companies for the period from January 1, 2024, to December 31, 2024.</p><pre>import tejapi<br>tejapi.ApiConfig.api_key =&#39;your tejapi key&#39;<br>tejapi.ApiConfig.api_base= &quot;your base&quot;<br>tejapi.ApiConfig.ignoretz = True<br>start_date = &#39;2024-01-01&#39;<br>end_date = &#39;2024-12-31&#39;<br>data = tejapi.get(&#39;TWN/APISALE&#39;,     #資料表代碼<br>                  paginate = True,<br>                  mdate={&#39;gte&#39;: start_date, &#39;lte&#39;: end_date},<br>                  chinese_column_name = True)<br>print(data)</pre><figure><img alt="TEJ API" src="https://cdn-images-1.medium.com/max/1024/0*eAcjKFWN41_bEQRo.png" /><figcaption>Output from python code</figcaption></figure><p>For details on the available databases, please refer to the following website: <a href="https://api.tej.com.tw/index.html">Website</a></p><p>TEJ API primarily provides comprehensive market data, offering single-point data access suitable for basic data analysis, simple data retrieval, and automation needs. It is highly beginner-friendly for those new to working with databases, making it an easy-to-use product for quick deployment.</p><h3>TEJ Tool API:</h3><p>Building upon an understanding of TEJ API, users can leverage various databases to access diverse data types. However, advanced data users often face the challenge of merging and processing multiple datasets, which requires aligning data by time and frequency. For example, when analyzing both monthly revenue and stock closing prices, users must address the frequency mismatch, as monthly revenue is monthly data while closing prices are daily data.</p><p>This is where <strong>TEJ Tool API</strong> comes into play. It provides services for integrating different types of data, enabling advanced users to skip the manual data consolidation process while ensuring accuracy.</p><p><strong>Example:</strong></p><p>Using the [ get_history_data ] function from TEJ Tool API, users can directly retrieve data for specified fields (as shown in the “columns” section of the illustration). This includes data spanning different frequency types, such as trading data (e.g., closing prices), accounting data (e.g., total liabilities), and financial ratios (e.g., current ratio). These datasets, originally of varying frequencies, can be seamlessly integrated into a single table using TEJ Tool API.</p><pre>import TejToolAPI<br><br>columns = [&#39;Industry&#39;, &#39;本益比&#39;, &#39;收盤價&#39;, &#39;流動比率&#39;, &#39;股東權益總計&#39;, &#39;負債總額&#39;, &#39;營收成長率&#39;,&#39;eps&#39;,&#39;mt_div&#39;,&#39;現金股利率&#39;]<br><br>start_dt = pd.Timestamp(&#39;2015-12-29&#39;, tz = &#39;UTC&#39;)<br>end_dt = pd.Timestamp(&#39;2024-12-31&#39;, tz = &quot;UTC&quot;)<br><br>data__ = TejToolAPI.get_history_data(start = start_dt,<br>                                  end = end_dt,<br>                                  ticker = pool,<br>                                  fin_type = &#39;A&#39;, # 為累計資料<br>                                  columns = columns,<br>                                  transfer_to_chinese = True)<br><br>data__[data__[&#39;股票代碼&#39;] == &#39;2330&#39;]</pre><figure><img alt="TEJ API" src="https://cdn-images-1.medium.com/max/1024/0*QAS-lwW07kPU8f4m.png" /><figcaption>Output from python code</figcaption></figure><p>For more information about the fields available in TEJ Tool API, please refer to the following website: <a href="https://tquant.tejwin.com/%e8%b3%87%e6%96%99%e9%9b%86/">Website</a></p><p>TEJ Tool API is designed for users requiring diverse data types. By using this API, users can save significant time in data handling. Moreover, in the process of analyzing data, issues such as look-ahead bias and survivorship bias often arise. TEJ Tool API addresses these issues by incorporating the announcement dates for each dataset, ensuring that analytical results remain unbiased, stable, and reliable.</p><h3>TQuant Lab:</h3><p>Given the abundance of financial and economic data provided by TEJ, savvy users may consider utilizing this data for quantitative trading analysis. <strong>TQuant Lab</strong> is a product developed precisely to meet such needs!</p><p>TQuant Lab offers professional backtesting tools and factor analysis modules. By integrating market trading information, it allows investors to implement their trading strategies using a simple programming framework. The platform builds upon the Zipline architecture (a well-established backtesting tool internationally), making it more streamlined and user-friendly for beginners in quantitative trading.</p><p>To cater to users of varying expertise levels, TQuant Lab provides a wide range of built-in factor analysis tools and indicators, including:</p><ul><li><strong>Factor Testing</strong></li><li><strong>Return Analysis</strong></li><li><strong>Fundamental Analysis</strong> (e.g., Price-to-Earnings Ratio, Price-to-Book Ratio)</li><li><strong>Technical Indicators</strong> (e.g., Moving Averages, Relative Strength Index)</li></ul><p>Users can also design and expand custom factors based on their strategy needs, achieving a high degree of customization. Additionally, TQuant Lab features a strategy performance evaluation module, enabling users to analyze portfolio risk and return characteristics, plot cumulative return graphs, leverage utilization charts, and more. Users can even optimize portfolio weights for enhanced efficiency.</p><p>With its user-friendly interface and powerful computational capabilities, TQuant Lab is accessible to both seasoned quantitative researchers and newcomers, helping them embark on their journey into quantitative trading.</p><p><strong>Illustration of Analysis Charts Supported by TQuant Lab:</strong></p><p><em>(You can add or create visual representations based on the mentioned features, such as cumulative return graphs, leverage charts, or factor analysis plots.)</em></p><figure><img alt="TQuant" src="https://cdn-images-1.medium.com/max/1024/0*n1wKK8As7v1cYbZ_.png" /><figcaption>TQuant Lab strategy charts</figcaption></figure><p>For instructional articles about TQuant Lab, please refer to : <a href="https://www.tejwin.com/insight/tquant-%e5%be%9e-0-%e5%88%b0-1-day-1-%e9%87%8f%e5%8c%96%e4%ba%a4%e6%98%93-%e6%8a%95%e8%b3%87%e7%ad%96%e7%95%a5/">Website</a></p><p>We regularly release related tutorials to guide users in leveraging the platform effectively.</p><p><strong>TQuant Lab Tutorial Examples : </strong><a href="https://tquant.tejwin.com/%e7%af%84%e4%be%8b%e6%95%99%e5%ad%b8/"><strong>Website</strong></a></p><p><a href="https://tquant.tejwin.com/">TQuant Lab｜一站式量化研究，打造專屬於你的投資研究金鑰</a></p><h3>Conclusion</h3><figure><img alt="TEJ API" src="https://cdn-images-1.medium.com/max/1024/1*4QG4Osn4n-Wo8GJGQMClMw.png" /><figcaption>Conclusion Table</figcaption></figure><h3>Further Reading</h3><ul><li><a href="https://www.tejwin.com/insight/program-trading/"><strong>What is Algorithmic Trading?</strong> Introduction to Algorithmic Trading, Its Pros and Cons, and Common Strategies — TEJ Taiwan Economic Journal</a></li><li><a href="https://www.tejwin.com/insight/tej-api-%e6%96%87%e4%bb%b6%e8%a7%a3%e8%aa%aa/"><strong>TEJ API Documentation Explanation</strong></a></li><li><a href="https://www.tejwin.com/insight/tej-rest-api-%e4%bd%bf%e7%94%a8%e6%89%8b%e5%86%8a/"><strong>TEJ REST API User Manual</strong></a></li><li><a href="https://www.tejwin.com/news/%e9%87%8f%e5%8c%96%e6%8a%95%e8%b3%87%e8%b2%a1%e5%8b%99%e8%b3%87%e6%96%99%e5%b0%8d%e4%ba%86%e5%97%8e-tej-%e9%87%8f%e5%8c%96%e6%8a%95%e8%b3%87%e6%9c%88%e5%a0%b1-2-%e6%9c%9f/"><strong>Quantitative Investing: Are Your “Financial Data” Correct?</strong> — TEJ Quantitative Investment Monthly Report, Issue 2</a></li><li><a href="https://www.tejwin.com/insight/https-www-tejwin-com-insight-tquant-lab-%e4%bd%bf%e7%94%a8%e6%95%99%e5%ad%b8-google-colab/"><strong>Running TQuant Lab on Google Colab: A Guide and Common Errors</strong></a></li></ul><h3>Related Links</h3><ul><li><a href="https://github.com/tejtw/TQuant-Lab"><strong>TQuant Lab GitHub</strong></a></li><li><a href="https://tquant.tejwin.com/"><strong>TQuant Lab Homepage</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78a3a4b005a3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tej-api-financial-data-anlaysis/application-differences-among-tej-api-tej-tool-api-and-tquant-lab-78a3a4b005a3">【Application】Differences Among TEJ API, TEJ Tool API, and TQuant Lab</a> was originally published in <a href="https://medium.com/tej-api-financial-data-anlaysis">TEJ-API Financial Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【實戰應用】TEJ API、TEJ Tool API 與 TQuant Lab 的差異說明]]></title>
            <link>https://medium.com/tej-api-%E9%87%91%E8%9E%8D%E8%B3%87%E6%96%99%E5%88%86%E6%9E%90/%E5%AF%A6%E6%88%B0%E6%87%89%E7%94%A8-tej-api-tej-tool-api-%E8%88%87-tquant-lab-%E7%9A%84%E5%B7%AE%E7%95%B0%E8%AA%AA%E6%98%8E-9400dc4c96d1?source=rss-6b49fe7bddc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9400dc4c96d1</guid>
            <category><![CDATA[backtest]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tej]]></category>
            <category><![CDATA[tquant]]></category>
            <category><![CDATA[tejapi實戰應用]]></category>
            <dc:creator><![CDATA[TEJ 台灣經濟新報]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 09:32:17 GMT</pubDate>
            <atom:updated>2025-01-14T09:32:17.621Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="TEJ API" src="https://cdn-images-1.medium.com/max/1024/0*P0a2Q-VW9ekZXWcC.jpg" /><figcaption>Photo from <a href="https://www.pexels.com/zh-tw/photo/356079/">Pexels</a></figcaption></figure><h3>前言：</h3><p>TEJ 是台灣知名的金融資訊服務平台，提供涵蓋各類經濟、金融、股市、債市、期貨等多元化資料和分析工具。TEJ平台以其豐富的數據庫和專業的分析功能，廣泛應用於金融機構、研究單位和投資者，幫助使用者獲取即時、準確的市場數據，並進行深度的數據分析與決策支持。</p><p>隨著金融市場和數據分析需求的日益增長，TEJ 提供了多元的經濟資料使用服務，幫助投資人在這個大數據時代可以更好的整理數據，並進行資料的分析使用，甚至進行有利可圖的資產交易。</p><p>在TEJ提供的眾多服務及產品中，TEJ API、TEJ Tool API 以及 TQuant Lab 是提供資料抓取及資料分析的產品，它們在提供強大數據串接工具和分析功能上各有特色，但在具體應用層面上也存在一定的差異。本篇文章將深入分析這三者的主要功能、使用場景及優缺點，幫助使用者更清楚地了解它們的區別，從而選擇最適合自身需求的工具，提升數據分析與投資決策的效率。</p><h3>TEJ API：</h3><p>如前述所說的，TEJ 致力於獲取經濟市場中的各種資料，從最基本的股票交易資料到很小的會計科目，都會收錄在TEJ API的產品內容中，讀者可以通過指定需要的資料庫來獲取對應的股票資料。</p><p>範例：</p><p>通過指定不同的資料庫，使用者可以獲取不同的資料，此範例就是使用月營收的資料庫（資料庫代號：’TWN/APISALE’），來獲取台灣公司的在2024–01–01至2024–12–31期間的月營收資料。</p><pre>import tejapi<br><br>tejapi.ApiConfig.api_key =&#39;your tejapi key&#39;<br>tejapi.ApiConfig.api_base= &quot;your base&quot;<br>tejapi.ApiConfig.ignoretz = True<br>start_date = &#39;2024-01-01&#39;<br>end_date = &#39;2024-12-31&#39;<br>data = tejapi.get(&#39;TWN/APISALE&#39;,     #資料表代碼<br>                  paginate = True,<br>                  mdate={&#39;gte&#39;: start_date, &#39;lte&#39;: end_date},<br>                  chinese_column_name = True)<br>print(data)</pre><figure><img alt="TEJ API" src="https://cdn-images-1.medium.com/max/1024/0*SaauN0yE3r3VKfkQ.png" /><figcaption>TEJ API 輸出示意圖</figcaption></figure><p>關於資料庫的種類說明，可以參考以下網站：<a href="https://api.tej.com.tw/index.html">https://api.tej.com.tw/index.html</a></p><p>TEJ API 主要提供完整的市場資料，提供單點的資料提供，適合進行簡單的資料分析，以及簡單的資料擷取和自動化需求。對於使用資料庫的初學者非常友善，屬於能快速上手使用的資料庫產品。</p><h3>TEJ Tool API：</h3><p>有了對於TEJ API的瞭解，讀者可以引用不同資料庫來獲取多元的數據類型。但對於進階的資料需求者，顯然使用TEJ API 的各種資料會需要進行多筆資料間的合併及處理，這之中就會需要對齊資料的時間以及資料頻率。像是如果需要同時分析月營收以及股票收盤價的情況，就需要考慮資料頻率的問題，因為月營收是月頻率資料而收盤價則是日頻率資料。</p><p>這就是為何會推出 TEJ Tool API 的產品服務，TEJ Tool API 提供不同類型的資料整合，讓進階資料需求者可以不用自行整理資料，同時確保資料的正確性。</p><p>範例：</p><p>利用 TEJ Tool API 的 get_history_data 函數，可以直接獲取指定欄位（圖中的 columns 部分）的資料，並且資料間是屬於不同類型的資料，像是圖中的呼叫出交易資料的收盤價、會計資料的負債總額以及財務比率的流動比率。這些原本屬於不同類型的資料，通過TEJ Tool API 可以很好的整合在同一張表格當中。</p><pre>import TejToolAPI<br><br>columns = [&#39;Industry&#39;, &#39;本益比&#39;, &#39;收盤價&#39;, &#39;流動比率&#39;, &#39;股東權益總計&#39;, &#39;負債總額&#39;, &#39;營收成長率&#39;,&#39;eps&#39;,&#39;mt_div&#39;,&#39;現金股利率&#39;]<br><br>start_dt = pd.Timestamp(&#39;2015-12-29&#39;, tz = &#39;UTC&#39;)<br>end_dt = pd.Timestamp(&#39;2024-12-31&#39;, tz = &quot;UTC&quot;)<br><br>data__ = TejToolAPI.get_history_data(start = start_dt,<br>                                  end = end_dt,<br>                                  ticker = pool,<br>                                  fin_type = &#39;A&#39;, # 為累計資料<br>                                  columns = columns,<br>                                  transfer_to_chinese = True)<br><br>data__[data__[&#39;股票代碼&#39;] == &#39;2330&#39;]<br></pre><figure><img alt="TEJ API" src="https://cdn-images-1.medium.com/max/1024/0*DDglJUhWsM0YxUzV.png" /><figcaption>TEJ Tool API 輸出結果示意圖</figcaption></figure><p>關於TEJ Tool API 的欄位說明可以參考以下網址：<a href="https://tquant.tejwin.com/%e8%b3%87%e6%96%99%e9%9b%86/">https://tquant.tejwin.com/%e8%b3%87%e6%96%99%e9%9b%86/</a></p><p>TEJ Tool API 主要提供給需要多類型資料的讀者，使用 TEJ Tool API 可以讓讀者在使用資料的過程中節省非常多的時間。與此同時，在研究資料時，常常會出現前視偏誤以及倖存者偏差的情況，而 TEJ Tool API 在整合資料時搭配每個資料的公告日，使得我們的分析結果不落入這樣的陷阱當中，並且提高分析結果的穩定性與可靠性。</p><h3>TQuant Lab：</h3><p>既然 TEJ 提供了這麼豐富的財金資料，聰明的讀者一定想到可以使用這些資料進行量化交易的分析，而 TQuant Lab 就是為了這樣的需求而誕生的產品！</p><p>TQuant Lab 提供專業的回測工具以及因子分析模組，通過整合市場的交易資訊，讓投資人可以用簡單的程式架構去實現心中的交易策略。TQuant Lab 延伸使用了Zipline 架構（在國外行之有年的回測工具），讓TQuant Lab 的架構能夠更加簡潔，對於初學量化交易的讀者使用起來更便利。</p><p>為了滿足不同層次用戶的需求，TQuant Lab 提供了多種內建因子分析工具，包括基本面分析（如本益比、股價淨值比）以及技術面因子（如移動平均、相對強弱指標）等。用戶也可以根據自己的策略需求，自行設計與擴展因子，實現高度的客製化。</p><p>此外，TQuant Lab 還內建了策略績效評估模組，用戶可以輕鬆分析投資組合的風險與報酬特性，繪製累計報酬圖、槓桿使用率圖表等等，甚至進一步優化投資組合權重。透過友善的界面與強大的運算能力，無論是資深的量化研究員還是剛入門的新手，都能夠快速上手並開始量化交易的旅程。</p><p>TQuant Lab 中支援的分析圖表示意圖：</p><figure><img alt="TQuant Lab" src="https://cdn-images-1.medium.com/max/1024/0*Vj2wD9DSWbeKCsGw.png" /><figcaption>TQuant Lab 提供的績效分析示意圖</figcaption></figure><p>有關TQuant Lab 的教學文章，請參考：<a href="https://www.tejwin.com/insight/tquant-%e5%be%9e-0-%e5%88%b0-1-day-1-%e9%87%8f%e5%8c%96%e4%ba%a4%e6%98%93-%e6%8a%95%e8%b3%87%e7%ad%96%e7%95%a5/">文章連結</a></p><p>我們會不定期的推出相關的教學文章。</p><p>TQuant Lab 策略範例：<a href="https://tquant.tejwin.com/%e7%af%84%e4%be%8b%e6%95%99%e5%ad%b8/">文章連結</a></p><h3>結論：</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HV9zGunHYeN1t_HdxaxBiw.png" /></figure><h3>延伸閱讀</h3><p><a href="https://www.tejwin.com/insight/program-trading/">程式交易是什麼？程式交易教學、優缺點及常見策略懶人包 — TEJ台灣經濟新報</a></p><p><a href="https://www.tejwin.com/insight/tej-api-%e6%96%87%e4%bb%b6%e8%a7%a3%e8%aa%aa/">TEJ API 文件解說</a></p><p><a href="https://www.tejwin.com/insight/tej-rest-api-%e4%bd%bf%e7%94%a8%e6%89%8b%e5%86%8a/">TEJ REST API 使用手冊</a></p><p><a href="https://www.tejwin.com/news/%e9%87%8f%e5%8c%96%e6%8a%95%e8%b3%87%e8%b2%a1%e5%8b%99%e8%b3%87%e6%96%99%e5%b0%8d%e4%ba%86%e5%97%8e-tej-%e9%87%8f%e5%8c%96%e6%8a%95%e8%b3%87%e6%9c%88%e5%a0%b1-2-%e6%9c%9f/">量化投資「財務資料」對了嗎？ — TEJ 量化投資月報 2 期</a></p><p><a href="https://www.tejwin.com/insight/https-www-tejwin-com-insight-tquant-lab-%e4%bd%bf%e7%94%a8%e6%95%99%e5%ad%b8-google-colab/">Google Colab 運行 TQuant Lab 使用教學及常見錯誤</a></p><h3>相關連結</h3><ul><li><a href="https://github.com/tejtw/TQuant-Lab">TQuant Lab Github</a></li><li><a href="https://tquant.tejwin.com/">TQuant Lab 首頁</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9400dc4c96d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tej-api-%E9%87%91%E8%9E%8D%E8%B3%87%E6%96%99%E5%88%86%E6%9E%90/%E5%AF%A6%E6%88%B0%E6%87%89%E7%94%A8-tej-api-tej-tool-api-%E8%88%87-tquant-lab-%E7%9A%84%E5%B7%AE%E7%95%B0%E8%AA%AA%E6%98%8E-9400dc4c96d1">【實戰應用】TEJ API、TEJ Tool API 與 TQuant Lab 的差異說明</a> was originally published in <a href="https://medium.com/tej-api-%E9%87%91%E8%9E%8D%E8%B3%87%E6%96%99%E5%88%86%E6%9E%90">TEJ-API 金融資料分析</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TQuant Lab Director And Supervisor Holdings — Which Strategy Reigns Supreme?]]></title>
            <link>https://medium.com/tej-api-financial-data-anlaysis/tquant-lab-director-and-supervisor-holdings-which-strategy-reigns-supreme-c7e07ac4d395?source=rss-6b49fe7bddc1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7e07ac4d395</guid>
            <category><![CDATA[backtesting]]></category>
            <category><![CDATA[strategy]]></category>
            <category><![CDATA[tejapi-application]]></category>
            <category><![CDATA[tquant]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[TEJ 台灣經濟新報]]></dc:creator>
            <pubDate>Thu, 09 Jan 2025 06:31:44 GMT</pubDate>
            <atom:updated>2025-01-09T06:31:44.457Z</atom:updated>
            <content:encoded><![CDATA[<h3>【Application】TQuant Lab Director And Supervisor Holdings — Which Strategy Reigns Supreme?</h3><figure><img alt="Director" src="https://cdn-images-1.medium.com/max/1024/0*2k1njvNAOAn7ely5" /></figure><h3>Key Highlights</h3><ul><li><strong>Article Difficulty</strong>： ★☆☆☆☆</li><li>Introduction to the impact of insider (directors and supervisors) holdings on stock performance.</li><li>Backtesting insider holding strategies using TQuant Lab to observe the effectiveness of momentum factors.</li></ul><h3>Preface</h3><p>In the stock market, the proportion of shares held by directors and supervisors has long been an important indicator for investors. Changes in insider holdings often signal their confidence in the company’s prospects, potentially influencing stock prices. However, identifying meaningful changes in insider holdings from vast amounts of data can be daunting for investors.<br>To address this, we use TQuant Lab to filter companies with significant changes in insider holding ratios and perform backtests. TQuant Lab enables us to quickly uncover potential correlations between management activity and stock price movements and to evaluate the strategy’s effectiveness, helping investors capture hidden opportunities in the market.<br>Are you curious about how to use insider holding ratios to predict stock trends and gain an edge in investing? Let’s dive in!</p><h3>Simple Stock Selection</h3><h3>Trading Logic</h3><p>We analyze insider holding changes using three strategies, backtesting data from <strong>January 1, 2020, to December 31, 2023</strong>. According to Article 25, Paragraph 2 of 《<a href="https://law.moj.gov.tw/ENG/LawClass/LawAll.aspx?pcode=G0400051"><strong>The Securities and Exchange Act</strong></a>》, insider holding ratios must be disclosed before the 15th of each month for the previous month. Therefore, we set the strategy rebalancing date to the 16th of each month to avoid look-ahead bias.</p><h3>Strategy Selection Criteria</h3><ol><li><strong>Holding Ratio Above 40%</strong>: Ensures insiders hold a significant proportion of shares, filtering for companies with high insider holdings.</li><li><strong>Top 30 Holding Ratios</strong>: Leverages the momentum effect by selecting the top 30 companies with the highest holding ratios to observe potential higher returns.</li><li><strong>Holding Ratio Increased for 2 Consecutive Months</strong>: Indicates that insiders have optimistic expectations for the company’s future, as shown by a sustained increase in their holdings.</li></ol><p>For simplicity, these are referred to as <strong>Strategies 1, 2, and 3</strong> throughout the article.</p><h3>Simulated Trading Costs</h3><p>To enhance the realism of the strategies, the model incorporates slippage and transaction fees to simulate the impact of price friction on trading outcomes.</p><h3>Editing Environment and Module Requirements</h3><p>This article uses the <strong>Windows 11 operating system</strong> with <strong>Visual Studio Code (VS Code)</strong> as the primary editor for analysis and writing.</p><p>The <strong>zipline-tej</strong> version used is <strong>2.0.0</strong>. Note that the article will focus on key sections of the code.</p><p>For the complete code, please refer to the project’s <strong>GitHub repository</strong>!</p><h3>Complete Backtesting Process</h3><h3>Import Required Packages</h3><pre>import os <br>import pandas as pd <br><br>os.environ[&#39;TEJAPI_KEY&#39;] = &quot;Yourkey&quot; <br>os.environ[&#39;TEJAPI_BASE&#39;] = &quot;https://api.tej.com.tw&quot; <br>from zipline.pipeline import Pipeline <br>from logbook import Logger, StderrHandler, INFO <br>log_handler = StderrHandler(format_string=&#39;[{record.time:%Y-%m-%d %H:%M:%S.%f}]: &#39; + <br>                            &#39;{record.level_name}: {record.func_name}: {record.message}&#39;, <br>                            level=INFO) <br>log_handler.push_application() <br>log = Logger(&#39;Algorithm&#39;)</pre><h3>Getting the Stock Pool</h3><p>In this step, we check whether the stock pool contains stocks with characteristics that do not meet the strategy’s requirements and make appropriate adjustments. The strategy’s selection range includes common and KY stocks (companies registered overseas but listed in Taiwan). Since smaller-cap companies typically have higher insider holding ratios, we did not limit the selection to Taiwan’s top 200 highly liquid stocks. This design allows for a more precise focus on small- and mid-cap stocks that meet the strategy’s criteria, thereby improving the strategy’s effectiveness.</p><pre>from zipline.sources.TEJ_Api_Data import get_universe<br>start = &#39;2020-01-01&#39;<br>end = &#39;2023-12-31&#39;<br><br>pool = get_universe(start, end, mkt = [&#39;TWSE&#39;, &#39;OTC&#39;], stktp_e =[&#39;Common Stock-Foreign&#39;, &#39;Common Stock&#39;])</pre><h3>Importing Stock Pool and Price-Volume Data</h3><p>The data period ranges from <strong>2020–01–01 to 2023–12–31</strong>. The selected stocks’ price-volume data and the weighted stock price return index (IR0001) are imported as the performance benchmark.</p><pre># Set environment variables to specify the backtesting time range and the selected stock pool.<br>start_dt = pd.Timestamp(start, tz=&#39;utc&#39;) <br>end_dt = pd.Timestamp(end, tz=&#39;utc&#39;) <br>tickers = &#39; &#39;.join(pool) <br>os.environ[&#39;mdate&#39;] = start+&#39; &#39;+end <br>os.environ[&#39;ticker&#39;] = tickers+&#39; IR0001&#39; <br>!zipline ingest -b tquant</pre><h3>Building Historical Data</h3><pre>import tejapi<br># Fetch director and supervisor shareholding data from the TWN/APIBSTN1 API<br>data = tejapi.fastget(<br>    &#39;TWN/APIBSTN1&#39;,<br>    coid=pool,<br>    mdate={&#39;gte&#39;: pd.Timestamp(start) - pd.DateOffset(months=3), &#39;lte&#39;: pd.Timestamp(end)},<br>    opts={&#39;columns&#39;: [&#39;coid&#39;, &#39;mdate&#39;, &#39;fld005&#39;, &#39;fld005l&#39;]},<br>    paginate=True<br>).rename(columns={<br>    &#39;fld005&#39;: &#39;Director_and_Supervisor_Holdings_Percentage&#39;,<br>    &#39;fld005l&#39;: &#39;Difference_in_Director_and_Supervisor_Holdings_Percentage_from_Previous_Period&#39;<br>})<br># Calculate `The_Month_Before_Last` (fld005l of the previous period)<br>shift_data = (<br>    data[[&#39;coid&#39;, &#39;mdate&#39;, &#39;Difference_in_Director_and_Supervisor_Holdings_Percentage_from_Previous_Period&#39;]]<br>    .rename(columns={&#39;Difference_in_Director_and_Supervisor_Holdings_Percentage_from_Previous_Period&#39;: &#39;The_Month_Before_Last&#39;})<br>)<br>shift_data[&#39;mdate&#39;] = shift_data[&#39;mdate&#39;] + pd.DateOffset(months=1)<br>data = data.merge(shift_data, on=[&#39;coid&#39;, &#39;mdate&#39;], how=&#39;left&#39;)<br># According to regulations, director and supervisor shareholding data must be disclosed by the 15th of each month for the previous month&#39;s data.<br># Therefore, adjust `mdate` to the 15th of the next month.<br>data[&#39;mdate&#39;] = data[&#39;mdate&#39;] + pd.DateOffset(months=1)<br>data[&#39;mdate&#39;] = data[&#39;mdate&#39;].apply(lambda x: x.replace(day=15))<br># Replace NA values with &#39;N/A&#39; to prevent forward-filling incorrect data<br>for i in [<br>    &#39;Director_and_Supervisor_Holdings_Percentage&#39;,<br>    &#39;Difference_in_Director_and_Supervisor_Holdings_Percentage_from_Previous_Period&#39;,<br>    &#39;The_Month_Before_Last&#39;<br>]:<br>    data[i] = np.where(data[i].isnull(), &#39;N/A&#39;, data[i])<br># Generate a DataFrame containing all calendar dates for each company<br>days = pd.date_range(pd.Timestamp(start) - pd.DateOffset(months=2), end).tolist()<br>df_tradeday = pd.DataFrame({<br>    &#39;coid&#39;: [tick for tick in pool for day in days],<br>    &#39;mdate&#39;: days * len(pool)<br>})<br># Merge the generated DataFrame with the API data, forward-fill missing values, and replace &#39;N/A&#39; back with np.nan<br>data = (<br>    df_tradeday<br>    .merge(data, on=[&#39;coid&#39;, &#39;mdate&#39;], how=&#39;left&#39;)<br>    .set_index([&#39;coid&#39;, &#39;mdate&#39;])<br>    .sort_index()<br>    .groupby([&#39;coid&#39;])<br>    .ffill()<br>    .reset_index()<br>    .replace({&#39;N/A&#39;: np.nan})<br>)</pre><h3>Transforming Data into the Required Pipeline Format</h3><pre>from zipline.data import bundles<br># Load the &#39;tquant&#39; bundle<br>bundle = bundles.load(&#39;tquant&#39;)<br>sids = bundle.asset_finder.equities_sids<br>assets = bundle.asset_finder.retrieve_all(sids)<br>symbol_mapping_sid = {i.symbol: i.sid for i in assets}<br># shift(1): Data announced on the 15th can only be used starting on the 16th to avoid look-ahead bias<br>transform_data = data.set_index([&#39;coid&#39;, &#39;mdate&#39;]).unstack(&#39;coid&#39;).shift(1)<br>transform_data = transform_data.rename(columns=symbol_mapping_sid)<br>transform_data.index = transform_data.index.tz_localize(&#39;UTC&#39;)<br>transform_data.tail()</pre><h3>Creating the CustomDataset Database</h3><p>After retrieving price-volume and historical data, we can use CustomDataset to assist in constructing the required trading signals. Since the data fields needed for Strategies 1 and 2 are identical, they can share the same CustomDataset, improving data processing efficiency and simplifying workflows.</p><p><strong>Strategies 1 and 2</strong></p><pre>from zipline.pipeline.data.dataset import Column, DataSet <br>from zipline.pipeline.domain import TW_EQUITIES <br>from zipline.pipeline.loaders.frame import DataFrameLoader <br>class CustomDataset(DataSet): <br>    Director_and_Supervisor_Holdings_Percentage = Column(dtype=float) <br>    domain = TW_EQUITIES <br>inputs=[CustomDataset.Director_and_Supervisor_Holdings_Percentage] <br>Custom_loader = {i:DataFrameLoader(column=i, baseline=transform_data[i.name]) for i in inputs} <br>Custom_loader</pre><p><strong>Strategies 3</strong></p><pre>from zipline.pipeline.loaders.frame import DataFrameLoader<br>from zipline.pipeline.data.dataset import Column, DataSet<br>from zipline.pipeline.domain import TW_EQUITIES<br>class CustomDataset(DataSet):<br>    Difference_in_Director_and_Supervisor_Holdings_Percentage_from_Previous_Period = Column(dtype=float)<br>    The_Month_Before_Last = Column(dtype=float)<br>    domain = TW_EQUITIES<br>inputs=[CustomDataset.Difference_in_Director_and_Supervisor_Holdings_Percentage_from_Previous_Period,<br>        CustomDataset.The_Month_Before_Last]<br>Custom_loader = {i:DataFrameLoader(column=i, baseline=transform_data[i.name]) for i in inputs}<br>Custom_loader</pre><h3>Generating Trading Signals</h3><p>Since the trading signals for the three strategies differ, they need to be configured separately. However, the fundamental settings of these strategies are consistent, allowing them to share the same underlying framework. This approach enhances setup efficiency and ensures consistency.</p><h4>Strategies 1</h4><p>def compute_signals():<br># Enable the Pipeline to display data corresponding to the specific date<br>Dire = CustomDataset.Director_and_Supervisor_Holdings_Percentage.latest</p><p># Filter Director_and_Supervisor_Holdings_Percentage_filter = (CustomDataset.Director_and_Supervisor_Holdings_Percentage.latest &gt; 40) # When the director and supervisor shareholding percentage is greater than 40, it returns True. return Pipeline(columns={ ‘Dire’: Dire, # Column for Director and Supervisor Holdings Percentage ‘longs’: Director_and_Supervisor_Holdings_Percentage_filter # Indicates stocks to go long when True }, ) # The algorithm will buy stocks where the “longs” column is True and exit positions where it is False.</p><h4>Strategies 2</h4><p>def compute_signals(): Dire = CustomDataset.Director_and_Supervisor_Holdings_Percentage.latest return Pipeline(columns={ ‘Dire’:Dire, ‘longs’ : Dire.top(30), }, )</p><h4>Strategies 3</h4><p>def compute_signals():<br># Retrieve the latest values for the two momentum factors<br>MOM1 = CustomDataset.Difference_in_Director_and_Supervisor_Holdings_Percentage_from_Previous_Period.latest<br>MOM2 = CustomDataset.The_Month_Before_Last.latest</p><p># Filter conditions<br>Difference_in_Director_and_Supervisor_Holdings_Percentage_from_Previous_Period_filter = \<br> (CustomDataset.Difference_in_Director_and_Supervisor_Holdings_Percentage_from_Previous_Period.latest &gt; 0)<br># Filter for MOM-1: True if the difference in director and supervisor shareholding percentage from the previous period is positive.</p><p>The_Month_Before_Last_filter = (CustomDataset.The_Month_Before_Last.latest &gt; 0)<br># Filter for MOM-2: True if the previous month’s difference in shareholding percentage is positive.</p><p># Combine the filters<br>mask = (Difference_in_Director_and_Supervisor_Holdings_Percentage_from_Previous_Period_filter &amp; The_Month_Before_Last_filter)<br># The mask will be True only if both MOM-1 and MOM-2 are positive, indicating consecutive monthly increases.</p><p>return Pipeline(columns={<br> ‘MOM-1’: MOM1, # MOM-1: Difference in director and supervisor shareholding percentage from the previous period<br> ‘MOM-1 Positive’: Difference_in_Director_and_Supervisor_Holdings_Percentage_from_Previous_Period_filter, # Whether MOM-1 is positive<br> ‘MOM-2’: MOM2, # MOM-2: Difference in shareholding percentage from two months ago<br> ‘MOM-2 Positive’: The_Month_Before_Last_filter, # Whether MOM-2 is positive<br> ‘longs’: mask, # Long signal: True if both MOM-1 and MOM-2 are positive<br> },<br>)</p><h3>Verify Pipeline Configuration</h3><p>Manually inspect the results of the Pipeline to ensure it aligns with the expected setup. If discrepancies are found, return to the <strong>compute_signals </strong>function to make necessary corrections. Here is a basic method to verify the Pipeline results:</p><pre>pipeline_result.query(&quot;longs == 1&quot;)</pre><figure><img alt="Director" src="https://cdn-images-1.medium.com/max/1024/0*Rn-Ts8oWZReEL0__.png" /><figcaption>Pipeline Results Using Strategy 3 as an Example</figcaption></figure><p>According to Article 25, Paragraph 2 of the Securities and Exchange Act, the shareholding ratio of directors and supervisors must be disclosed by the 15th of each month, reflecting data from the previous month. To avoid look-ahead bias, we have set the strategy rebalancing date to the 16th of each month.</p><pre># Retrieve all trading sessions<br>from zipline.utils.calendar_utils import get_calendar <br>cal = get_calendar(&#39;TEJ&#39;).all_sessions  # Get all sessions from the &#39;TEJ&#39; calendar<br>cal = cal[(cal &gt;= &#39;2020-01-01&#39;) &amp; (cal &lt;= &#39;2023-12-31&#39;)]  # Filter trading sessions to the desired date range<br># Calculate the distance of each trading day from the 16th of each month<br>cal = pd.DataFrame(cal).rename(columns={0: &#39;date&#39;})  # Convert calendar to a DataFrame and rename the column<br>cal[&#39;diff&#39;] = cal[&#39;date&#39;].transform(lambda x: x - pd.Timestamp(year=x.year, month=x.month, day=16, tz=&#39;UTC&#39;))<br># For each date, compute the difference between the trading day and the 16th of the corresponding month<br># Select rebalancing dates (the first trading day on or after the 16th of each month) and convert them to strings<br>tradeday = cal.groupby([cal[&#39;date&#39;].dt.year, cal[&#39;date&#39;].dt.month]) \<br>              .apply(lambda x: x[x[&#39;diff&#39;].ge(pd.Timedelta(days=0))].head(1)).date.tolist()<br># Group trading days by year and month, and find the first trading day where the difference from the 16th is &gt;= 0<br>tradeday = [str(i.date()) for i in tradeday]  # Convert the selected dates to string format</pre><h3>Conduct a simple backtest using Algo</h3><p>Set the initial capital to 1,000,000 and do not use leverage.</p><pre>from zipline.algo.pipeline_algo import *<br>algo = TargetPercentPipeAlgo(<br>    start_session=start_dt,<br>    end_session=end_dt,<br>    capital_base=1e6,<br>    tradeday=tradeday,<br>    max_leverage=1,<br>    slippage_model=slippage.VolumeShareSlippage(volume_limit=0.15, price_impact=0.01),<br>    pipeline=compute_signals,<br>    custom_loader = Custom_loader<br>)<br>results = algo.run()</pre><h3>Conducting Performance Evaluation with Pyfolio</h3><pre>from pyfolio.utils import extract_rets_pos_txn_from_zipline<br>import pyfolio as pf<br><br># Extract returns, positions, and transactions from the backtest results<br>returns, positions, transactions = extract_rets_pos_txn_from_zipline(results)<br>benchmark_rets = results.benchmark_return  # Extract the benchmark&#39;s returns<br># Generate all available charts provided by Pyfolio<br>pf.tears.create_full_tear_sheet(<br>    returns=returns,<br>    positions=positions,<br>    transactions=transactions,<br>    benchmark_rets=benchmark_rets<br>)</pre><h4>Strategies 1</h4><figure><img alt="Director" src="https://cdn-images-1.medium.com/max/1024/0*VSavrFWYANfYk9T9.jpg" /></figure><h4>Strategies 2</h4><figure><img alt="Director" src="https://cdn-images-1.medium.com/max/1024/0*p81MqOVPwy92tfYy.jpg" /></figure><h4>Strategies 3</h4><figure><img alt="Director" src="https://cdn-images-1.medium.com/max/1024/0*1JvH7GvIjQAnOWSG.jpg" /></figure><p>From the data shown above, the annual returns of the three strategies are 15.145%, 17.988%, and 20.04%, respectively, all outperforming the market benchmark (14.931%). However, upon examining the trend charts, it can be observed that the performance of the three strategies remained either flat or even lagged behind the benchmark for most of the time before 2022. It wasn’t until 2022 that they gradually began to recover. In the future, extending the observation period could help analyze whether the performance of this investment strategy differs significantly between bull and bear markets, identifying the strategy’s strengths and weaknesses across different market cycles.<br>In addition to the raw returns, the risk-adjusted returns highlight the strategies’ performance. The Sharpe ratios of the three methods are 0.99, 1.17, and 1.28, respectively, exceeding the benchmark (0.86). Similarly, the Sortino ratios of the three strategies are 1.26, 1.56, and 1.68, outperforming the benchmark (1.22). These figures indicate that Strategies 2 and 3 perform better in terms of returns and risk-adjusted returns.</p><h4>Strategies 1</h4><figure><img alt="Director" src="https://cdn-images-1.medium.com/max/1024/0*KFilLI2qJkPKrxfq.png" /></figure><h4>Strategies 2</h4><figure><img alt="Director" src="https://cdn-images-1.medium.com/max/1024/0*kZ1yfgKnb_NhJxiy.png" /></figure><h4>Strategies 3</h4><figure><img alt="Director" src="https://cdn-images-1.medium.com/max/1024/0*hKzPNknmdpJN-DHx.png" /></figure><p>From the chart above, it can be observed that the number of months with negative returns for the three strategies is 15, 16, and 16, respectively, all fewer than the benchmark’s 20 months. Having fewer months of losses compared to the benchmark helps to alleviate psychological pressure on investors.</p><h4>Strategies 1</h4><figure><img alt="Director" src="https://cdn-images-1.medium.com/max/1024/0*n9SRJh6Ny_5LWSLp.png" /></figure><h4>Strategies 2</h4><figure><img alt="Director" src="https://cdn-images-1.medium.com/max/1024/0*1m6ANYcM7xTnTq1s.png" /></figure><h4>Strategies 3</h4><figure><img alt="Director" src="https://cdn-images-1.medium.com/max/1024/0*pce5lcITB_mbWOIA.png" /></figure><p>Further observation of the portfolio allocation over time for the top 10 holdings in each strategy reveals that the average exposure to a single stock is approximately 0.004, 0.035, and 0.0125, respectively. This indicates that there is no risk of excessive concentration in individual stocks. Additionally, users can adjust the number of holdings according to their preferences to conduct further testing.</p><h4>Strategies 1</h4><figure><img alt="Director" src="https://cdn-images-1.medium.com/max/855/0*k-ghAin0Fr-FGzqq.png" /></figure><h4>Strategies 2</h4><figure><img alt="Director" src="https://cdn-images-1.medium.com/max/861/0*NaB7sriBcmc2uUeA.png" /></figure><h4>Strategies 3</h4><figure><img alt="Director" src="https://cdn-images-1.medium.com/max/864/0*6zu6ZYMrLJh_F84S.png" /></figure><p>Finally, regarding maximum drawdown (MDD), the MDD for each strategy is -30.345%, -22.702%, and -27.511%, respectively. Only Strategies 2 and 3 outperform the market benchmark (28.553%). From the chart of the five most significant drawdowns, it can be observed that the periods of maximum drawdown occurred during the COVID-19 pandemic in 2020. Regarding drawdown duration, the maximum drawdown periods for the strategies are 273, 266, and 160 days, all shorter than the benchmark (359 days).</p><h3>Conclusion</h3><p>From the results of the three strategies, it is evident that the risk and return characteristics vary across different methods. Strategies 2 and 3 demonstrate the best performance in terms of both raw returns and risk-adjusted returns, with Strategy 2 having the most negligible maximum drawdown. Overall, the strategies constructed using director and supervisor shareholding ratios outperform the market regarding returns, with Sharpe ratios close to or exceeding 1. This indicates that director and supervisor shareholding ratios exhibit a certain degree of predictive power.<br>Among the three strategies, Strategies 2 and 3 are both worth considering. However, the specific entry and exit conditions can be tailored to individual investor preferences and extended using TQuant Lab tools. This example serves as a simple demonstration.<br>TQuant Lab provides a convenient factor testing environment, making the selection, testing, and backtesting of director and supervisor shareholding ratio strategies more intuitive. By applying this tool in practical investment processes, investors can more confidently explore the potential market opportunities brought by changes in director and supervisor shareholding ratios, thereby enhancing the scientific basis of investment decision-making.</p><p><a href="https://tquant.tejwin.com/">TQuant Lab｜一站式量化研究，打造專屬於你的投資研究金鑰</a></p><h3>Source Code</h3><ul><li><a href="https://github.com/tejtw/TEJAPI_Python_Medium_Application/blob/main/%E8%91%A3%E7%9B%A3%E6%8C%81%E8%82%A1%E7%AD%96%E7%95%A51-%E9%AB%98%E6%8C%81%E8%82%A1%E8%91%A3%E7%9B%A3.ipynb">Strategies 1 Github</a></li><li><a href="https://github.com/tejtw/TEJAPI_Python_Medium_Application/blob/main/%E8%91%A3%E7%9B%A3%E6%8C%81%E8%82%A1%E7%AD%96%E7%95%A52-%E6%8E%92%E5%90%8D%E5%89%8D30%E8%91%A3%E7%9B%A3.ipynb">Strategies 2 Github</a></li><li><a href="https://github.com/tejtw/TEJAPI_Python_Medium_Application/blob/main/%E8%91%A3%E7%9B%A3%E6%8C%81%E8%82%A1%E7%AD%96%E7%95%A53-%E5%85%A9%E6%9C%88%E9%80%A3%E5%A2%9E%E8%91%A3%E7%9B%A3.ipynb">Strategies 3 Github</a></li></ul><h3>Extended Reading</h3><ul><li><a href="https://www.tejwin.com/en/insight/stock-selection-factors-research-combining-insider-ownership-and-momentum-factors/">S</a><a href="https://www.tejwin.com/en/?post_type=insight&amp;p=26698"><strong>tock Selection Factors Research: Combining Insider Ownership and Momentum Factors</strong></a></li><li><a href="https://www.tejwin.com/en/insight/algorithmic-trading-sinopac-api/">A</a><a href="https://www.tejwin.com/en/insight/running-tquant-lab-in-google-colab/"><strong>lgorithmic Trading Guide：Leveraging TQuant Lab Strategies with the SinoPac API for Automated Trading</strong></a></li></ul><h3>Useful Links</h3><ul><li><a href="https://github.com/tejtw/TQuant-Lab">TQuant Lab GitHub</a></li><li><a href="https://tquant.tejwin.com/">TQuant Lab Official Website</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7e07ac4d395" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tej-api-financial-data-anlaysis/tquant-lab-director-and-supervisor-holdings-which-strategy-reigns-supreme-c7e07ac4d395">TQuant Lab Director And Supervisor Holdings — Which Strategy Reigns Supreme?</a> was originally published in <a href="https://medium.com/tej-api-financial-data-anlaysis">TEJ-API Financial Data Analysis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>