{"id":34243,"date":"2025-04-09T13:30:00","date_gmt":"2025-04-09T05:30:00","guid":{"rendered":"https:\/\/www.tejwin.com\/?post_type=insight&#038;p=34243"},"modified":"2025-04-16T15:37:42","modified_gmt":"2025-04-16T07:37:42","slug":"tquant-from-0-to-1-day-4-core-architecture-of-backtesting-what-are-the-key-settings-for-initialize","status":"publish","type":"insight","link":"https:\/\/www.tejwin.com\/en\/insight\/tquant-from-0-to-1-day-4-core-architecture-of-backtesting-what-are-the-key-settings-for-initialize\/","title":{"rendered":"\u3010TQuant : From 0 to 1 &#8211; Day 4\u3011 Core Architecture of Backtesting: What are the key settings for Initialize?"},"content":{"rendered":"\n<figure class=\"wp-block-image size-full caption-align-center\"><a href=\"https:\/\/unsplash.com\/photos\/person-using-imac-Imc-IoZDMXc\" target=\"_blank\" rel=\"noopener\"><img fetchpriority=\"high\" decoding=\"async\" width=\"2940\" height=\"1960\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/photo-1555421689-491a97ff2040-3.avif\" alt=\"TQuant\" class=\"wp-image-34036\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/photo-1555421689-491a97ff2040-3.avif 2940w, https:\/\/www.tejwin.com\/wp-content\/uploads\/photo-1555421689-491a97ff2040-3-300x200.avif 300w, https:\/\/www.tejwin.com\/wp-content\/uploads\/photo-1555421689-491a97ff2040-3-1024x683.avif 1024w, https:\/\/www.tejwin.com\/wp-content\/uploads\/photo-1555421689-491a97ff2040-3-150x100.avif 150w, https:\/\/www.tejwin.com\/wp-content\/uploads\/photo-1555421689-491a97ff2040-3-768x512.avif 768w, https:\/\/www.tejwin.com\/wp-content\/uploads\/photo-1555421689-491a97ff2040-3-1536x1024.avif 1536w, https:\/\/www.tejwin.com\/wp-content\/uploads\/photo-1555421689-491a97ff2040-3-2048x1365.avif 2048w\" sizes=\"(max-width: 2940px) 100vw, 2940px\" \/><\/a><figcaption class=\"wp-element-caption\">Photo by <a href=\"https:\/\/unsplash.com\/@austindistel\" target=\"_blank\" rel=\"noopener\">Austin Distel <\/a>on <a href=\"https:\/\/unsplash.com\/photos\/laptop-computer-on-glass-top-table-hpjSkU2UYSU?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-69f1341600e74\" 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-69f1341600e74\"  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\/tquant-from-0-to-1-day-4-core-architecture-of-backtesting-what-are-the-key-settings-for-initialize\/#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\/tquant-from-0-to-1-day-4-core-architecture-of-backtesting-what-are-the-key-settings-for-initialize\/#Overview_of_the_Four_Core_Components\" >Overview of the Four Core Components<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-from-0-to-1-day-4-core-architecture-of-backtesting-what-are-the-key-settings-for-initialize\/#initialize\" >initialize<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-from-0-to-1-day-4-core-architecture-of-backtesting-what-are-the-key-settings-for-initialize\/#handle_data\" >handle_data<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-from-0-to-1-day-4-core-architecture-of-backtesting-what-are-the-key-settings-for-initialize\/#analyze\" >analyze<\/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\/tquant-from-0-to-1-day-4-core-architecture-of-backtesting-what-are-the-key-settings-for-initialize\/#run_algorithm\" >run_algorithm<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-from-0-to-1-day-4-core-architecture-of-backtesting-what-are-the-key-settings-for-initialize\/#How_to_Use_the_initialize_Function\" >How to Use the initialize() Function<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-from-0-to-1-day-4-core-architecture-of-backtesting-what-are-the-key-settings-for-initialize\/#Setting_Slippage\" >Setting Slippage<\/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\/tquant-from-0-to-1-day-4-core-architecture-of-backtesting-what-are-the-key-settings-for-initialize\/#Setting_Commission\" >Setting Commission<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-from-0-to-1-day-4-core-architecture-of-backtesting-what-are-the-key-settings-for-initialize\/#The_context_Parameter\" >The context Parameter<\/a><\/li><\/ul><\/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\/tquant-from-0-to-1-day-4-core-architecture-of-backtesting-what-are-the-key-settings-for-initialize\/#Summary\" >Summary<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-from-0-to-1-day-4-core-architecture-of-backtesting-what-are-the-key-settings-for-initialize\/#%E3%80%90TQuant_From_0_to_1_%E2%80%93_Day_5%E3%80%91Link_to_be_added\" >\u3010TQuant: From 0 to 1 \u2013 Day 5\u3011(Link to be added)<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-from-0-to-1-day-4-core-architecture-of-backtesting-what-are-the-key-settings-for-initialize\/#Extended_Reading\" >Extended Reading<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-from-0-to-1-day-4-core-architecture-of-backtesting-what-are-the-key-settings-for-initialize\/#Useful_Links\" >Useful 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 Zipline engine, integrated within TQuant Lab, offers a high-quality and realistic backtesting framework. It leverages four core functions\u2014initialize\u3001handle_data\u3001analyze\u3001run_algorithm\u2014\u2014to construct a comprehensive simulation environment. These components enable trading strategies to dynamically adjust to market conditions, incorporating elements such as slippage and transaction costs to ensure that backtest results closely reflect real-world performance.<\/p>\n\n\n\n<p>This article begins with a brief overview of the four key components and their applications. It then focuses in detail on the initialize function, exploring its specific configurations and role within the backtesting process.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Overview_of_the_Four_Core_Components\"><\/span>Overview of the Four Core Components<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"initialize\"><\/span>initialize<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The initialize function serves as the starting point of any trading strategy within <strong>Zipline<\/strong> and plays a critical role in configuring the backtesting environment. Common settings defined here include slippage models, commission fees, the target security, and the benchmark index. This function is executed once at the beginning of the backtest.<\/p>\n\n\n\n<p>The initialize function takes a single parameter, context, which acts as a persistent storage object for custom variables. These variables can be accessed and updated on each trading day during the simulation. For example, one might define context.day = 0 to count the number of trading days elapsed, and context.has_ordered = False to track whether a position in TSMC stock has been initiated.<\/p>\n\n\n\n<p>In addition, the functions set_slippage() and set_commission() can be used within initialize to define slippage behavior and commission cost models, respectively. These configurations will be briefly discussed later in this article.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from zipline.api import set_slippage, set_commission\nfrom zipline.finance import slippage, commission\ndef initialize(context):\n    context.day = 0\n    context.has_ordered = False\n    set_slippage(slippage.FixedSlippage())\n    set_commission(commission.PerShare(cost=0.00285))\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"handle_data\"><\/span>handle_data<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The handle_data function is responsible for defining the trading logic, executing orders, and recording relevant trading information. It is called once per day throughout the backtesting period after the simulation begins.<\/p>\n\n\n\n<p>This function takes two parameters: context and data. The context parameter serves the same purpose as in initialize\u2014it stores custom variables that persist across trading days and can be updated or referenced during the backtest. The data parameter provides access to daily price and volume information for each asset. For example, data.current() can be used to retrieve the current day&#8217;s open, high, low, and close prices, while data.history() allows access to historical price and volume data.<\/p>\n\n\n\n<p>In addition, the record function can be used within handle_data to track specific values across trading days. These recorded values will appear as columns in the final output DataFrame generated by run_algorithm. <\/p>\n\n\n\n<p>Below is an example of how this function can be implemented:<\/p>\n\n\n\n<p class=\"has-text-align-center\">record( &#8216;column_name&#8217; = value)<\/p>\n\n\n\n<p>As an example, consider a simple strategy in which we place an order to buy 1,000 shares of TSMC (ticker: 2330) and hold the position until the end of the backtest. In this case, we record three key elements during each trading day: the number of trading days elapsed (context.day), whether the position has already been initiated (context.has_ordered), and the current closing price retrieved via data.current(symbol(&#8220;2330&#8221;), &#8220;close&#8221;). <\/p>\n\n\n\n<p>Within the handle_data function, Zipline supports six different order functions to place trades. A detailed explanation of the first four methods will be provided in the next section of this series.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from zipline.api import order, record, symbol\ndef handle_data(context, data):\n    context.day += 1\n    if not context.has_ordered:\n        order(symbol(\"2330\"), 1000)\n        context.has_ordered = True    \n    record(\n        trade_days = context.day,\n        has_ordered = context.has_ordered,\n        TSMC = data.current(symbol(\"2330\"), \"close\")\n    )\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"analyze\"><\/span>analyze<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The analyze function is primarily used for visualizing backtest results, helping users evaluate strategy performance and risk management outcomes. It is called once at the end of the backtest process.<\/p>\n\n\n\n<p>This function takes two parameters: context and perf. The context object serves the same role as described in the initialize section, while perf refers to the output DataFrame generated by run_algorithm. This DataFrame contains a variety of recorded performance metrics and can be used to extract specific columns for plotting and analysis.<\/p>\n\n\n\n<p>As an example, we can use <strong>Matplotlib<\/strong> to visualize the portfolio value over time and compare it with the price trend of TSMC (2330). A more detailed discussion of how to use the analyze function will be covered in a later section of this series.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import matplotlib.pyplot as plt\ndef analyze(context, perf):\n    ax1 = plt.subplot(211)\n    perf.portfolio_value.plot(ax=ax1,title='portfolio values')\n    ax2 = plt.subplot(212, sharex=ax1)\n    perf&#91;'TSMC'].plot(ax=ax2,title='TSMC close')\n    plt.gcf().set_size_inches(18, 8)\n    plt.show()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"run_algorithm\"><\/span>run_algorithm<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The run_algorithm function is the core entry point for executing a backtest and serves as the primary trigger for running a trading strategy.<\/p>\n\n\n\n<p>This function accepts multiple parameters and includes several built-in fields that allow users to configure the backtest environment in detail. A comprehensive explanation of these parameters and their applications will be provided in a later section of this series.<br><\/p>\n\n\n\n<p><strong>Example Code:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from zipline import run_algorithm\nimport pandas as pd \n\nstart_date = pd.Timestamp('2018-12-30',tz='utc')\nend_date = pd.Timestamp('2023-05-26',tz='utc')\n\nresults = run_algorithm(start= start_date,  \n                       end=end_date,\n                       initialize=initialize,                       \n                       capital_base=1e6,                       \n                       analyze=analyze,\n                       handle_data=handle_data,\n                       data_frequency='daily',\n                       bundle='tquant'\n                       )<\/code><\/pre>\n\n\n\n<p class=\"has-text-align-center\"><img decoding=\"async\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/AD_4nXcozPNymg-SweHfMGLZkk7fRLNvpGBZRqB1xGgDhHiAHTCIt9uZJfMY9s4HJqlQRlQPWARmCHjD6EjFVxMktmXZfJjh-oiheeRbcP6W9TNEW7OtJIe60QJLn0D31HtTG9mSAQDaQkeyWy9ZQ5pYTt1mEAm-z6TKAgxy.png\" width=\"602\" height=\"264\"><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"How_to_Use_the_initialize_Function\"><\/span><strong>How to Use the initialize() Function<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>After introducing the four core components of the backtesting framework, we now turn to a detailed explanation of the <code>initialize()<\/code> function\u2014its parameters and practical usage.<\/p>\n\n\n\n<p>One of its most common applications is to set <strong>slippage<\/strong> and <strong>commission<\/strong> models, which help ensure that backtest results better reflect real-world market conditions. Additionally, custom variables and parameters can be defined within <code>initialize()<\/code> to store and manage trading-related information throughout the simulation.<br><\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Setting_Slippage\"><\/span><strong>Setting Slippage<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The set_slippage() function is used to define the slippage model. Zipline supports the following four types of slippage models:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><td>Slippage Models<\/td><td>Explanation<\/td><\/tr><tr><td>FixedSlippage<\/td><td>Simulates transaction costs by applying a constant bid-ask spread. This model does not account for volume constraints.<\/td><\/tr><tr><td>VolumeShareSlippage<\/td><td>Calculates slippage based on the proportion of the trade volume relative to the asset\u2019s total daily volume, incorporating market impact.<\/td><\/tr><tr><td>FixedBasisPointsSlippage<\/td><td>Applies a fixed number of basis points to each trade, with the option to set volume limits to reflect liquidity constraints.<\/td><\/tr><tr><td>NoSlippage<\/td><td>Assumes trades are executed at market prices without any slippage applied.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Setting_Commission\"><\/span>Setting Commission<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The set_commission() function is used to define the commission model. <strong>Zipline<\/strong> provides several methods for calculating transaction costs, including:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><td>Commission Models<\/td><td>Explanation<\/td><\/tr><tr><td>NoCommission<\/td><td>No transaction fees are charged. This setting is typically used in simulation environments or promotional programs.<\/td><\/tr><tr><td>PerDollar<\/td><td>Commission is calculated as a fixed rate applied to the total trade value. For example, a fee of 0.0015 is charged for every NT$1 traded. This is Zipline\u2019s default setting.<\/td><\/tr><tr><td>PerTrade<\/td><td>A fixed fee is charged per transaction, regardless of the trade size or value. The default is NT$0.<\/td><\/tr><tr><td>Custom_TW_Commission<\/td><td>Taiwan Equity Market Commission Model (Tailored for local regulations): This model includes two direct costs: brokerage commission (0.1425%) and securities transaction tax (0.3%) and allows for setting a minimum fee (default: NT$20).<br><br>1. transaction fee<br>\u2022 Applies to both buy and sell orders.<br>\u2022 Formula: Trade Price \u00d7 Number of Shares \u00d7 0.1425% \u00d7 Discount (Discount defaults to 1, meaning no discount applied)<br>\u2022 A minimum commission (default NT$20) is enforced.<br><br>2. Securities Transaction Tax<br>\u2022 This only applies to sell transactions.<br>\u2022 Formula: Trade Price \u00d7 Number of Shares \u00d7 Tax Rate (Default tax rate: 0.3%)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>&nbsp;<strong>Example Code:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from zipline.api import set_commission\nfrom zipline.finance import commission\ndef initialize(context):\n    set_slippage(slippage.&lt;slippage models&gt;)\n    set_commission(commission.&lt;commission models&gt;)\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_context_Parameter\"><\/span><strong>The context Parameter<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>context is a <strong>namespace object<\/strong> used to store user-defined variables and parameters. These variables persist throughout the backtest and can be accessed or updated on each trading day.<\/p>\n\n\n\n<p>For example, we may define a variable to track the number of trading days elapsed and another to record whether the strategy has already placed an order for the target stock:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>context.day = 0\n<ul class=\"wp-block-list\">\n<li>Used to count the number of trading days. Initialized at 0 and incremented by one with each new trading day.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li>context.has_ordered = False\n<ul class=\"wp-block-list\">\n<li>Used to determine whether the target stock has been purchased. Initialized as False (indicating no position). Once the order is executed, the flag can be updated to True.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<p><strong>Example Code:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from zipline.api import set_slippage, set_commission\nfrom zipline.finance import slippage, commission\n\ndef initialize(context):\n    context.day = 0\n    context.has_ordered = False\n    set_slippage(slippage.FixedSlippage())\n    set_commission(commission.PerShare(cost=0.00285))\n<\/code><\/pre>\n\n\n\n<p>You can also define a list of stock tickers to be traded and convert them into Zipline-recognizable <strong>Asset<\/strong> objects, which simplifies subsequent order placement. In addition, you can specify a custom <strong>benchmark<\/strong> for performance comparison.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>context.tickers = [\u20181101\u2019, \u20182330\u2019]\n<ul class=\"wp-block-list\">\n<li>Defines the list of stock tickers to be traded.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li>context.asset = [symbol(ticker) for ticker in context.tickers]\n<ul class=\"wp-block-list\">\n<li>Converts the ticker symbols into Asset objects recognized by Zipline, and stores them in the context for later use in trading logic.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li>set_benchmark(symbol(&#8216;IR0001&#8217;))\n<ul class=\"wp-block-list\">\n<li>Sets the benchmark to the asset with ticker &#8216;IR0001&#8217;, which represents the Capitalization-Weighted Price Return Index of the Taiwan stock market.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<p><strong>Example Code:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from zipline.api import set_slippage, set_commission\nfrom zipline.finance import slippage, commission\n\ndef initialize(context):\n    context.tickers = &#91;'1101', '2330']\n    context.asset = &#91;symbol(ticker) for ticker in context.tickers]\n    set_slippage(slippage.FixedSlippage(spread=0.00))\n    set_commission(commission.PerDollar(cost=commission_cost))\n    set_benchmark(symbol('IR0001'))\n<\/code><\/pre>\n\n\n\n<p><strong>Important Reminder<\/strong>: This analysis is for reference only and does not constitute any product or investment advice.<\/p>\n\n\n\n<p>We welcome readers interested in various trading strategies to consider purchasing relevant solutions from&nbsp;<a href=\"https:\/\/www.tejwin.com\/en\/solution\/quantitative-finance-solution\/\" class=\"ek-link\"><strong><mark style=\"background-color:#ffdf88\" class=\"has-inline-color\">Quantitative Finance Solution<\/mark><\/strong><\/a>. With our high-quality databases, you can construct a trading strategy that suits your needs.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button has-custom-width wp-block-button__width-100 has-custom-font-size\" style=\"font-size:22px\"><a class=\"wp-block-button__link has-background wp-element-button\" href=\"https:\/\/www.tejwin.com\/en\/databank-solution\/financial-data\/\" style=\"border-radius:16px;background:linear-gradient(135deg,rgb(243,224,131) 0%,rgb(102,197,166) 50%,rgb(51,132,181) 100%)\"><strong>Access to Comprehensive Quantitative Data<\/strong><br><strong>Start Building Portfolios That Outperform the Market Today!<\/strong><\/a><\/div>\n<\/div>\n\n\n\n<div style=\"height:22px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<p class=\"has-text-align-center\" style=\"font-size:32px\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\"><strong><em>&#8220;Taiwan stock market data, TEJ collect it all.&#8221;<\/em><\/strong><\/mark><\/p>\n\n\n\n<p>The characteristics of the Taiwan stock market differ from those of other European and American markets. Especially in the first quarter of 2024, with the <strong><mark style=\"background-color:rgba(0, 0, 0, 0);color:#c05d5d\" class=\"has-inline-color\">Taiwan Stock Exchange reaching a new high of 20,000 points<\/mark><\/strong> due to the rise in TSMC&#8217;s stock price, global institutional investors are paying more attention to the performance of the Taiwan stock market.&nbsp;<\/p>\n\n\n\n<p><strong><mark style=\"background-color:rgba(0, 0, 0, 0);color:#0978b8\" class=\"has-inline-color\">Taiwan Economical Journal (TEJ)<\/mark><\/strong>, a financial database established in Taiwan for over 30 years, serves local financial institutions and academic institutions, and has long-term cooperation with internationally renowned data providers, providing high-quality financial data for five financial markets in Asia.&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><mark style=\"background-color:#ebc766\" class=\"has-inline-color has-black-color\">Complete Coverage<\/mark><\/strong>: Includes all listed companies on stock markets in Taiwan, China, Hong Kong, Japan, Korea, etc.&nbsp;<\/li>\n\n\n\n<li><strong><mark style=\"background-color:#ebc766\" class=\"has-inline-color\">Comprehensive Analysis of Enterprises<\/mark><\/strong>: Operational aspects, financial aspects, securities market performance, ESG sustainability, etc.&nbsp;<\/li>\n\n\n\n<li><strong><mark style=\"background-color:#ebc766\" class=\"has-inline-color\">High-Quality Database<\/mark><\/strong>: TEJ data is cleaned, checked, enhanced, and integrated to ensure it meets the information needs of financial and market analysis.&nbsp;<\/li>\n<\/ul>\n\n\n\n<p>With TEJ&#8217;s assistance, you can access relevant information about major stock markets in Asia, such as securities market, financials data, enterprise operations, board of directors, sustainability data, etc., providing investors with timely and high-quality content. Additionally, TEJ offers advisory services to help solve problems in theoretical practice and financial management!<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-a89b3969 wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button has-custom-width wp-block-button__width-100 has-custom-font-size\" style=\"font-size:21px\"><a class=\"wp-block-button__link has-background has-text-align-center wp-element-button\" href=\"https:\/\/www.tejwin.com\/en\/contact\/\" style=\"border-radius:16px;background:linear-gradient(135deg,rgb(160,209,216) 0%,rgb(51,145,181) 50%,rgb(50,95,191) 100%)\"><strong>Want to Learn More About Our Databases and Solutions?<br>Contact Us and Get the Free Trial Today!<\/strong><\/a><\/div>\n<\/div>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Summary\"><\/span>Summary<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Within the initialize() function, we can configure key components such as <strong>slippage<\/strong>, <strong>commission model<\/strong>, <strong>tradable assets<\/strong>, and the <strong>benchmark index<\/strong>. Additionally, the context object serves as a central storage for tracking the trading state, ensuring that the backtest executes smoothly and systematically.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"%E3%80%90TQuant_From_0_to_1_%E2%80%93_Day_5%E3%80%91Link_to_be_added\"><\/span><strong>\u3010TQuant: From 0 to 1 \u2013 Day 5\u3011(Link to be added)<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Extended_Reading\"><\/span>Extended Reading<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><a href=\"https:\/\/www.tejwin.com\/en\/insight\/your-gateway-to-quantitative-trading\/\">\u3010TQuant : From 0 to 1 &#8211; Day 1\u3011 Your Gateway to Quantitative Trading: Become a Quant Expert with TQuant Lab, No Experience Needed!<\/a><\/p>\n\n\n\n<p><a href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-from-0to1-commission-and-slippage\/\" data-type=\"link\" data-id=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-from-0to1-commission-and-slippage\/\">\u3010TQuant : From 0 to 1 &#8211; Day 2\u3011 Avoid the Invisible Killers of Quantitative Trading: Use TQuant Lab to Precisely Manage Commission and Slippage, Giving Your Strategies the Edge!<\/a><\/p>\n\n\n\n<p><a href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-from-0-to-1-day-3-building-a-comprehensive-investment-data-perspective-stock-pool-screening-and-data-retrieval-with-tejtoolapi-2\/\" data-type=\"link\" data-id=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-from-0-to-1-day-3-building-a-comprehensive-investment-data-perspective-stock-pool-screening-and-data-retrieval-with-tejtoolapi-2\/\">[TQuant from 0 to 1 &#8211; Day 3] Building a Comprehensive Investment Data Perspective: Stock Pool Screening and Data Retrieval with TejToolAPI<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Useful_Links\"><\/span>Useful Links<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\" target=\"_blank\" rel=\"noopener\">https:\/\/github.com\/tejtw\/TQuant-Lab<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/tquant.tejwin.com\/\" target=\"_blank\" rel=\"noopener\">https:\/\/tquant.tejwin.com\/<\/a><\/li>\n<\/ul>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Zipline engine, integrated within TQuant Lab, offers a high-quality and realistic backtesting framework. It leverages four core functions\u2014initialize\u3001handle_data\u3001analyze\u3001run_algorithm\u2014\u2014to construct a comprehensive simulation environment. These components enable trading strategies to dynamically adjust to market conditions, incorporating elements such as slippage and transaction costs to ensure that backtest results closely reflect real-world performance.<\/p>\n<p>This article begins with a brief overview of the four key components and their applications. It then focuses in detail on the initialize function, exploring its specific configurations and role within the backtesting process.<\/p>\n","protected":false},"featured_media":34037,"template":"","tags":[2962,2987,3007,3008,3166,2428],"insight-category":[50,1356],"class_list":["post-34243","insight","type-insight","status-publish","has-post-thumbnail","hentry","tag-market-data","tag-quant","tag-tejapi-data-analysis","tag-tejapi-quant","tag-tquant-lab-2","tag-2428","insight-category-fintech","insight-category-tquant-lab-en"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/34243","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":5,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/34243\/revisions"}],"predecessor-version":[{"id":40063,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/34243\/revisions\/40063"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media\/34037"}],"wp:attachment":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media?parent=34243"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/tags?post=34243"},{"taxonomy":"insight-category","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight-category?post=34243"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}