{"id":40690,"date":"2025-10-23T14:00:00","date_gmt":"2025-10-23T06:00:00","guid":{"rendered":"https:\/\/www.tejwin.com\/?post_type=insight&#038;p=40690"},"modified":"2026-03-03T13:09:37","modified_gmt":"2026-03-03T05:09:37","slug":"golden-cross-futures-trading-strategy","status":"publish","type":"insight","link":"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/","title":{"rendered":"Golden Cross Futures Trading Strategy\uff08MTX\uff09"},"content":{"rendered":"\n<figure class=\"wp-block-image aligncenter size-full is-resized is-style-default\"><img fetchpriority=\"high\" decoding=\"async\" width=\"406\" height=\"268\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.21.38.png\" alt=\"\" class=\"wp-image-40522\" style=\"width:800px;height:auto\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.21.38.png 406w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.21.38-300x198.png 300w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.21.38-150x99.png 150w\" sizes=\"(max-width: 406px) 100vw, 406px\" \/><figcaption class=\"wp-element-caption\">Photo by <a href=\"https:\/\/unsplash.com\/@moneyphotos?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash\" target=\"_blank\" rel=\"noopener\">rc.xyz NFT gallery<\/a> on <a href=\"https:\/\/unsplash.com\/photos\/a-pile-of-money-sitting-on-top-of-a-wooden-floor-o-MyHqEEHoM?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash\" target=\"_blank\" rel=\"noopener\">Unsplash<\/a><\/figcaption><\/figure>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_81 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a05e21c5ba16\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"ez-toc-cssicon\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a05e21c5ba16\"  aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/#Introduction\" >Introduction<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/#Practical_Applications\" >Practical Applications<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/#Investment_Targets_and_Backtesting_Period\" >Investment Targets and Backtesting Period<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/#Core_Logic\" >Core Logic<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/#1_Indicator_System\" >1. Indicator System<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/#2_Filter_Mechanism_Core_Risk_Management\" >2. Filter Mechanism (Core Risk Management)<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/#3_Entry_Logic_Executed_Only_When_Filter_OFF\" >3. Entry Logic (Executed Only When Filter = OFF)<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/#4_Exit_and_Risk_Management\" >4. Exit and Risk Management<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/#5_Contract_Rolling\" >5. Contract Rolling<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/#Trading_Flowchart\" >Trading Flowchart<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/#Strategy_Features\" >Strategy Features<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/#Package_Import\" >Package Import<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/#Data_Processing\" >Data Processing<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/#Conclusion\" >Conclusion<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/#GitHub_Source_Code\" >GitHub Source Code<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/#Further_Reading\" >Further Reading<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/www.tejwin.com\/en\/insight\/golden-cross-futures-trading-strategy\/#Related_Links\" >Related Links<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Introduction\"><\/span>Introduction<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The concept of the&nbsp;<strong>Moving Average (MA)<\/strong>&nbsp;originates from the&nbsp;<strong>Dow Theory<\/strong>&nbsp;developed in the early 20th century. Dow Theory emphasizes that markets exhibit trends, and such trends can be observed through price movements themselves. However, in the early days, price data was highly volatile and lacked smoothing tools. Analysts therefore began using the average price over a certain period to reduce random noise\u2014this marked the beginning of the moving average.<\/p>\n\n\n\n<p>With advancements in statistics and computer computation, the moving average gradually became one of the most fundamental technical indicators in quantitative trading. From the&nbsp;<strong>Simple Moving Average (SMA)<\/strong>&nbsp;and&nbsp;<strong>Exponential Moving Average (EMA)<\/strong>&nbsp;to more sophisticated variants such as the&nbsp;<strong>Double Exponential Moving Average (DEMA)<\/strong>&nbsp;and&nbsp;<strong>Hull Moving Average (HMA)<\/strong>, all these improvements aim to address the inherent&nbsp;<strong>lag<\/strong>&nbsp;problem of traditional moving averages, allowing them to reflect price trends more quickly or more smoothly.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Practical_Applications\"><\/span><strong>Practical Applications<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In practice, moving average strategies are widely used across different markets:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Single Moving Average Breakout:<\/strong>&nbsp;The price breaking above or below a long-term moving average (such as the 200-day MA) is used to determine bullish or bearish conditions.<\/li>\n\n\n\n<li><strong>Dual Moving Average Crossover:<\/strong>&nbsp;The crossover between short-term and long-term moving averages serves as an entry or exit signal.<\/li>\n\n\n\n<li><strong>Multiple Moving Average Alignment:<\/strong>&nbsp;The arrangement of multiple MAs indicates whether the market is in a bullish or bearish configuration, helping to confirm the strength of a trend.<\/li>\n\n\n\n<li><strong>Integration with Risk Management:<\/strong>&nbsp;Moving average signals are often combined with stop-loss rules, volatility filters, or other conditions to enhance robustness.<\/li>\n<\/ul>\n\n\n\n<p>Among these, the most representative examples are the&nbsp;<strong>Golden Cross<\/strong>&nbsp;and&nbsp;<strong>Death Cross<\/strong>. When a short-term moving average crosses above a long-term moving average, it is often regarded as the beginning of a bullish trend; conversely, when it crosses below, it signals a potential bearish trend. However, relying solely on crossover signals in a sideways or choppy market can lead to false breakouts. Therefore, in practice, traders often incorporate layered stop-loss mechanisms, volatility filters, and futures rollover adjustments to improve the strategy\u2019s feasibility and stability.<\/p>\n\n\n\n<p>This strategy, built within the&nbsp;<strong>Golden Cross framework<\/strong>, integrates&nbsp;<strong>trailing stop-losses<\/strong>&nbsp;and&nbsp;<strong>dynamic filtering<\/strong>&nbsp;for risk management, and applies&nbsp;<strong>continuous contract data<\/strong>&nbsp;to handle futures rollovers, ensuring consistency between backtesting and live trading performance.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Investment_Targets_and_Backtesting_Period\"><\/span>Investment Targets and Backtesting Period<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Instrument:<\/strong>&nbsp;Mini Taiwan Stock Index Futures (<strong>MTX<\/strong>, continuous contract)<\/li>\n\n\n\n<li><strong>Data Frequency:<\/strong>&nbsp;Daily (closing price)<\/li>\n\n\n\n<li><strong>Benchmark:<\/strong>&nbsp;Taiwan Capitalization Weighted Stock Index Total Return (<strong>IR0001<\/strong>)<\/li>\n\n\n\n<li><strong>Backtesting Period:<\/strong>&nbsp;2020-01-02 to 2025-09-26<\/li>\n\n\n\n<li><strong>Contract Rollover:<\/strong>&nbsp;Continuous contract constructed using&nbsp;<strong>calendar roll<\/strong>&nbsp;with&nbsp;<strong>adjustment = add<\/strong>, ensuring performance continuity across contract expirations.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Core_Logic\"><\/span>Core Logic<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"1_Indicator_System\"><\/span>1. Indicator System<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The strategy identifies market trends using&nbsp;<strong>MA3<\/strong>&nbsp;and&nbsp;<strong>MA10<\/strong>.<br>A&nbsp;<strong>Golden Cross<\/strong>&nbsp;serves as the&nbsp;<strong>buy trigger<\/strong>, while a&nbsp;<strong>Death Cross<\/strong>&nbsp;acts as the&nbsp;<strong>exit signal<\/strong>.<br>To reduce noise, a&nbsp;<strong>1.0001 buffer condition<\/strong>&nbsp;is applied in the program, requiring the short-term moving average to be significantly higher than the long-term moving average before confirming a Golden Cross.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"2_Filter_Mechanism_Core_Risk_Management\"><\/span>2. Filter Mechanism (Core Risk Management)<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Activation condition:<\/strong>&nbsp;When the benchmark\u2019s 2-day decline is&nbsp;<strong>\u2264 \u22125%<\/strong>, the filter turns&nbsp;<strong>ON<\/strong>.<\/li>\n\n\n\n<li><strong>Deactivation conditions (as currently implemented):<\/strong><\/li>\n\n\n\n<li><strong>Market rebound:<\/strong>&nbsp;When the benchmark\u2019s 2-day gain is&nbsp;<strong>\u2265 +5%<\/strong>, the filter turns&nbsp;<strong>OFF<\/strong>.<\/li>\n\n\n\n<li><strong>Automatic deactivation:<\/strong>&nbsp;The filter automatically turns&nbsp;<strong>OFF<\/strong>&nbsp;after being active for&nbsp;<strong>200 days<\/strong>.<br><strong>When the filter is ON:<\/strong><\/li>\n\n\n\n<li>Any existing position is&nbsp;<strong>immediately liquidated<\/strong>&nbsp;(forced exit).<\/li>\n\n\n\n<li>After liquidation, the system must&nbsp;<strong>wait 5 trading days<\/strong>&nbsp;before entering again (same cooldown as stop-loss).<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"3_Entry_Logic_Executed_Only_When_Filter_OFF\"><\/span>3. Entry Logic (Executed Only When Filter = OFF)<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Golden Cross Buy Rule:<\/strong>\uff1a\n<ul class=\"wp-block-list\">\n<li>Condition: (MA3[-2] &lt; MA10[-2]) and (MA3[-1] &gt; MA10[-1] * 1.0001)<\/li>\n\n\n\n<li>Action: Open full position with 1.8x leverage<\/li>\n\n\n\n<li>Restriction: If the previous exit was due to stop-loss or forced liquidation, wait 5 days before re-entry<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"4_Exit_and_Risk_Management\"><\/span>4. Exit and Risk Management<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>When the Filter is ON:<\/strong><\/li>\n\n\n\n<li>Any open position is&nbsp;<strong>forcefully closed<\/strong>&nbsp;immediately.<\/li>\n\n\n\n<li><strong>When the Filter is OFF:<\/strong>\n<ol class=\"wp-block-list\">\n<li>Stop-loss Conditions:\n<ul class=\"wp-block-list\">\n<li>1-day return &lt; \u22125%<\/li>\n\n\n\n<li>5-day return &lt; \u221210%<\/li>\n\n\n\n<li>10-day return &lt; \u221215%<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Death Cross Exit: (MA3[-2] &gt; MA10[-2]) and (MA3[-1] &lt; MA10[-1]) \u2192 Close position<\/li>\n\n\n\n<li><span style=\"white-space: normal;\">Time Stop:<\/span>\uff1aClose the position if it has been held for more than&nbsp;<strong>200 days<\/strong>.<\/li>\n<\/ol>\n<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"5_Contract_Rolling\"><\/span>5. Contract Rolling<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The strategy uses&nbsp;<strong>continuous MTX contracts<\/strong>&nbsp;to automatically handle rollovers, preventing price discontinuities and performance distortions caused by contract expiration.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Trading_Flowchart\"><\/span>Trading Flowchart<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code># Trading Flowchart\n\nAt each daily close \u2192 Update filter status  \n\u251c\u2500 Is the filter OFF?  \n\u2502  \u2514\u2500 No (Filter = ON)  \n\u2502     \u251c\u2500 Have position \u2192 Force close (start 5-trading-day cooldown)  \n\u2502     \u2514\u2500 No position \u2192 No entry  \n\u2514\u2500 Yes (Filter = OFF)  \n   \u251c\u2500 Have position  \n   \u2502  \u251c\u2500 Stop-loss (1D\/5D\/10D) \u2192 Close (start 5-day cooldown)  \n   \u2502  \u251c\u2500 Death Cross \u2192 Close  \n   \u2502  \u251c\u2500 Holding &gt; 200 days \u2192 Close  \n   \u2502  \u2514\u2500 Otherwise \u2192 Continue holding  \n   \u2514\u2500 No position  \n      \u251c\u2500 (If in cooldown) \u2192 No entry; cooldown \u22121  \n      \u251c\u2500 Golden Cross (with 1.0001 buffer) \u2192 Enter full position (leverage 1.8\u00d7)  \n      \u2514\u2500 Else \u2192 No entry\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Strategy_Features\"><\/span>Strategy Features<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Dynamic Risk Management:<\/strong>&nbsp;The filter enhances capital protection during sharp market declines by enforcing&nbsp;<strong>forced liquidation (ON)<\/strong>&nbsp;and a&nbsp;<strong>5-day cooldown period<\/strong>&nbsp;before re-entry.<\/li>\n\n\n\n<li><strong>Noise Reduction:<\/strong>&nbsp;The Golden Cross condition includes a&nbsp;<strong>MA10[-1] * 1.0001<\/strong>&nbsp;buffer to minimize false breakouts and avoid noise trading.<\/li>\n\n\n\n<li><strong>Multi-Layered Exit Protection:<\/strong>&nbsp;Combines&nbsp;<strong>three-tier stop-loss<\/strong>,&nbsp;<strong>technical indicators<\/strong>, and&nbsp;<strong>time-based stops<\/strong>&nbsp;for comprehensive downside risk control.<\/li>\n\n\n\n<li><strong>Strict Risk Execution:<\/strong>&nbsp;When the filter is triggered, all positions are&nbsp;<strong>immediately closed<\/strong>, preventing exposure to tail-risk drawdowns.<\/li>\n\n\n\n<li><strong>Rollover Consistency:<\/strong>&nbsp;Continuous contracts ensure consistency and interpretability between&nbsp;<strong>backtesting<\/strong>&nbsp;and&nbsp;<strong>live trading<\/strong>&nbsp;performance.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Package_Import\"><\/span>Package Import<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>#%% Setup\n\nticker1 = 'IR0001 IX0001'\nticker2 = 'MTX MSCI NYF'\n\n# \u74b0\u5883\u8b8a\u6578\nimport os\nimport sys\n# import time  # \u672a\u4f7f\u7528\nimport yaml\n\n''' ------------------- \u4e0d\u4f7f\u7528 config.yaml \u7ba1\u7406 API KEY \u7684\u4f7f\u7528\u8005\u53ef\u4ee5\u5ffd\u7565\u4ee5\u4e0b\u7a0b\u5f0f\u78bc -------------------'''\nnotebook_dir = os.path.dirname(os.path.abspath(__file__)) if '__file__' in globals() else os.getcwd()\nyaml_path = os.path.join(notebook_dir, '..', 'config.yaml')\nyaml_path = os.path.abspath(os.path.join(notebook_dir, '..', 'config.yaml'))\nwith open(yaml_path, 'r') as tejapi_settings: config = yaml.safe_load(tejapi_settings)\n''' ------------------- \u4e0d\u4f7f\u7528 config.yaml \u7ba1\u7406 API KEY \u7684\u4f7f\u7528\u8005\u53ef\u4ee5\u5ffd\u7565\u4ee5\u4e0a\u7a0b\u5f0f\u78bc -------------------'''\n\n# --------------------------------------------------------------------------------------------------\nos.environ&#91;'TEJAPI_BASE']   = config&#91;'TEJAPI_BASE'] # = \"https:\/\/api.tej.com.tw\"\nos.environ&#91;'TEJAPI_KEY']    = config&#91;'TEJAPI_KEY']  # = \"YOUR_API_KEY\"\n# --------------------------------------------------------------------------------------------------\nos.environ&#91;'ticker']        = ticker1\nos.environ&#91;'future']        = ticker2\nos.environ&#91;'mdate']         = '20180101 20251002'\n!zipline ingest -b tquant_future\n\n# \u6578\u64da\u5206\u6790\u5957\u4ef6\nimport warnings\nimport numpy as np  \nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\nfrom logbook import Logger, StderrHandler, INFO\n\n\n# tquant \u76f8\u95dc\u5957\u4ef6\n# import tejapi  \n# import TejToolAPI  \nimport zipline\nimport pyfolio as pf\n\nfrom zipline.utils.calendar_utils import get_calendar\nfrom zipline.utils.events import date_rules, time_rules\nfrom zipline.finance.commission import (\n    PerContract\n)\nfrom zipline.finance.slippage import (\n    FixedSlippage\n)\nfrom zipline import run_algorithm\n\nfrom zipline.api import (\n    record, \n    schedule_function,\n    set_slippage, \n    set_commission, \n    order_value,\n    set_benchmark, \n    symbol, \n    get_datetime,\n    date_rules, \n    time_rules, \n    continuous_future\n)\nfrom pyfolio.utils import extract_rets_pos_txn_from_zipline\n\n# logbook \u8a2d\u5b9a\nwarnings.filterwarnings('ignore')\nprint(sys.executable)\nprint(sys.version)\nprint(sys.prefix)\n\nlog_handler = StderrHandler(\n    format_string = (\n        '&#91;{record.time:%Y-%m-%d %H:%M:%S.%f}]: ' +\n        '{record.level_name}: {record.func_name}: {record.message}'\n    ),\n    level=INFO\n)\nlog_handler.push_application()\nlog = Logger('Algorithm')\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Data_Processing\"><\/span>Data Processing<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>\n\n#%% Strategy 1.3\n\n# \u76ee\u524d\u6700\u8b9a\u7684\u7248\u672c\u7684\u4fee\u6539\u7248 + \u6ffe\u7db2\u5929\u6578\u9650\u5236\n'''========================================================================================='''\n\n# \u7b56\u7565\u53c3\u6578\n#---------------------------------------------------------------------------------------------\n'''\n\u672a\u89f8\u767c\u6ffe\u7db2\u6642 MA3 &amp; MA10 \u9ec3\u91d1\u4ea4\u53c9 =&gt; \u8cb7\u9032(\u5168\u5009\uff0c\u69d3\u687f 1.8\u500d)\uff0c\u6ffe\u7db2\u958b\u555f or \u6b7b\u4ea1\u4ea4\u53c9 or \u89f8\u767c\u505c\u640d\u689d\u4ef6 or \u8d85\u904e\u6301\u6709\u5929\u6578 =&gt; \u5e73\u5009\n'''\n# \u5747\u7dda\u53c3\u6578\nSHORT_MA = 3\nLONG_MA = 10\n\n# \u505c\u640d\u53c3\u6578\nMAX_HOLD_DAYS = 200\nSTOPLOSS_1D = 5\nSTOPLOSS_5D = 10\nSTOPLOSS_10D = 15\n\n# \u6ffe\u7db2\u53c3\u6578\n\nFILLTER_ON_ACCDAY = 2\nFILLTER_OF_ACCDAY = 3\n\nFILLTER_ON_TRIGGER = -5\nFILLTER_OF_TRIGGER = 5\nFILLTER_AUTO_OFF_DAYS = 200  # \u6ffe\u7db2\u958b\u555f\u5f8c\u81ea\u52d5\u95dc\u9589\u5929\u6578\n\n# \u69d3\u687f\u53c3\u6578\nLEVERAGE = 1.8\nMAX_LEVERAGE = LEVERAGE + 0.05\n\n# \u5176\u4ed6\nMTX_CONTRACT_MULTIPLIER = 50    # \u5c0f\u53f0\u4e58\u6578\uff08\u8acb\u4f9d\u4f60\u884c\u60c5\u7cfb\u7d71\u8a2d\u5b9a\uff09\nCAPITAL_BASE = 1e6\nSTART_DT = pd.Timestamp('2020-01-02', tz='utc')\nEND_DT   = pd.Timestamp('2025-09-26', tz='utc')\n\nprint(f'\u6700\u5927\u69d3\u687f\uff1a{MAX_LEVERAGE} \u500d')\nprint(\"&#91;Trading log---------------]: ----------------------------- | signal ----- |action|Original posi| Note\")\n#---------------------------------------------------------------------------------------------\n\ndef initialize(context):\n    set_benchmark(symbol('IR0001'))\n\n    set_commission(\n        futures=PerContract(\n            cost          = {'MTX': 15},\n            exchange_fee  = 0\n        )\n    )\n\n    set_slippage(\n        futures=FixedSlippage(spread=1.0))\n\n    # set_max_leverage(MAX_LEVERAGE)\n\n    context.asset = continuous_future('MTX', offset=0, roll='calendar', adjustment='add')\n    context.universe = &#91;context.asset]\n    context.in_position = False\n    context.hold_days = 0\n    context.wait_after_stoploss = 0\n    context.filter_triggered = 0  # \u6dfb\u52a0\u6ffe\u7db2\u72c0\u614b\u8b8a\u6578\n    context.filter_days = 0  # \u6ffe\u7db2\u958b\u555f\u5929\u6578\u8a08\u6578\u5668\n\n    schedule_function(ma_strategy, date_rules.every_day(), time_rules.market_close())\n\ndef ma_strategy(context, data):\n    # \u7372\u53d6\u8db3\u5920\u7684\u6b77\u53f2\u8cc7\u6599\n    hist = data.history(context.asset, &#91;'close'], bar_count=max(LONG_MA+2, 15), frequency='1d')\n    close = hist&#91;'close']\n    \n    # \u7372\u53d6\u57fa\u6e96\u6307\u6a19\u6b77\u53f2\u8cc7\u6599\n    benchmark_hist = data.history(symbol('IR0001'), &#91;'close'], bar_count=7, frequency='1d')\n    benchmark_close = benchmark_hist&#91;'close']\n    \n    # \u8a08\u7b97\u7b56\u7565\u7d2f\u8a08\u5831\u916c\n    return_1d  = (close.iloc&#91;-1] - close.iloc&#91;-2]) \/ close.iloc&#91;-2] * 100\n    return_5d  = (close.iloc&#91;-1] - close.iloc&#91;-6]) \/ close.iloc&#91;-6] * 100\n    return_10d = (close.iloc&#91;-1] - close.iloc&#91;-11]) \/ close.iloc&#91;-11] * 100\n\n    # \u8a08\u7b97\u6307\u6578\u7d2f\u8a08\u5831\u916c\n    benchmark_return_on = (benchmark_close.iloc&#91;-1] - benchmark_close.iloc&#91;-(FILLTER_ON_ACCDAY+1)]) \/ benchmark_close.iloc&#91;-(FILLTER_ON_ACCDAY+1)] * 100\n    benchmark_return_of = (benchmark_close.iloc&#91;-1] - benchmark_close.iloc&#91;-(FILLTER_OF_ACCDAY+1)]) \/ benchmark_close.iloc&#91;-(FILLTER_OF_ACCDAY+1)] * 100\n\n    # \u8a08\u7b97\u5747\u7dda\n    short_ma = close.rolling(window=SHORT_MA).mean()\n    long_ma = close.rolling(window=LONG_MA).mean()\n\n    # \u5224\u65b7\u662f\u5426\u6709\u6301\u5009\n    contract = data.current(context.asset, 'contract')\n    open_positions = context.portfolio.positions\n    in_position = contract in open_positions and open_positions&#91;contract].amount != 0\n    value = context.portfolio.portfolio_value\n\n    # \u8a08\u7b97\u9ec3\u91d1\u4ea4\u53c9\u8a0a\u865f\n    # golden_cross = (short_ma.iloc&#91;-2] &lt; long_ma.iloc&#91;-2]) and (short_ma.iloc&#91;-1] &gt; long_ma.iloc&#91;-1])\n    golden_cross = (short_ma.iloc&#91;-2] &lt; long_ma.iloc&#91;-2]) and (short_ma.iloc&#91;-1] &gt; long_ma.iloc&#91;-1] * 1.0001)\n\n    # \u8a08\u7b97\u6b7b\u4ea1\u4ea4\u53c9\u8a0a\u865f\n    death_cross  = (short_ma.iloc&#91;-2] &gt; long_ma.iloc&#91;-2]) and (short_ma.iloc&#91;-1] &lt; long_ma.iloc&#91;-1])\n\n    # \u8a08\u7b97\u505c\u640d\u8a0a\u865f\n    stop_loss_flag = (return_1d &lt; -STOPLOSS_1D) or (return_5d &lt; -STOPLOSS_5D) or (return_10d &lt; -STOPLOSS_10D)\n\n    # \u8a08\u7b97\u6ffe\u7db2\u8a0a\u865f\n\n    if context.filter_triggered == 0:\n        if benchmark_return_on &lt;= FILLTER_ON_TRIGGER:\n            context.filter_triggered = 1\n            context.filter_days = 0  # \u91cd\u7f6e\u6ffe\u7db2\u5929\u6578\u8a08\u6578\u5668\n            #----------------------------------|--------------|\n            log.info(f'{get_datetime().date()} | Filter ON    | Benchmark {FILLTER_ON_ACCDAY}d return: {benchmark_return_on:.2f}%')\n\n    else:  # context.filter_triggered == 1\n        context.filter_days += 1  # \u6ffe\u7db2\u5929\u6578\u8a08\u6578\u5668\u589e\u52a0\n        \n        # \u6aa2\u67e5\u6ffe\u7db2\u81ea\u52d5\u95dc\u9589\u689d\u4ef6\uff1a\u5929\u6578\u9054\u5230\u4e0a\u9650\n        if context.filter_days &gt;= FILLTER_AUTO_OFF_DAYS:\n            context.filter_triggered = 0\n            context.filter_days = 0\n            #----------------------------------|--------------|\n            log.info(f'{get_datetime().date()} | Filter OFF   | Auto off after {FILLTER_AUTO_OFF_DAYS} days')\n        \n        # \u6aa2\u67e5\u6ffe\u7db2\u95dc\u9589\u689d\u4ef6\uff1a\u5e02\u5834\u53cd\u5f48\n        elif benchmark_return_of &gt;= FILLTER_OF_TRIGGER:\n            context.filter_triggered = 0\n            context.filter_days = 0\n            #----------------------------------|--------------|\n            log.info(f'{get_datetime().date()} | Filter OFF   | Benchmark {FILLTER_OF_ACCDAY}d return: {benchmark_return_of:.2f}%')\n\n    # \u8a08\u7b97\u9032\u51fa\u5834\u8a0a\u865f\n\n    # \u6ffe\u7db2\u672a\u89f8\u767c\u6642\uff0c\u4f9d\u7b56\u7565\u9032\u51fa\u5834\n    if context.filter_triggered == 0:\n\n        # \u6709\u90e8\u4f4d =&gt; \u5224\u65b7\u51fa\u5834\u6642\u6a5f\n        if in_position:\n            context.hold_days += 1\n\n            # \u79fb\u52d5\u505c\u640d\n            if stop_loss_flag:\n                order_value(contract, 0)\n                #----------------------------------|--------------|\n                log.info(f'{get_datetime().date()} | STOP_LOSS    | sell | position: {open_positions&#91;contract].amount if contract in open_positions else 0} | Hold Days: {context.hold_days}')\n                context.hold_days = 0\n                context.wait_after_stoploss = 5\n            \n            # \u6b7b\u4ea1\u4ea4\u53c9\n            elif death_cross:\n                order_value(contract, 0)\n                #----------------------------------|--------------|\n                log.info(f'{get_datetime().date()} | Death Cross  | sell | position: {open_positions&#91;contract].amount if contract in open_positions else 0} | Hold Days: {context.hold_days}')\n                context.hold_days = 0    \n            \n            # \u8d85\u904e\u6301\u6709\u5929\u6578\u9650\u5236\n            elif context.hold_days &gt;= MAX_HOLD_DAYS:\n                order_value(contract, 0)\n                #----------------------------------|--------------|\n                log.info(f'{get_datetime().date()} | Max Hold     | sell | position: {open_positions&#91;contract].amount if contract in open_positions else 0} | Hold Days: {context.hold_days}')\n                context.hold_days = 0\n\n        # \u7121\u90e8\u4f4d =&gt; \u5224\u65b7\u9032\u5834\u6642\u6a5f\n        else:\n            context.hold_days = 0\n            if context.wait_after_stoploss &gt; 0:\n                context.wait_after_stoploss -= 1\n            elif golden_cross:\n                order_value(contract, value * LEVERAGE)\n                #----------------------------------|--------------|\n                log.info(f'{get_datetime().date()} | Golden Cross | buy  | position: {open_positions&#91;contract].amount if contract in open_positions else 0} | Amount: {value * LEVERAGE}')\n                context.hold_days = 0\n    \n    # \u6ffe\u7db2\u89f8\u767c\u6642\uff0c\u7121\u689d\u4ef6\u76f4\u63a5\u5e73\u5009\n    else: # context.filter_triggered == 1\n        \n        if in_position:\n            context.hold_days += 1\n            order_value(contract, 0)\n            #----------------------------------|--------------|\n            log.info(f'{get_datetime().date()} | Filter Close | sell | position: {open_positions&#91;contract].amount if contract in open_positions else 0} | Hold Days: {context.hold_days} | Filter Days: {context.filter_days}')\n            context.hold_days = 0\n            context.wait_after_stoploss = 5\n\n    record(close=data.current(context.asset, 'price'))\n    record(position=open_positions&#91;contract].amount if contract in open_positions else 0)\n    record(filter_status=context.filter_triggered)  # \u8a18\u9304\u6ffe\u7db2\u72c0\u614b\n\ndef analyze(context=None, results=None):\n    close = results&#91;'close']\n    ma3 = close.rolling(window=3).mean()\n    ma10 = close.rolling(window=10).mean()\n    position = results&#91;'position']  \n    filter_status = results.get('filter_status', pd.Series(0, index=results.index))  # \u6ffe\u7db2\u72c0\u614b\n\n    fig, (ax1, ax2, ax3) = plt.subplots(\n        3, 1, \n        figsize=(16, 9), \n        sharex=True,\n        gridspec_kw={'height_ratios': &#91;4, 2, 2]}\n        )\n\n    # \u4e0a\u65b9\uff1a\u7b56\u7565\u8207\u57fa\u6e96\u7e3e\u6548\n    results.algorithm_period_return.plot(label='Strategy', ax=ax1)\n    results.benchmark_period_return.plot(label='Benchmark', ax=ax1)\n    ax1.set_title('MTX 3MA\/10MA Crossover Strategy with Filter (Dynamic Contracts)')\n    ax1.legend(loc=\"upper left\")\n    ax1.grid(True)\n\n    # \u4e2d\u9593\uff1a\u6536\u76e4\u50f9\u3001\u5747\u7dda\u8207\u6301\u5009\u5340\u584a\n    # ax2.plot(close.index, close, label='MTX Close')\n    ma_diff = ma3 - ma10\n\n    ax2.set_title('MTX Close, MA3, MA10 with Position Highlight')\n    ax2.bar(ma_diff.index, ma_diff, width=0.8, alpha=0.7, label='MA3-MA10', \n            color=&#91;'black' if x &gt; 0 else 'black' for x in ma_diff])\n    ax2.axhline(y=0, color='black', linewidth=2, linestyle='-')\n    ax2.set_ylabel('MA3 - MA10')\n    ax2.legend(loc=\"upper left\")\n    ax2.grid(True)\n    # ax2.plot(ma3.index, ma3, label='MA3')\n    # ax2.plot(ma10.index, ma10, label='MA10')\n\n    # \u4e0b\u65b9\uff1a\u6ffe\u7db2\u72c0\u614b\n    ax3.plot(filter_status.index, filter_status, label='Filter Status', color='red', linewidth=2)\n    ax3.fill_between(filter_status.index, 0, filter_status, alpha=0.3, color='red', \n                     where=(filter_status &gt; 0), label='Filter ON')\n    ax3.set_ylim(-0.1, 1.1)\n    ax3.set_ylabel('Filter Status')\n    ax3.set_title('Filter Status (0=OFF, 1=ON)')\n    ax3.legend(loc=\"upper left\")\n    ax3.grid(True)\n\n    # \u6dfb\u52a0\u6301\u5009\u5340\u584a\u5230\u6240\u6709\u5716\u8868\n    in_position = (position &gt; 0)\n    start = None\n    for i in range(len(in_position)):\n        if in_position.iloc&#91;i] and start is None:\n            start = i\n        elif not in_position.iloc&#91;i] and start is not None:\n            ax1.axvspan(close.index&#91;start], close.index&#91;i-1], color='orange', alpha=0.3)\n            ax2.axvspan(close.index&#91;start], close.index&#91;i-1], color='orange', alpha=0.3)\n            ax3.axvspan(close.index&#91;start], close.index&#91;i-1], color='orange', alpha=0.3)\n            start = None\n    if start is not None:\n        ax1.axvspan(close.index&#91;start], close.index&#91;-1], color='orange', alpha=0.3)\n        ax2.axvspan(close.index&#91;start], close.index&#91;-1], color='orange', alpha=0.3)\n        ax3.axvspan(close.index&#91;start], close.index&#91;-1], color='orange', alpha=0.3)\n\n    plt.tight_layout()\n    plt.show()\n\nresults = run_algorithm(\n    start            = START_DT,\n    end              = END_DT,\n    initialize       = initialize,\n    capital_base     = CAPITAL_BASE,\n    analyze          = analyze,\n    data_frequency   = 'daily',\n    bundle           = 'tquant_future',\n    trading_calendar = get_calendar('TEJ'),\n)\n\n#%% pyfolio\n'''========================================================================================='''\n\nplt.rcParams&#91;'font.sans-serif'] = &#91;'Arial', 'Noto Sans CJK TC', 'SimHei']\nplt.rcParams&#91;'axes.unicode_minus'] = False\n\ntry:\n    returns, positions, transactions = extract_rets_pos_txn_from_zipline(results)\n    # print('returns:', returns.head())\n    # print('positions:', positions.head())\n    # print('transactions:', transactions.head())\n\nexcept Exception as e:\n    print('extract_rets_pos_txn_from_zipline error:', e)\n    returns = results.get('algorithm_period_return', None)\n    positions = None\n    transactions = None\n    if returns is not None:\n        print('returns (fallback):', returns.head())\n\nbenchmark_rets = getattr(results, 'benchmark_return', None)\n\nif benchmark_rets is None and hasattr(results, 'benchmark_period_return'):\n    benchmark_rets = results.benchmark_period_return\n    \nif benchmark_rets is not None:\n    print('benchmark_rets:', benchmark_rets.head())\nelse:\n    print('No benchmark returns found!')\n    \nif returns is not None:\n    pf.tears.create_full_tear_sheet(\n        returns=returns,\n        positions=positions,\n        transactions=transactions,\n        benchmark_rets=benchmark_rets\n    )\nelse:\n    print('No returns data for pyfolio.')\n\n#%% Summary\n'''========================================================================================='''\n\nsummary_strategy = pf.timeseries.perf_stats(returns, factor_returns=benchmark_rets)\nsummary_benchmark = pf.timeseries.perf_stats(benchmark_rets)\nsummary = pd.concat(&#91;summary_strategy, summary_benchmark], axis=1)\nsummary.columns = &#91;'Strategy', 'Benchmark']\nsummary = summary.round(4)\n\nsummary\n<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"252\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\/\u622a\u5716-2025-10-20-\u4e0b\u53481.26.40-1024x252.png\" alt=\"\" class=\"wp-image-40527\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.26.40-1024x252.png 1024w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.26.40-300x74.png 300w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.26.40-150x37.png 150w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.26.40-768x189.png 768w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.26.40-1536x378.png 1536w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.26.40.png 1693w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code><\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" width=\"1024\" height=\"302\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\/\u622a\u5716-2025-10-20-\u4e0b\u53481.27.36-1024x302.png\" alt=\"\" class=\"wp-image-40529\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.27.36-1024x302.png 1024w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.27.36-300x89.png 300w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.27.36-150x44.png 150w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.27.36-768x227.png 768w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.27.36-1536x454.png 1536w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.27.36.png 1629w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p><br>benchmark_rets: 2020-01-02 00:00:00+00:00    0.008614\n2020-01-03 00:00:00+00:00    0.000823\n2020-01-06 00:00:00+00:00   -0.012970\n2020-01-07 00:00:00+00:00   -0.006110\n2020-01-08 00:00:00+00:00   -0.005322\nName: benchmark_return, dtype: float64\n<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Start date<\/th><td colspan=\"2\">2020-01-02<\/td><\/tr><tr><th>End date<\/th><td colspan=\"2\">2025-09-26<\/td><\/tr><tr><th>Total months<\/th><td colspan=\"2\">66<\/td><\/tr><tr><th><\/th><th>Backtest<\/th><\/tr><\/thead><tbody><tr><th>Annual return<\/th><td>29.162%<\/td><\/tr><tr><th>Cumulative returns<\/th><td>312.722%<\/td><\/tr><tr><th>Annual volatility<\/th><td>13.704%<\/td><\/tr><tr><th>Sharpe ratio<\/th><td>1.94<\/td><\/tr><tr><th>Calmar ratio<\/th><td>2.67<\/td><\/tr><tr><th>Stability<\/th><td>0.81<\/td><\/tr><tr><th>Max drawdown<\/th><td>-10.902%<\/td><\/tr><tr><th>Omega ratio<\/th><td>1.88<\/td><\/tr><tr><th>Sortino ratio<\/th><td>3.28<\/td><\/tr><tr><th>Skew<\/th><td>0.54<\/td><\/tr><tr><th>Kurtosis<\/th><td>13.65<\/td><\/tr><tr><th>Tail ratio<\/th><td>1.96<\/td><\/tr><tr><th>Daily value at risk<\/th><td>-1.621%<\/td><\/tr><tr><th>Gross leverage<\/th><td>0.61<\/td><\/tr><tr><th>Daily turnover<\/th><td>0.156%<\/td><\/tr><tr><th>Alpha<\/th><td>0.24<\/td><\/tr><tr><th>Beta<\/th><td>0.28<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Worst drawdown periods<\/th><th>Net drawdown in %<\/th><th>Peak date<\/th><th>Valley date<\/th><th>Recovery date<\/th><th>Duration<\/th><\/tr><\/thead><tbody><tr><th>0<\/th><td>10.90<\/td><td>2024-07-11<\/td><td>2024-09-04<\/td><td>2025-05-09<\/td><td>198<\/td><\/tr><tr><th>1<\/th><td>10.30<\/td><td>2023-07-14<\/td><td>2023-08-25<\/td><td>2024-05-13<\/td><td>201<\/td><\/tr><tr><th>2<\/th><td>9.16<\/td><td>2021-04-20<\/td><td>2022-07-06<\/td><td>2022-07-20<\/td><td>309<\/td><\/tr><tr><th>3<\/th><td>6.69<\/td><td>2020-10-12<\/td><td>2020-10-30<\/td><td>2020-11-06<\/td><td>20<\/td><\/tr><tr><th>4<\/th><td>6.09<\/td><td>2023-03-07<\/td><td>2023-07-10<\/td><td>2023-07-14<\/td><td>88<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Top 10 long positions of all time<\/th><th>max<\/th><\/tr><tr><th>sid<\/th><th><\/th><\/tr><\/thead><tbody><tr><th>MTX202009<\/th><td>64.14%<\/td><\/tr><tr><th>MTX202007<\/th><td>64.14%<\/td><\/tr><tr><th>MTX202401<\/th><td>63.85%<\/td><\/tr><tr><th>MTX202011<\/th><td>63.68%<\/td><\/tr><tr><th>MTX202309<\/th><td>63.38%<\/td><\/tr><tr><th>MTX202308<\/th><td>63.30%<\/td><\/tr><tr><th>MTX202101<\/th><td>63.26%<\/td><\/tr><tr><th>MTX202010<\/th><td>63.23%<\/td><\/tr><tr><th>MTX202207<\/th><td>63.08%<\/td><\/tr><tr><th>MTX202312<\/th><td>63.05%<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Top 10 short positions of all time<\/th><th>max<\/th><\/tr><tr><th>sid<\/th><th><\/th><\/tr><\/thead><\/table><\/figure>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Top 10 positions of all time<\/th><th>max<\/th><\/tr><tr><th>sid<\/th><th><\/th><\/tr><\/thead><tbody><tr><th>MTX202009<\/th><td>64.14%<\/td><\/tr><tr><th>MTX202007<\/th><td>64.14%<\/td><\/tr><tr><th>MTX202401<\/th><td>63.85%<\/td><\/tr><tr><th>MTX202011<\/th><td>63.68%<\/td><\/tr><tr><th>MTX202309<\/th><td>63.38%<\/td><\/tr><tr><th>MTX202308<\/th><td>63.30%<\/td><\/tr><tr><th>MTX202101<\/th><td>63.26%<\/td><\/tr><tr><th>MTX202010<\/th><td>63.23%<\/td><\/tr><tr><th>MTX202207<\/th><td>63.08%<\/td><\/tr><tr><th>MTX202312<\/th><td>63.05%<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th><\/th><th>Strategy<\/th><th>Benchmark<\/th><\/tr><\/thead><tbody><tr><th>Annual return<\/th><td>0.2916<\/td><td>0.1881<\/td><\/tr><tr><th>Cumulative returns<\/th><td>3.1272<\/td><td>1.5977<\/td><\/tr><tr><th>Annual volatility<\/th><td>0.1370<\/td><td>0.1978<\/td><\/tr><tr><th>Sharpe ratio<\/th><td>1.9365<\/td><td>0.9707<\/td><\/tr><tr><th>Calmar ratio<\/th><td>2.6749<\/td><td>0.6587<\/td><\/tr><tr><th>Stability<\/th><td>0.8124<\/td><td>0.8224<\/td><\/tr><tr><th>Max drawdown<\/th><td>-0.1090<\/td><td>-0.2855<\/td><\/tr><tr><th>Omega ratio<\/th><td>1.8757<\/td><td>1.1919<\/td><\/tr><tr><th>Sortino ratio<\/th><td>3.2789<\/td><td>1.3591<\/td><\/tr><tr><th>Skew<\/th><td>0.5411<\/td><td>-0.5698<\/td><\/tr><tr><th>Kurtosis<\/th><td>13.6454<\/td><td>8.1531<\/td><\/tr><tr><th>Tail ratio<\/th><td>1.9604<\/td><td>1.0142<\/td><\/tr><tr><th>Daily value at risk<\/th><td>-0.0162<\/td><td>-0.0242<\/td><\/tr><tr><th>Alpha<\/th><td>0.2355<\/td><td>NaN<\/td><\/tr><tr><th>Beta<\/th><td>0.2803<\/td><td>NaN<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"610\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\/\u622a\u5716-2025-10-20-\u4e0b\u53481.34.19-1024x610.png\" alt=\"\" class=\"wp-image-40533\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.34.19-1024x610.png 1024w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.34.19-300x179.png 300w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.34.19-150x89.png 150w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.34.19-768x457.png 768w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.34.19.png 1286w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"352\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\/\u622a\u5716-2025-10-20-\u4e0b\u53481.35.12-1024x352.png\" alt=\"\" class=\"wp-image-40535\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.35.12-1024x352.png 1024w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.35.12-300x103.png 300w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.35.12-150x52.png 150w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.35.12-768x264.png 768w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.35.12.png 1258w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"379\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\/\u622a\u5716-2025-10-20-\u4e0b\u53481.38.57-1024x379.png\" alt=\"\" class=\"wp-image-40537\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.38.57-1024x379.png 1024w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.38.57-300x111.png 300w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.38.57-150x56.png 150w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.38.57-768x284.png 768w, https:\/\/www.tejwin.com\/wp-content\/uploads\/\u622a\u5716-2025-10-20-\u4e0b\u53481.38.57.png 1294w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>This strategy is built around the&nbsp;<strong>MA3\/MA10 Golden Cross<\/strong>, with a&nbsp;<strong>1.0001 buffer<\/strong>&nbsp;added to reduce false breakouts. It incorporates a&nbsp;<strong>sharp-decline filter<\/strong>&nbsp;(triggered when the benchmark\u2019s 2-day drop \u2264 \u22125%, enforcing immediate liquidation and a 5-day cooldown), a&nbsp;<strong>three-tier stop-loss system<\/strong>, and a&nbsp;<strong>time-based stop<\/strong>. The design allows the strategy to&nbsp;<strong>amplify gains during trending markets<\/strong>&nbsp;while prioritizing&nbsp;<strong>capital preservation during sharp drawdowns<\/strong>. A&nbsp;<strong>continuous contract<\/strong>&nbsp;is used to handle rollovers, improving consistency between&nbsp;<strong>backtesting<\/strong>&nbsp;and&nbsp;<strong>live trading<\/strong>&nbsp;results.<\/p>\n\n\n\n<p>The advantages include&nbsp;<strong>clear trading signals<\/strong>,&nbsp;<strong>structured risk management<\/strong>, and a&nbsp;<strong>balanced 1.8\u00d7 leverage<\/strong>&nbsp;that provides stable risk-adjusted returns under strict stop-loss control. Limitations include&nbsp;<strong>lag inherent in moving averages<\/strong>,&nbsp;<strong>vulnerability to whipsaws in sideways markets<\/strong>, and&nbsp;<strong>sensitivity of performance to filter thresholds and parameter tuning<\/strong>.<\/p>\n\n\n\n<p>Future work should include&nbsp;<strong>walk-forward analysis<\/strong>&nbsp;and&nbsp;<strong>sensitivity testing<\/strong>&nbsp;(on MA periods, buffer values, and filter thresholds), integrating&nbsp;<strong>volatility-based regime segmentation<\/strong>&nbsp;or&nbsp;<strong>ADX filters<\/strong>&nbsp;to activate trading only during strong trends, and incorporating&nbsp;<strong>transaction cost and slippage evaluation<\/strong>&nbsp;to enhance real-world feasibility.<\/p>\n\n\n\n<p><em>Note: This analysis is for informational purposes only and does not constitute investment advice or recommendations for any financial product.<\/em><\/p>\n\n\n\n<div style=\"border: 1px black; border-style: solid none; text-align: center; border-color: #296580; padding: 24px; margin-top: 24px; margin-bottom: 24px;\"><br \/>\n<p style=\"margin: 0px; font-size: 24px; font-weight: bold; line-height: 1.5;\">\u3010TQuant Lab Backtesting System\u3011Solving Your Quantitative Finance Challenges<\/p>\n<br \/>\n<div style=\"margin-top: 32px;\"><strong data-start=\"38\" data-end=\"90\">Click here to sign up and start your free trial<\/strong><\/div>\n<\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><h2 class=\"wp-block-heading\" style=\"box-sizing: border-box; border-width: 0px; margin: 0px 0px 1rem; font-size: 1.625rem; font-weight: 700; font-family: system-ui, &quot;Segoe UI&quot;, Roboto, Helvetica, Arial, sans-serif, &quot;Apple Color Emoji&quot;, &quot;Segoe UI Emoji&quot;; letter-spacing: 1.28px; white-space: normal;\"><\/h2><\/h3>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"GitHub_Source_Code\"><\/span>GitHub Source Code<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><a href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\/blob\/main\/example\/TQ-Future_\u9ec3\u91d1\u4ea4\u53c9\u671f\u8ca8\u4ea4\u6613\u7b56\u7565.ipynb\" target=\"_blank\" rel=\"noopener\">Click to View on GitHub<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Further_Reading\"><\/span>Further Reading<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.tejwin.com\/en\/insight\/panic-or-opportunity-spotting-market-turning-points-through-margin-maintenance-ratios\/\">Panic or Opportunity? Spotting Market Turning Points Through Margin Maintenance Ratios<\/a><\/li>\n\n\n\n<li><a class=\"ek-link\" href=\"https:\/\/www.tejwin.com\/en\/insight\/lstm-stock-price-prediction-part-2\/\">Discovering Investment Factors through Point-in-Time Audited Financial Database<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Related_Links\"><\/span>Related Links<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a class=\"ek-link\" href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\" target=\"_blank\" rel=\"noreferrer noopener\">TQuant Lab GitHub<\/a><\/li>\n\n\n\n<li><a class=\"ek-link\" href=\"https:\/\/tquant.tejwin.com\/\" target=\"_blank\" rel=\"noopener\">TQuant Lab Homepage<\/a><\/li>\n<\/ul>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The concept of the\u00a0Moving Average (MA)\u00a0originates from the\u00a0Dow Theory\u00a0developed in the early 20th century. Dow Theory emphasizes that markets exhibit trends, and such trends can be observed through price movements themselves.<br \/>\n From the\u00a0Simple Moving Average (SMA)\u00a0and\u00a0Exponential Moving Average (EMA)\u00a0to more sophisticated variants such as the\u00a0Double Exponential Moving Average (DEMA)\u00a0and\u00a0Hull Moving Average (HMA), all these improvements aim to address the inherent\u00a0lag\u00a0problem of traditional moving averages, allowing them to reflect price trends more quickly or more smoothly.<\/p>\n","protected":false},"featured_media":40523,"template":"","tags":[3063,2962,3176,2989,3166],"insight-category":[3509,1356],"class_list":["post-40690","insight","type-insight","status-publish","has-post-thumbnail","hentry","tag-backtesting-2","tag-market-data","tag-python-2","tag-quantitive-analysis","tag-tquant-lab-2","insight-category-fintech-en","insight-category-tquant-lab-en"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/40690","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight"}],"about":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/types\/insight"}],"version-history":[{"count":10,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/40690\/revisions"}],"predecessor-version":[{"id":40886,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/40690\/revisions\/40886"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media\/40523"}],"wp:attachment":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media?parent=40690"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/tags?post=40690"},{"taxonomy":"insight-category","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight-category?post=40690"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}