{"id":1463,"date":"2024-07-10T17:30:00","date_gmt":"2024-07-10T17:30:00","guid":{"rendered":"https:\/\/www.tejwin.com\/en\/insights\/running-tquant-lab-in-google-colab\/"},"modified":"2024-07-10T17:30:00","modified_gmt":"2024-07-10T17:30:00","slug":"running-tquant-lab-in-google-colab","status":"publish","type":"insight","link":"https:\/\/www.tejwin.com\/en\/insights\/running-tquant-lab-in-google-colab\/","title":{"rendered":"Tutorial on Running TQuant Lab in Google Colab and Common Errors"},"content":{"rendered":"<figure class=\"wp-block-image aligncenter size-full is-resized caption-align-center\"><img loading=\"lazy\" decoding=\"async\" alt=\"Running TQuant Lab in Google Colab \" class=\"wp-image-24848\" height=\"3648\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/jametlene-reskp-3Dtu6_XfqIk-unsplash.jpg\" style=\"width:840px;height:auto\" width=\"5472\"\/><figcaption class=\"wp-element-caption\">Photo by <a href=\"https:\/\/unsplash.com\/@reskp?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash\" rel=\"noopener\" target=\"_blank\">Jametlene Reskp<\/a> on <a class=\"ek-link\" href=\"https:\/\/unsplash.com\/photos\/silver-pocketwatch-3Dtu6_XfqIk?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash\" rel=\"noopener\" target=\"_blank\">Unsplash<\/a><\/figcaption><\/figure>\n<h2 class=\"wp-block-heading\">Summary of Key Points in This Article<\/h2>\n<ul class=\"wp-block-list\">\n<li>Article Difficulty: \u2605\u2606\u2606\u2606\u2606<\/li>\n<li>Tutorial on Running TQuant Lab in Google Colab<\/li>\n<li>Simple Test: Select the top five companies by revenue (from any industry) and backtest their returns<\/li>\n<li>Install fonts to ensure the Pyfolio package can plot graphs smoothly<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\">Introduction<\/h2>\n<p class=\"wp-block-paragraph\">For students who want to use TQuant Lab, in addition to the original GitHub installation tutorial, we now offer a faster and simpler way to use it directly on Google Colab. The tutorial on running TQuant Lab in Google Colab eliminates the need to set up a virtual environment, significantly lowering the barrier to entry.<\/p>\n<h2 class=\"wp-block-heading\">Running TQuant Lab in Google Colab and Installing some Commonly used Package<\/h2>\n<h3 class=\"wp-block-heading\">You only need one simple lines of code to complete the environment setup.<\/h3>\n<pre class=\"wp-block-code\"><code>              !pip install zipline-tej<\/code><\/pre>\n<h3 class=\"wp-block-heading\">If you encounter a pop-up window showing an error, simply click \u201cRestart Runtime\u201d to resolve it.<\/h3>\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" alt=\"Running TQuant Lab in Google Colab \" class=\"wp-image-24843\" height=\"506\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/image-453.png\" width=\"1038\"\/><\/figure>\n<h3 class=\"wp-block-heading\">In the end, you may see the following error message, but you can ignore it. The system is actually ready for use.<\/h3>\n<pre class=\"wp-block-code\"><code><mark class=\"has-inline-color has-black-color\" style=\"background-color:rgba(0, 0, 0, 0)\"><span class=\"has-inline-background\" style=\"background-color:#abb8c3\">ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\ncudf-cu12 24.4.1 requires pandas&lt;2.2.2dev0,&gt;=2.0, but you have pandas 1.5.3 which is incompatible.\ngoogle-colab 1.0.0 requires pandas==2.0.3, but you have pandas 1.5.3 which is incompatible.<\/span><\/mark><\/code><\/pre>\n<h2 class=\"wp-block-heading\">TQuant Lab Tutorial: Selecting the Top Five Semiconductor Companies by Revenue for Backtesting<\/h2>\n<h3 class=\"wp-block-heading\">Load Commonly Used Packages<\/h3>\n<pre class=\"wp-block-code\"><code>import os \nos.environ['TEJAPI_BASE'] = 'https:\/\/api.tej.com.tw'\nos.environ['TEJAPI_KEY'] = 'Your_Key'\n\nimport datetime\n\nimport tejapi\nimport pandas as pd \nimport numpy as np<\/code><\/pre>\n<h3 class=\"wp-block-heading\">First, identify all companies in the semiconductor<\/h3>\n<pre class=\"wp-block-code\"><code>from zipline.sources.TEJ_Api_Data import get_universe\n\npool = get_universe(start = '2022-07-02', \n                    end = '2023-07-02',\n                    mkt_bd_e = 'TSE',  \n                    stktp_e = 'Common Stock',  \n                    sub_ind_e=['M2324 Semiconductor', 'M2325 Computer and Peripheral Equipment'])<\/code><\/pre>\n<h3 class=\"wp-block-heading\">Check their revenue and select the top five highest, then save their stock symbols.<\/h3>\n<pre class=\"wp-block-code\"><code>import TejToolAPI\n\nstart_time = pd.Timestamp('2022-07-02')\nend_time = pd.Timestamp('2023-07-02')\n\ndata = TejToolAPI.get_history_data(start = start_time,\n                                   end = end_time,\n                                   ticker = pool,\n                                   fin_type = 'A',\n                                   columns = ['\u71df\u696d\u7e3d\u6536\u5165'],\n                                   transfer_to_chinese = True)\n\ndata  = data.drop_duplicates(subset=['\u80a1\u7968\u4ee3\u78bc'], keep='last').reset_index(drop=True)\n\ndata = data.nlargest(5, '\u71df\u696d\u7e3d\u6536\u5165_A')    #select the top five highest\n\ndata<\/code><\/pre>\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th><\/th>\n<th class=\"has-text-align-center\" data-align=\"center\">stock<\/th>\n<th class=\"has-text-align-center\" data-align=\"center\">date<\/th>\n<th class=\"has-text-align-center\" data-align=\"center\">Total_Operating_Income_A<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<th>6<\/th>\n<td class=\"has-text-align-center\" data-align=\"center\">2330<\/td>\n<td class=\"has-text-align-center\" data-align=\"center\">2023-06-30<\/td>\n<td class=\"has-text-align-center\" data-align=\"center\">508632973.0<\/td>\n<\/tr>\n<tr>\n<th>90<\/th>\n<td class=\"has-text-align-center\" data-align=\"center\">4938<\/td>\n<td class=\"has-text-align-center\" data-align=\"center\">2023-06-30<\/td>\n<td class=\"has-text-align-center\" data-align=\"center\">318136546.0<\/td>\n<\/tr>\n<tr>\n<th>27<\/th>\n<td class=\"has-text-align-center\" data-align=\"center\">2382<\/td>\n<td class=\"has-text-align-center\" data-align=\"center\">2023-06-30<\/td>\n<td class=\"has-text-align-center\" data-align=\"center\">266180950.0<\/td>\n<\/tr>\n<tr>\n<th>67<\/th>\n<td class=\"has-text-align-center\" data-align=\"center\">3231<\/td>\n<td class=\"has-text-align-center\" data-align=\"center\">2023-06-30<\/td>\n<td class=\"has-text-align-center\" data-align=\"center\">212000207.0<\/td>\n<\/tr>\n<tr>\n<th>4<\/th>\n<td class=\"has-text-align-center\" data-align=\"center\">2324<\/td>\n<td class=\"has-text-align-center\" data-align=\"center\">2023-06-30<\/td>\n<td class=\"has-text-align-center\" data-align=\"center\">209458784.0<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<pre class=\"wp-block-code\"><code>tickers = data['\u80a1\u7968\u4ee3\u78bc'].unique()<\/code><\/pre>\n<h3 class=\"wp-block-heading\">Load the data onto your local computer.<\/h3>\n<pre class=\"wp-block-code\"><code>start = '2023-07-03'\nend = '2024-07-02'\n\nos.environ['mdate'] = start + ' ' + end\nos.environ['ticker'] = ' '.join(tickers) + ' ' + 'IR0001'\n\n!zipline ingest -b tquant\n\nfrom zipline.data import bundles\nbundle_data = bundles.load('tquant')\n\nfrom zipline.api import *\nfrom zipline.finance import commission, slippage\n\ndef initialize(context):\n    context.day = 0\n    context.tickers = tickers\n    set_slippage(slippage.VolumeShareSlippage(volume_limit = 0.025, price_impact = 0.1))\n    set_commission(commission.Custom_TW_Commission(min_trade_cost = 20, discount = 1.0, tax = 0.003))\n    set_benchmark(symbol('IR0001'))\n    set_liquidity_risk_management_rule(['\u5168\u984d\u4ea4\u5272\u80a1\u7968(Full-Cash Delivery Securities)', '\u6f32\u505c\u80a1\u7968(Limit Up)', '\u8dcc\u505c\u80a1\u7968(Limit Down)', '\u958b\u76e4\u5373\u9396\u6b7b(Limited Whole Day)'])\n\ndef handle_data(context, data):\n\n    if context.day == 0:\n        for ticker in context.tickers:\n            order_percent(symbol(ticker), 1 \/ len(tickers))\n\n    context.day += 1\n\nimport matplotlib.pyplot as plt\n\ncapital_base = 1e6 \n\ndef analyze(context, results):\n\n    fig = plt.figure()\n    ax1 = fig.add_subplot(111)\n    results['benchmark_cum'] = results.benchmark_return.add(1).cumprod() * capital_base\n    results[['portfolio_value', 'benchmark_cum']].plot(ax = ax1, label = 'Portfolio Value($)')\n    ax1.set_ylabel('Portfolio value (TWD)')\n\n    plt.legend(loc = 'upper left')\n\n    plt.gcf().set_size_inches(18, 8)\n    plt.grid()\n    plt.show()\n\nfrom zipline import run_algorithm\n\nstart_date = pd.Timestamp('20230703', tz = 'utc')\nend_date = pd.Timestamp('20240702', tz = 'utc')\n\nresults = run_algorithm(\n    start = start_date,\n    end = end_date,\n    initialize = initialize,\n    handle_data = handle_data,\n    analyze = analyze,\n    bundle = 'tquant',\n    capital_base = capital_base,\n)\n\nresults<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" alt=\"Running TQuant Lab in Google Colab \" class=\"wp-image-29384\" height=\"630\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/portfolio_value-1.png\" width=\"1467\"\/><\/figure>\n<h2 class=\"wp-block-heading\">Font Issues Encountered with Pyfolio and How to Resolve Them<\/h2>\n<pre class=\"wp-block-code\"><code>from pyfolio.utils import extract_rets_pos_txn_from_zipline\nimport pyfolio as pf\n\nreturns, positions, transactions = extract_rets_pos_txn_from_zipline(results) \nbenchmark_rets = results.benchmark_return \n\nfrom pyfolio.plotting import plot_rolling_sharpe\n\nplot_rolling_sharpe(returns, factor_returns=benchmark_rets)<\/code><\/pre>\n<pre class=\"wp-block-code\"><code><mark><span class=\"has-inline-background\" style=\"background-color:#abb8c3\">WARNING:matplotlib.font_manager:findfont: Generic family 'sans-serif' not found because none of the following families were found: Microsoft JhengHei\nWARNING:matplotlib.font_manager:findfont: Generic family 'sans-serif' not found because none of the following families were found: Microsoft JhengHei\nWARNING:matplotlib.font_manager:findfont: Generic family 'sans-serif' not found because none of the following families were found: Microsoft JhengHei\nWARNING:matplotlib.font_manager:findfont: Generic family 'sans-serif' not found because none of the following families were found: Microsoft JhengHei\nWARNING:matplotlib.font_manager:findfont: Generic family 'sans-serif' not found because none of the following families were found: Microsoft JhengHei<\/span><\/mark><\/code><\/pre>\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" alt=\"Running TQuant Lab in Google Colab \" class=\"wp-image-29386\" height=\"512\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/sharpe-3.png\" width=\"716\"\/><\/figure>\n<h3 class=\"wp-block-heading\">Even though the charts have been successfully plotted, you may still encounter warnings about missing fonts. To resolve this issue, you can manually load the fonts.<\/h3>\n<pre class=\"wp-block-code\"><code>import matplotlib\nimport matplotlib.font_manager as fm\n!wget -O MicrosoftJhengHei.ttf https:\/\/github.com\/a7532ariel\/ms-web\/raw\/master\/Microsoft-JhengHei.ttf\n!wget -O ArialUnicodeMS.ttf https:\/\/github.com\/texttechnologylab\/DHd2019BoA\/raw\/master\/fonts\/Arial%20Unicode%20MS.TTF\n \nfm.fontManager.addfont('MicrosoftJhengHei.ttf')\nmatplotlib.rc('font', family='Microsoft Jheng Hei')\n \nfm.fontManager.addfont('ArialUnicodeMS.ttf')\nmatplotlib.rc('font', family='Arial Unicode MS')<\/code><\/pre>\n<h3 class=\"wp-block-heading\">After trying again, the warning messages should no longer appear.<\/h3>\n<pre class=\"wp-block-code\"><code>plot_rolling_sharpe(returns, factor_returns=benchmark_rets)<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" alt=\"Running TQuant Lab in Google Colab \" class=\"wp-image-29388\" height=\"512\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/sharpe-4.png\" width=\"716\"\/><\/figure>\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n<p class=\"wp-block-paragraph\">This introduction\u2019s testing section mostly references the code from the article \u201c<a class=\"ek-link\" href=\"\/en\/insight\/buffetts-business-investment-rules\/\">TQuant Lab Warren E. Buffett\u2019s Business Investment Rules<\/a>.\u201d You can refer to the original extended reading content if you have any questions.<\/p>\n<p class=\"wp-block-paragraph\">Additionally, this introduction allows everyone to use TQuant without needing extra virtual environment installations and extensive settings. It\u2019s much more convenient to get started right away and follow this recommended approach.<\/p>\n<div style=\"border: 1px black; border-style: solid none; text-align: center; border-color: #296580; padding: 24px; margin-top: 24px; margin-bottom: 24px;\">\n<p>\u3010TQuant Lab Backtesting System\u3011Solving Your Quantitative Finance Challenges<\/p>\n<p>Providing Comprehensive Tools for Trading Backtesting<\/p>\n<div style=\"margin-top: 32px;\"><a href=\"https:\/\/tquant.tejwin.com\/\" rel=\"noopener\" style=\"border: none; border-radius: 4px; background-color: #296580; color: white; font-size: 20px; width: fit-content; text-decoration: none; padding: 12px 30px 12px 30px;\" target=\"_blank\">Click Here to Register and Start Your Free Trial<\/a><\/div>\n<\/div>\n<h2 class=\"wp-block-heading\">Source Code<\/h2>\n<ul class=\"wp-block-list\">\n<li><a class=\"ek-link\" href=\"https:\/\/github.com\/tejtw\/TEJAPI_Python_Medium_Application\/blob\/main\/Buffett&#039;s%20Business%20Investment%20Rules.ipynb\" rel=\"noreferrer noopener\" target=\"_blank\">C<\/a><a href=\"https:\/\/github.com\/tejtw\/TEJAPI_Python_Medium_Quant\/blob\/main\/Google%20Colab%20%E6%95%99%E5%AD%B8.ipynb\" rel=\"noreferrer noopener\" target=\"_blank\">lick Here to Github<\/a><\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\">Extended Reading<\/h2>\n<ul class=\"wp-block-list\">\n<li><a class=\"ek-link\" href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\/blob\/main\/lecture\/Install%20TQuant%20Lab.ipynb\" rel=\"noopener\" target=\"_blank\">Install TQuant Lab<\/a><\/li>\n<li><a class=\"ek-link\" href=\"https:\/\/github.com\/tejtw\/TEJAPI_Python_Medium_Application\/blob\/main\/%E5%B7%B4%E8%8F%B2%E7%89%B9%E4%BC%81%E6%A5%AD%E6%8A%95%E8%B3%87%E6%B3%95%E5%89%87%E9%81%B8%E8%82%A1%E7%AD%96%E7%95%A5.ipynb\" rel=\"noopener\" target=\"_blank\">Buffett\u2019s Business Investment Rules<\/a><\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\">Relevant Links<\/h2>\n<ul class=\"wp-block-list\">\n<li><a class=\"ek-link\" href=\"\/en\/\">TEJ Official Website<\/a><\/li>\n<li><a class=\"ek-link\" href=\"https:\/\/github.com\/tejtw\/TQuant-Lab\" rel=\"noreferrer noopener\" target=\"_blank\">TQuant Lab Github<\/a><\/li>\n<li><a class=\"ek-link\" href=\"https:\/\/tquant.tejwin.com\/\" rel=\"noopener\" target=\"_blank\">TQuant Lab Homepage<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>For students who want to use TQuant Lab, in addition to the original GitHub installation tutorial, we now offer a faster and simpler way to use it directly on Google Colab. The tutorial on running TQuant Lab in Google Colab eliminates the need to set up a virtual environment, significantly lowering the barrier to entry.<\/p>\n","protected":false},"featured_media":1462,"template":"","tags":[70,91],"insight_category":[16],"class_list":["post-1463","insight","type-insight","status-publish","has-post-thumbnail","hentry","tag-tej-api","tag-beginners-guide","insight_category-quant-data-science"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/1463","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"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media\/1462"}],"wp:attachment":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media?parent=1463"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/tags?post=1463"},{"taxonomy":"insight_category","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight_category?post=1463"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}