{"id":17186,"date":"2023-08-29T14:00:00","date_gmt":"2023-08-29T06:00:00","guid":{"rendered":"https:\/\/www.tejwin.com\/?post_type=insight&#038;p=17186"},"modified":"2023-08-29T10:50:40","modified_gmt":"2023-08-29T02:50:40","slug":"tquant-lab-rookie-manual","status":"publish","type":"insight","link":"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-rookie-manual\/","title":{"rendered":"TQuant Lab Rookie Manual"},"content":{"rendered":"\n<figure class=\"wp-block-image aligncenter size-large is-resized caption-align-center\"><img fetchpriority=\"high\" decoding=\"async\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\/image-249-1024x683.png\" alt=\"TQuant Lab \u63d0\u4f9b\u5f37\u5927\u7684\u91cf\u5316\u56de\u6e2c\u7cfb\u7d71\uff0c\u9ad8\u7cbe\u78ba\u5ea6\u7684\u7e3e\u6548\u98a8\u96aa\u8a08\u7b97\u3001\u9ad8\u54c1\u8cea\u7684\u8cc7\u6599\u4f86\u6e90\u3001\u9ad8\u64ec\u771f\u5ea6\u7684\u4ea4\u6613\u74b0\u5883\u6a21\u64ec\uff0c\u5e6b\u52a9\u4f7f\u7528\u8005\u5feb\u901f\u90e8\u5c6c\u5404\u6a23\u7684\u4ea4\u6613\u7b56\u7565\uff0c\u6b61\u8fce\u5404\u4f4d\u9ede\u64ca\u9032\u5165\u6587\u7ae0\u4e86\u89e3\u66f4\u591a\u8cc7\u8a0a\u3002\" class=\"wp-image-17144\" style=\"width:840px;height:560px\" width=\"840\" height=\"560\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/image-249-1024x683.png 1024w, https:\/\/www.tejwin.com\/wp-content\/uploads\/image-249-300x200.png 300w, https:\/\/www.tejwin.com\/wp-content\/uploads\/image-249-150x100.png 150w, https:\/\/www.tejwin.com\/wp-content\/uploads\/image-249-768x512.png 768w, https:\/\/www.tejwin.com\/wp-content\/uploads\/image-249-1536x1024.png 1536w, https:\/\/www.tejwin.com\/wp-content\/uploads\/image-249.png 1740w\" sizes=\"(max-width: 840px) 100vw, 840px\" \/><figcaption class=\"wp-element-caption\">Photo by <a href=\"https:\/\/unsplash.com\/@talhahassan116?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\" target=\"_blank\" rel=\"noopener\">Talha Hassan<\/a> on <a href=\"https:\/\/unsplash.com\/photos\/wdBqEHzo39g?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\" class=\"ek-link\" 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-69f10aeba5ee3\" 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-69f10aeba5ee3\"  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-lab-rookie-manual\/#Highlight\" >Highlight<\/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-lab-rookie-manual\/#Introduction\" >Introduction<\/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\/tquant-lab-rookie-manual\/#Module_Installation\" >Module Installation<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-rookie-manual\/#YML_Installation\" >YML Installation<\/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-lab-rookie-manual\/#Manual_Installation\" >Manual Installation<\/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-lab-rookie-manual\/#Google_Colab_Installation\" >Google Colab Installation<\/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\/tquant-lab-rookie-manual\/#Exchange_calendar_issue\" >Exchange calendar issue<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-rookie-manual\/#Ingest_data\" >Ingest data<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-rookie-manual\/#Strategy_back-testing\" >Strategy back-testing<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-rookie-manual\/#Initialize_function\" >Initialize function<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-rookie-manual\/#Handle_data_function\" >Handle_data function<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-rookie-manual\/#ziplineapiorder\" >zipline.api.order<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-rookie-manual\/#ziplinedatacurrent\" >zipline.data.current<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-rookie-manual\/#Analyze_function\" >Analyze function<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-rookie-manual\/#Run_algorithm_function\" >Run_algorithm function<\/a><\/li><\/ul><\/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\/tquant-lab-rookie-manual\/#Conclusion\" >Conclusion<\/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\/tquant-lab-rookie-manual\/#Source_code\" >Source code<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-18\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-rookie-manual\/#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-19\" href=\"https:\/\/www.tejwin.com\/en\/insight\/tquant-lab-rookie-manual\/#Related_link\" >Related link<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Highlight\"><\/span>Highlight<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Article Difficulty\uff1a\u2605\u2606\u2606\u2606\u2606<\/li>\n\n\n\n<li>TQuant Lab back-testing introduction<\/li>\n\n\n\n<li>Demonstrate how to use TQuant Lab<\/li>\n<\/ul>\n\n\n\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>TQuant Lab is a back-testing platform developed by TEJ, extending from the well-known Zipline framework. All securities-related information in TQuant Lab originates from TEJ&#8217;s exclusive database, ensuring the high quality of data usage. Furthermore, as it is built on the foundation of Zipline, the program architecture has undergone third-party verification over the course of several years, guaranteeing accuracy in its implementation. Thirdly, TQuant Lab offers adjustable parameters for different trading constraints and costs, facilitating users in creating the most lifelike trading environment. If you are interested, please feel free to contact us for more information.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Module_Installation\"><\/span>Module Installation<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>TQuant Lab offers installations for three operating systems or environments: Windows, Mac OS, and Google Colab. Before installing the modules, it is essential to have Anaconda installed. Instructions for installing Anaconda can be found in the <a href=\"https:\/\/medium.com\/python4u\/anaconda%E4%BB%8B%E7%B4%B9%E5%8F%8A%E5%AE%89%E8%A3%9D%E6%95%99%E5%AD%B8-f7dae6454ab6\" class=\"ek-link\" target=\"_blank\" rel=\"noopener\">Anaconda Introduction and Installation Tutorial<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"YML_Installation\"><\/span>YML Installation<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Please download installation packages down below in advanced.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Windows (<a href=\"https:\/\/minhaskamal.github.io\/DownGit\/#\/home?url=https:%2F%2Fgithub.com%2Ftejtw%2Fzipline-tej%2Fblob%2Fmain%2Fzipline-tej.yml\" class=\"ek-link\" target=\"_blank\" rel=\"noopener\">zipline-tej.yml<\/a>)<\/li>\n\n\n\n<li>Mac (<a href=\"https:\/\/minhaskamal.github.io\/DownGit\/#\/home?url=https:%2F%2Fgithub.com%2Ftejtw%2Fzipline-tej%2Fblob%2Fmain%2Fzipline-tej_mac.yml\" class=\"ek-link\" target=\"_blank\" rel=\"noopener\">zipline-tej-mac.yml<\/a>)<\/li>\n<\/ul>\n\n\n\n<p>Open the Anaconda Prompt and enter the following code to create a virtual environment and install the necessary modules:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Window User\n# Place yml file in below link\n$ cd &lt;C:\\Users\\username\\Downloads&gt;\n# create virtual environment\n$ conda env create -f zipline-tej.yml\n# activate virtual environment\n$ conda activate zipline-tej\n\nMac User\n# Place yml file in below link\n$ cd &lt;C:\\Users\\username\\Downloads&gt;\n# create virtual environment\n$ conda env create -f zipline-tej_mac.yml\n# activate virtual environment\n$ conda activate zipline-tej<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Manual_Installation\"><\/span>Manual Installation<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>If you are well-versed in Python, you can manually create a virtual environment and install the required dependencies one by one.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># create virtual env\n$ conda create -n &lt;env_name&gt; python=3.8\n\n# activate virtual env\n$ conda activate &lt;env_name&gt;\n\n# download dependency packages\n$ conda install -c conda-forge -y ta-lib\n$ conda install -y notebook=6.4.11\n$ conda install -c conda-forge nb_conda_kernels\n$ conda install -y xlrd=2.0.1\n$ conda install -y openpyxl=3.0.9\n$ pip install zipline-tej<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Google_Colab_Installation\"><\/span>Google Colab Installation<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Since TQuant Lab currently supports only Python 3.8 version, you can add a Python 3.8 runtime using the following code snippet:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>!wget -O mini.sh https:\/\/repo.anaconda.com\/miniconda\/Miniconda3-py38_4.8.2-Linux-x86_64.sh\n!chmod +x mini.sh\n!bash .\/mini.sh -b -f -p \/usr\/local\n!conda install -q -y jupyter\n!conda install -q -y google-colab -c conda-forge\n!python -m ipykernel install --name \"Python3.8\" --user\n!rm mini.sh\n!pip install pandas==1.2.5<\/code><\/pre>\n\n\n\n<p>Next, follow these steps:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Select &#8220;Runtime&#8221; in the menu.<\/li>\n\n\n\n<li>Choose &#8220;Change runtime type.&#8221;<\/li>\n\n\n\n<li>In the &#8220;Runtime type&#8221; dropdown, select &#8220;Python 3.8.&#8221;<\/li>\n\n\n\n<li>Click &#8220;Save.&#8221;<\/li>\n<\/ol>\n\n\n\n<p>After changing the runtime type to Python 3.8, you can run the following code to download <code>zipline-tej<\/code>. If you encounter any version issues with <code>yfinance<\/code> and <code>pandas<\/code>, please proceed despite the warnings.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>!conda install -y ta-lib -c conda-forge\n!pip install zipline-tej<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Exchange_calendar_issue\"><\/span>Exchange calendar issue<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Since TQuant Lab utilizes Taiwan stock market trading data provided by TEJ, we need to use a specialized trading calendar tailored for the Taiwanese stock market. This is crucial for subsequent back-testing purposes. Below, there are downloadable trading calendar files provided, and it&#8217;s necessary to place these files within the designated <code><strong>exchange_calendars<\/strong><\/code> folder. [<a href=\"https:\/\/minhaskamal.github.io\/DownGit\/#\/home?url=https:\/\/github.com\/tejtw\/zipline-tej\/tree\/main\/exchange_calendars\" class=\"ek-link\" target=\"_blank\" rel=\"noopener\">Download<\/a>]<\/p>\n\n\n\n<p>After downloading the aforementioned trading calendar files, copy the <code><strong>exchange_calendar_tejxtai.py<\/strong><\/code> file and append it to the <code><strong>calendar_utils.py<\/strong><\/code> file within the <code><strong>exchange_calendars<\/strong><\/code> folder.<\/p>\n\n\n\n<p>Navigate to the <strong><code>exchange_calendars<\/code> <\/strong>folder located in the site-packages. Typically, it&#8217;s located at the following path: <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Window user\n\n**C:\\Users\\username\\Anaconda3\\envs\\zipline-tej\\Lib\\site-packages\\exchange_calendars**\n\nMac user\n\nC:\\Users\\username\\Anaconda3\\envs\\zipline-tej\\Lib\\python3.8\\site-packages\\exchange_calendars<\/code><\/pre>\n\n\n\n<p>Full tutorial please refer to <a href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\/blob\/main\/lecture\/Install%20TQuant%20Lab.ipynb\" class=\"ek-link\" target=\"_blank\" rel=\"noopener\">Install TQuant Lab<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Ingest_data\"><\/span>Ingest data<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>TQuant Lab retrieves price and volume data from the database built by TEJ and stores the data in memory as data bundles. You can determine the assets to be imported and the time range by configuring environment variables. The available environment variables for configuration are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>os.environ[\"TEJAPI_BASE\"]<\/code>: Connects to the TEJ database domain.<\/li>\n\n\n\n<li><code>os.environ[\"TEJAPI_KEY\"]<\/code>: Identifies the user.<\/li>\n\n\n\n<li><code>os.environ[\"ticker\"]<\/code>: Specifies the desired assets to retrieve.<\/li>\n\n\n\n<li><code>os.environ[\"mdate\"]<\/code>: Specifies the desired time range for retrieval.<\/li>\n<\/ul>\n\n\n\n<p>Once you&#8217;ve set up the environment variables, use the command<strong> <code>!zipline ingest -b tquant<\/code> <\/strong>to import the data into a local data bundle. This data bundle will be named &#8220;tquant&#8221;.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import os\nimport pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt\n\nos.environ&#91;'TEJAPI_BASE'] = \"https:\/\/api.tej.com.tw\"\nos.environ&#91;'TEJAPI_KEY'] = \"YOUR KEY\"\nos.environ&#91;'ticker'] = \"IR0001 2330 2337 0050 2545\"\nos.environ&#91;'mdate'] = \"20200821 20230821\"\n\n!zipline ingest -b tquant<\/code><\/pre>\n\n\n\n<p>After loading the data, we can visualize what we have imported by code down below.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from zipline.data.data_portal import get_bundle\ndata_bundle = get_bundle(\n    bundle_name = 'tquant',\n    calendar_name = 'TEJ',\n    start_dt = pd.Timestamp(\"2020-08-21\", tz = 'utc'),\n    end_dt = pd.Timestamp(\"2023-08-21\", tz = 'utc')\n)\ndata_bundle.head(10)<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image size-large caption-align-center\"><img decoding=\"async\" width=\"1024\" height=\"461\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\/Screenshot-2023-08-22-090039-1024x461.png\" alt=\"\" class=\"wp-image-17179\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/Screenshot-2023-08-22-090039-1024x461.png 1024w, https:\/\/www.tejwin.com\/wp-content\/uploads\/Screenshot-2023-08-22-090039-300x135.png 300w, https:\/\/www.tejwin.com\/wp-content\/uploads\/Screenshot-2023-08-22-090039-150x68.png 150w, https:\/\/www.tejwin.com\/wp-content\/uploads\/Screenshot-2023-08-22-090039-768x346.png 768w, https:\/\/www.tejwin.com\/wp-content\/uploads\/Screenshot-2023-08-22-090039.png 1100w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Data frame for bundle<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Strategy_back-testing\"><\/span>Strategy back-testing<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In this example, let&#8217;s consider a &#8220;Buy and Hold&#8221; investment strategy for Taiwan Semiconductor Manufacturing Company (TSMC) using TQuant Lab. We will create the strategy and perform back-testing. To begin, let&#8217;s import the necessary modules:<\/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\nfrom zipline.api import order, record, symbol\nfrom zipline import run_algorithm<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"Initialize-function\"><span class=\"ez-toc-section\" id=\"Initialize_function\"><\/span>Initialize function<a href=\"http:\/\/localhost:8888\/notebooks\/Documents\/TEJ%20%E5%AF%A6%E7%BF%92\/TEJ%20Zipline\/%E4%BA%A4%E6%98%93%E7%AD%96%E7%95%A5\/TQuant%20Lab%20Rookie%20Manual.ipynb#Initialize-function\" target=\"_blank\" rel=\"noopener\"><\/a><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p><strong><code>initialize<\/code>&nbsp;<\/strong>is one of the key functions for zipline backtesting. This function would be executed once before the backtesting starts. The main purpose of this function is to set up the backtesting environment, mainly setting slippage and commission:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>zipline.api.set_slippage:<br>Set slippage model, TQuant Lab offers 4 different types of model. For detailed information, check out&nbsp;<a href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\/blob\/main\/lecture\/Zipline%20Slippage.ipynb\" target=\"_blank\" rel=\"noreferrer noopener\">Zipline Slippage<\/a>.<\/li>\n\n\n\n<li>zipline.api.set_commission:<br>Set commission model, TQuant Lab offers 3 different types of models. For detailed information, check out&nbsp;<a href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\/blob\/main\/lecture\/Zipline%20Commission%20Models.ipynb\" target=\"_blank\" rel=\"noreferrer noopener\">Zipline Commission<\/a>.<\/li>\n<\/ol>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def initialize(context):\n    set_slippage(slippage.FixedSlippage())\n    set_commission(commission.PerShare(cost=0.00285))<\/code><\/pre>\n\n\n\n<p>Besides, we can notice that there is an argument called&nbsp;<strong>context<\/strong>&nbsp;in&nbsp;<code>initialize<\/code>&nbsp;function. It is a persistent namespace for you to store variables you need to access from one algorithm iteration to the next. For example, we can set a variable (context.day = 0) to count the number of trading dates and a variable (context.has_ordered = False) to record whether holding the position of TSMC or not.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def initialize(context):\n    context.day = 0\n    context.has_ordered = False\n    set_slippage(slippage.FixedSlippage())\n    set_commission(commission.PerShare(cost=0.00285))<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"Handle_data-function\"><span class=\"ez-toc-section\" id=\"Handle_data_function\"><\/span>Handle_data function<a href=\"http:\/\/localhost:8888\/notebooks\/Documents\/TEJ%20%E5%AF%A6%E7%BF%92\/TEJ%20Zipline\/%E4%BA%A4%E6%98%93%E7%AD%96%E7%95%A5\/TQuant%20Lab%20Rookie%20Manual.ipynb#Handle_data-function\" target=\"_blank\" rel=\"noopener\"><\/a><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p><code>handle_data<\/code>&nbsp;is another key function for zipline backtesting. This function would be executed every trading day. The main purpose of this function is to establish a trading strategy, place orders, and record trading information.<\/p>\n\n\n\n<p>There are two arguments in&nbsp;<code>handle_data<\/code>&nbsp;&#8211;&nbsp;<strong>context<\/strong>&nbsp;and&nbsp;<strong>data<\/strong>.&nbsp;<strong>context<\/strong>&nbsp;is basically the same as above. To record whether we hold TSMC stock on each trading day, we set:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def handle_data(context, data):\n\n    # plus 1 in each trading day\u3002\n    context.day += 1 \n\n    # check whether we hold TSMC stock in current trading day\n    if not context.has_ordered:<\/code><\/pre>\n\n\n\n<p>Then we use&nbsp;<code>zipline.order<\/code>&nbsp;function to place orders. There are 6 different types of order methods. For detailed information, please check out<a href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\/blob\/main\/lecture\/Zipline%20Order%20(order%20%26%20order_target).ipynb\" class=\"ek-link\" target=\"_blank\" rel=\"noopener\">&nbsp;Zipline Order (percent &amp; target_percent)<\/a><a href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\/blob\/main\/lecture\/Zipline%20Order%20(percent%20%26%20target_percent).ipynb\" target=\"_blank\" rel=\"noreferrer noopener\" class=\"ek-link\">,&nbsp;<\/a><a href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\/blob\/main\/lecture\/Zipline%20Order%20(percent%20%26%20target_percent).ipynb\" target=\"_blank\" aria-label=\"Zipline Order (value &amp; target_value) (opens in a new tab)\" rel=\"noreferrer noopener\" class=\"ek-link\">Zipline Order (value &amp; target_value)<\/a><a href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\/blob\/main\/lecture\/Zipline%20Order%20(percent%20%26%20target_percent).ipynb\" target=\"_blank\" rel=\"noreferrer noopener\" class=\"ek-link\">,<\/a>&nbsp;and<a href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\/blob\/main\/lecture\/Zipline%20Order%20(value%20%26%20target_value).ipynb\" target=\"_blank\" aria-label=\" Zipline Order (order &amp; order_target) (opens in a new tab)\" rel=\"noreferrer noopener\" class=\"ek-link\"> Zipline Order (order &amp; order_target)<\/a><a href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\/blob\/main\/lecture\/Zipline%20Order%20(percent%20%26%20target_percent).ipynb\" target=\"_blank\" rel=\"noreferrer noopener\" class=\"ek-link\">. <\/a>Here, we use the most fundamental one:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"zipline.api.order\"><span class=\"ez-toc-section\" id=\"ziplineapiorder\"><\/span>zipline.api.order<a href=\"http:\/\/localhost:8888\/notebooks\/Documents\/TEJ%20%E5%AF%A6%E7%BF%92\/TEJ%20Zipline\/%E4%BA%A4%E6%98%93%E7%AD%96%E7%95%A5\/TQuant%20Lab%20Rookie%20Manual.ipynb#zipline.api.order\" target=\"_blank\" rel=\"noopener\"><\/a><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Buy or sell n share of assets.<\/p>\n\n\n\n<p>Parameters:<a href=\"http:\/\/localhost:8888\/notebooks\/Documents\/TEJ%20%E5%AF%A6%E7%BF%92\/TEJ%20Zipline\/%E4%BA%A4%E6%98%93%E7%AD%96%E7%95%A5\/TQuant%20Lab%20Rookie%20Manual.ipynb#Parameters:\" target=\"_blank\" rel=\"noopener\"><\/a><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>asset: zipline.assets.Asset<br>target asset<\/li>\n\n\n\n<li>amount: int<br>decide n share<\/li>\n\n\n\n<li>limit_price: float, optional<br>limit price<\/li>\n\n\n\n<li>stop_price: float, optional<br>stop price<\/li>\n<\/ul>\n\n\n\n<p>After adding the&nbsp;<code><strong>order(symbol(\"2330\"))<\/strong><\/code>&nbsp;for placing an order, we set&nbsp;<strong>context.has_ordered<\/strong>&nbsp;to True, so we will no longer place an order after this trading day.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def handle_data(context, data):\n\n    context.day += 1 \n    if not context.has_ordered:\n\n        order(symbol(\"2330\", 1000)\n\n        context.has_ordered = True\n<\/code><\/pre>\n\n\n\n<p>Eventually, to record the number of trading days, whether we hold TSMC stock or not, and stock price, we can use&nbsp;<strong><code>record<\/code>&nbsp;<\/strong>function. This function enables users to record trading information and turn to columns in the data frame from&nbsp;<code><strong>run_algorithm<\/strong><\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>record(column name = information)<\/code><\/pre>\n\n\n\n<p>In today&#8217;s case, we record the numbers of trading days (context.day), whether holding position or not (context.has_ordered), and today&#8217;s closed price (data.current(symbol(&#8220;2330&#8221;), &#8220;close&#8221;)). This&nbsp;<strong>data<\/strong>&nbsp;is equivalent to&nbsp;<strong>data<\/strong>&nbsp;mentioned in&nbsp;<strong><code>handle_data<\/code>&nbsp;<\/strong>arguments.&nbsp;<strong>data<\/strong>&nbsp;restores stocks&#8217; price and volume information. To get current price or volume info, we can use&nbsp;<code><strong>data.current()<\/strong><\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"zipline.data.current\"><span class=\"ez-toc-section\" id=\"ziplinedatacurrent\"><\/span>zipline.data.current<a href=\"http:\/\/localhost:8888\/notebooks\/Documents\/TEJ%20%E5%AF%A6%E7%BF%92\/TEJ%20Zipline\/%E4%BA%A4%E6%98%93%E7%AD%96%E7%95%A5\/TQuant%20Lab%20Rookie%20Manual.ipynb#zipline.data.current\" target=\"_blank\" rel=\"noopener\"><\/a><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Call stocks&#8217; current price and column<\/p>\n\n\n\n<p>Parameters:<a href=\"http:\/\/localhost:8888\/notebooks\/Documents\/TEJ%20%E5%AF%A6%E7%BF%92\/TEJ%20Zipline\/%E4%BA%A4%E6%98%93%E7%AD%96%E7%95%A5\/TQuant%20Lab%20Rookie%20Manual.ipynb#Parameters:\" target=\"_blank\" rel=\"noopener\"><\/a><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>assets: zipline.asset.Asset<br>target asset<\/li>\n\n\n\n<li>fields: str<br>target information, &#8216;close&#8217;, &#8216;open&#8217;, &#8216;high&#8217;, &#8216;low&#8217;, and &#8216;volume&#8217;.<\/li>\n<\/ul>\n\n\n\n<p>We want to record TSMC close price:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def 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\n    record(\n        trade_days = context.day,\n        has_ordered = context.has_ordered,\n        TSMC = data.current(symbol(\"2330\"), \"close\")\n    )<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"Analyze-function\"><span class=\"ez-toc-section\" id=\"Analyze_function\"><\/span>Analyze function<a href=\"http:\/\/localhost:8888\/notebooks\/Documents\/TEJ%20%E5%AF%A6%E7%BF%92\/TEJ%20Zipline\/%E4%BA%A4%E6%98%93%E7%AD%96%E7%95%A5\/TQuant%20Lab%20Rookie%20Manual.ipynb#Analyze-function\" target=\"_blank\" rel=\"noopener\"><\/a><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p><strong><code>Analyze<\/code>&nbsp;<\/strong>function is for performance and risk visualization. There are two arguments for this function. The first one is&nbsp;<strong>context<\/strong>, and it is the same as the previously mentioned one. Another one is&nbsp;<strong>perf<\/strong>, which is the final data frame from&nbsp;<code><strong>run_algorithm<\/strong><\/code>. We can use specific columns in the final data frame for visualization.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"Run_algorithm-function\"><span class=\"ez-toc-section\" id=\"Run_algorithm_function\"><\/span>Run_algorithm function<a href=\"http:\/\/localhost:8888\/notebooks\/Documents\/TEJ%20%E5%AF%A6%E7%BF%92\/TEJ%20Zipline\/%E4%BA%A4%E6%98%93%E7%AD%96%E7%95%A5\/TQuant%20Lab%20Rookie%20Manual.ipynb#Run_algorithm-function\" target=\"_blank\" rel=\"noopener\"><\/a><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>This function is for running the backtest. It will return a performance-related data frame. For detailed information, please check out&nbsp;<a href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\/blob\/main\/lecture\/TSMC%20buy%20and%20hold%20strategy.ipynb\" target=\"_blank\" rel=\"noreferrer noopener\" class=\"ek-link\">TSMC buy and hold strategy<\/a>. Here, we demonstrate the argument for this function:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>start:&nbsp;<em>pd.Timestamp<\/em>&nbsp;or&nbsp;<em>datetime<\/em>&nbsp;<br>Beginning date of back-testing<\/li>\n\n\n\n<li>end:&nbsp;<em>pd.Timestamp<\/em>&nbsp;or&nbsp;<em>datetime<\/em>&nbsp;<br>Ending fate of back-testing<\/li>\n\n\n\n<li>initialize:&nbsp;<em>callable<\/em>&nbsp; <br>call <strong>initialize <\/strong>function<\/li>\n\n\n\n<li>capital_base:&nbsp;<em>int<\/em>&nbsp;<br>capital base for back-testing<\/li>\n\n\n\n<li>handle_data:&nbsp;<em>callable<\/em>, optional <br>call <strong>handle_data <\/strong>function<\/li>\n\n\n\n<li>before_trading_start:&nbsp;<em>callable<\/em>, optional <br>call <strong>before_trading_start <\/strong>function<\/li>\n\n\n\n<li>analyze:&nbsp;<em>callable<\/em>, optional <br>call <strong>analyze <\/strong>function<\/li>\n\n\n\n<li>data_frequency:&nbsp;<em>{&#8220;daily&#8221;, &#8220;minute&#8221;}<\/em>, optional <br>set trading frequency<\/li>\n\n\n\n<li>bundle:&nbsp;<em>str<\/em>, optional<br>set bundle<\/li>\n\n\n\n<li>trading_calendar:&nbsp;<em>TradingCalendar<\/em>, optional <br>set exchange calendar<\/li>\n\n\n\n<li>benchmark_returns:&nbsp;<em>pd.Series<\/em>, optional <br>set benchmark return<\/li>\n\n\n\n<li>treasury_returns:&nbsp;<em>pd.Series<\/em>, optional <br>set risk-free rate<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>start_date = pd.Timestamp('2020-08-21',tz='utc')\nend_date = pd.Timestamp('2023-08-21',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<figure class=\"wp-block-image size-large caption-align-center\"><img decoding=\"async\" width=\"1024\" height=\"440\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\/Screenshot-2023-08-22-090152-1024x440.png\" alt=\"\" class=\"wp-image-17181\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/Screenshot-2023-08-22-090152-1024x440.png 1024w, https:\/\/www.tejwin.com\/wp-content\/uploads\/Screenshot-2023-08-22-090152-300x129.png 300w, https:\/\/www.tejwin.com\/wp-content\/uploads\/Screenshot-2023-08-22-090152-150x64.png 150w, https:\/\/www.tejwin.com\/wp-content\/uploads\/Screenshot-2023-08-22-090152-768x330.png 768w, https:\/\/www.tejwin.com\/wp-content\/uploads\/Screenshot-2023-08-22-090152.png 1095w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">returns of analyze function<\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-image size-large caption-align-center\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"488\" src=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/\/Screenshot-2023-08-22-090357-1024x488.png\" alt=\"\" class=\"wp-image-17183\" srcset=\"https:\/\/www.tejwin.com\/wp-content\/uploads\/Screenshot-2023-08-22-090357-1024x488.png 1024w, https:\/\/www.tejwin.com\/wp-content\/uploads\/Screenshot-2023-08-22-090357-300x143.png 300w, https:\/\/www.tejwin.com\/wp-content\/uploads\/Screenshot-2023-08-22-090357-150x72.png 150w, https:\/\/www.tejwin.com\/wp-content\/uploads\/Screenshot-2023-08-22-090357-768x366.png 768w, https:\/\/www.tejwin.com\/wp-content\/uploads\/Screenshot-2023-08-22-090357.png 1099w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">data frame for risk and performance<\/figcaption><\/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>The main purpose of this article is to help users understand how to use TQuant Lab. TQuant Lab is a quantitative backtesting platform developed by our company. Compared to self-built backtesting platforms, TQuant Lab offers highly accurate price and volume data, precise performance and risk calculations, and a realistic simulated trading environment. In the future, we will provide more articles about trading strategies deployed on TQuant Lab. Please stay tuned and continue to support us.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Source_code\"><\/span>Source code<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/gist.github.com\/tej87681088\/d1ad5414be7f6a7952de50920eb648b4\" class=\"ek-link\" target=\"_blank\" rel=\"noopener\">Click here to Github<\/a><\/li>\n<\/ul>\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<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.tejwin.com\/en\/insight\/what-is-the-look-ahead-bias\/\" class=\"ek-link\">What is the Look-ahead Bias ?<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.tejwin.com\/en\/insight\/how-to-avoid-common-mistakes-during-trading-loss-avoidance\/\" class=\"ek-link\">How to avoid common mistakes during trading &#8211; Loss Avoidance<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Related_link\"><\/span>Related link<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a aria-label=\"TEJ API \u8cc7\u6599\u5eab\u9996\u9801 (opens in a new tab)\" href=\"https:\/\/api.tej.com.tw\/index.html\" target=\"_blank\" rel=\"noreferrer noopener\" class=\"ek-link\">TEJ API <\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/github.com\/tejtw\/zipline-tej\" class=\"ek-link\" target=\"_blank\" rel=\"noopener\">zipline-tej<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/discord.com\/channels\/1133312771275104348\/1140917956432363550\" class=\"ek-link\" target=\"_blank\" rel=\"noopener\">Discord for TQuant Lab<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\" class=\"ek-link\" target=\"_blank\" rel=\"noopener\">TQuant-Lab<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>TQuant Lab offers a robust quantitative back-testing system with high precision performance and risk calculations, top-quality data sources, and a highly realistic simulated trading environment. It aids users in swiftly deploying a wide range of trading strategies. Feel free to click into the article to learn more information.<\/p>\n","protected":false},"featured_media":17215,"template":"","tags":[2904,2987,3006,2388,2428],"insight-category":[690,885],"class_list":["post-17186","insight","type-insight","status-publish","has-post-thumbnail","hentry","tag-beginners-guide","tag-quant","tag-tejapi-beginners-guide","tag-tquant-lab","tag-2428","insight-category-data-analysis","insight-category-tquant-lab"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/17186","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight"}],"about":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/types\/insight"}],"version-history":[{"count":0,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/17186\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media\/17215"}],"wp:attachment":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media?parent=17186"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/tags?post=17186"},{"taxonomy":"insight-category","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight-category?post=17186"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}