{"id":2268,"date":"2022-06-02T03:48:53","date_gmt":"2022-06-02T03:48:53","guid":{"rendered":"https:\/\/www.tejwin.com\/en\/insights\/prediction-of-portfolio-performance\/"},"modified":"2022-06-02T03:48:53","modified_gmt":"2022-06-02T03:48:53","slug":"prediction-of-portfolio-performance","status":"publish","type":"insight","link":"https:\/\/www.tejwin.com\/en\/insights\/prediction-of-portfolio-performance\/","title":{"rendered":"Prediction of Portfolio Performance"},"content":{"rendered":"<p class=\"wp-block-paragraph\" id=\"6b23\">Monte Carlo Simulation<\/p>\n<figure class=\"wp-block-image aligncenter caption-align-center\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1_1QAbSAIr-T1CyF5rFUPKLEA.jpg\"\/><figcaption class=\"wp-element-caption\">Photo by\u00a0<a href=\"https:\/\/unsplash.com\/@bash__profile\" rel=\"noreferrer noopener\" target=\"_blank\">Nicholas Cappello<\/a>\u00a0on\u00a0<a href=\"https:\/\/unsplash.com\/\" rel=\"noreferrer noopener\" target=\"_blank\">Unsplash<\/a><\/figcaption><\/figure>\n<h2 class=\"wp-block-heading\" id=\"d5e9\"><strong>Highlights<\/strong><\/h2>\n<ul class=\"wp-block-list\">\n<li>Difficulty\uff1a\u2605\u2605\u2605\u2606\u2606<\/li>\n<li>Simulate\u00a0future of the portfolio with Monte Carlo method.<\/li>\n<li>Reminder\uff1aWe first briefly describe the method and principle of Monte Carlo, and then will carry out data selection, simulation process and result presentation, so that readers can understand the implementation of Monte Carlo simulation process.<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"4c9b\"><strong>Preface<\/strong><\/h2>\n<p class=\"wp-block-paragraph\" id=\"36f4\">The purpose of Monte Carlo simulation is to\u00a0<strong>estimate the likely outcome of an uncertain event<\/strong>, and it works by modeling the variables of the uncertain event by assuming a probability distribution. Also, each forecast period is constantly recomputing the results with a random set of numbers, resulting in a large number of possible outcomes.<br \/>In the financial field, this method is widely used to measure the return and risk of asset portfolios, focusing more on predicting extreme trends at the end. Therefore, at the end of this article, we will also illustrate the risk-return performance of the portfolio by visualizing the results.<\/p>\n<h2 class=\"wp-block-heading\" id=\"6745\"><strong>Editing Environment and Modules Required<\/strong><\/h2>\n<p class=\"wp-block-paragraph\" id=\"c99f\">MacOS &amp; Jupyter Notebook<\/p>\n<pre class=\"wp-block-preformatted\"># Basic<br\/>import numpy as np<br\/>import pandas as pd# Graph<br\/>import matplotlib.pyplot as plt<br\/>%matplotlib inline<br\/>import seaborn as sns<br\/>sns.set()# TEJ API<br\/>import tejapi<br\/>tejapi.ApiConfig.api_key = 'Your Key'<br\/>tejapi.ApiConfig.ignoretz = True<\/pre>\n<p class=\"wp-block-paragraph\" id=\"a86a\"><a href=\"https:\/\/api.tej.com.tw\/columndoc.html?subId=42\" rel=\"noreferrer noopener\" target=\"_blank\">Security Transaction Data Table<\/a>\uff1aListed securities with unadjusted price and index. Code is \u2018TWN\/EWPRCD\u2019.<\/p>\n<p class=\"wp-block-paragraph\" id=\"3198\"><a href=\"https:\/\/api.tej.com.tw\/columndoc.html?subId=50\" rel=\"noreferrer noopener\" target=\"_blank\">Return Information Data Table<\/a>\uff1aListed securities with daily return. Code is \u2018TWN\/EWPRCD2\u2019.<\/p>\n<h2 class=\"wp-block-heading\" id=\"32e9\"><strong>Data Selection &amp; Pre-processing<\/strong><\/h2>\n<p class=\"wp-block-paragraph\" id=\"7758\"><strong>Step 1. Return Data<\/strong><\/p>\n<pre class=\"wp-block-preformatted\">ticker = ['1476', '2330', '2603', '2882']<br\/># Eclat Textile, TSMC, Cathay Financial Holdings and EVERGREENret = tejapi.get('TWN\/EWPRCD2', # \u516c\u53f8\u4ea4\u6613\u8cc7\u6599-\u5df2\u8abf\u6574\u80a1\u50f9(\u6536\u76e4\u50f9)<br\/>                  coid = ticker,<br\/>                  mdate = {'gte':'20200101'},<br\/>                  opts = {'columns': ['coid', 'mdate', 'roia']},<br\/>                  chinese_column_name = True,<br\/>                  paginate = True)<br\/>ret = ret.set_index('\u5e74\u6708\u65e5')<\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1ZRLSwHof560XNUseale-Fw.png\"\/><\/figure>\n<pre class=\"wp-block-preformatted\"># Transpose Table<br\/>RetData = {}for i in ticker:<br\/>    r = ret[ret['\u8b49\u5238\u4ee3\u78bc'] == i]<br\/>    r = r['\u65e5\u5831\u916c\u7387 %']<br\/>    RetData.setdefault(i, r)RetData = pd.concat(RetData, axis = 1)<br\/>RetData = RetData * 0.01<\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1lSTwH5Lki320mI_IXl9MbQ.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"3e36\">The data table format is converted here to facilitate the subsequent calculation of the average return of each target and the covariate between the targets.<\/p>\n<p class=\"wp-block-paragraph\" id=\"2ffc\"><strong>Step 2. Average Return, Covariance, Principal Calculation<\/strong><\/p>\n<pre class=\"wp-block-preformatted\"># Average Return<br\/>Mean = pd.DataFrame(<br\/>list(np.mean(RetData[i]) for i in RetData.columns), index=RetData.columns, columns = ['\u5e73\u5747\u503c'])# Covariance Matrix<br\/>covMatrix = RetData.cov()<\/pre>\n<figure class=\"wp-block-image aligncenter caption-align-center\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1vx91n5gUprC08L_bpfxqyg.png\"\/><figcaption class=\"wp-element-caption\">Left\uff1aAverage Return\uff1b Right\uff1aCovariance Matrix<\/figcaption><\/figure>\n<pre class=\"wp-block-preformatted\">price = tejapi.get('TWN\/EWPRCD', # Unadjusted Price<br\/>                  coid = ticker,<br\/>                  mdate = {'gte':'20220525', 'lte':'20220525'},<br\/>                  opts = {'columns': ['coid', 'mdate', 'close_d']},<br\/>                  chinese_column_name = True,<br\/>                  paginate = True)price = price.set_index('\u5e74\u6708\u65e5')principal = (price.loc['2020-05-25']['\u6536\u76e4\u50f9(\u5143)'].sum()) * 1000<\/pre>\n<p class=\"wp-block-paragraph\" id=\"d63d\">By adding up the close prices of the four underlyings on May 25, 2020, and assuming that at least one stock (1,000 shares) is held, the initial principal is $1,193,900.<\/p>\n<h2 class=\"wp-block-heading\" id=\"f302\"><strong>Simulation Condition Settings<\/strong><\/h2>\n<p class=\"wp-block-paragraph\" id=\"2fb9\"><strong>Weights, Simulation Period and Number of Simulations<\/strong><\/p>\n<pre class=\"wp-block-preformatted\"># Weights<br\/>weights = list()for i in range(4):<br\/>    weights.append(list(price['\u6536\u76e4\u50f9(\u5143)'])[i]\/price['\u6536\u76e4\u50f9(\u5143)'].sum())# Number<br\/>number_of_trial = 100# Period<br\/>sim_period = 30<\/pre>\n<p class=\"wp-block-paragraph\" id=\"020b\">In the part of weight setting, readers can make changes according to their own holdings of the target. We directly use the stock price weight ratio here and it is only for demonstration.<\/p>\n<p class=\"wp-block-paragraph\" id=\"318f\">Eclat Textile\uff1a40%\u3001TSMC\uff1a44%\u3001EVERGREEN\uff1a12%\u3001Cathay Financial Holdings\uff1a4%<\/p>\n<h2 class=\"wp-block-heading\" id=\"9a93\"><strong>Simulating Process<\/strong><\/h2>\n<pre class=\"wp-block-preformatted\">sim_mean = np.full(shape = (sim_period, 4), fill_value = Mean.T.loc['\u5e73\u5747\u5831\u916c'])<br\/>sim_mean = sim_mean.T<\/pre>\n<p class=\"wp-block-paragraph\" id=\"700e\">First, define the storage table sim_mean and fill in the average return of each target, and then transpose it to separate the individual targets.<\/p>\n<pre class=\"wp-block-preformatted\">sim_portfolio = np.full(shape = (sim_period, number_of_trial), fill_value = 0)<\/pre>\n<p class=\"wp-block-paragraph\" id=\"2d2a\">Next, define the storage table sim_portfolio as the forecast field of the portfolio, and fill each field with 0 first, and then fill in the forecast value of the forecast path for the period through calculation.<\/p>\n<pre class=\"wp-block-preformatted\">for i in range(0, number_of_trial):<br\/>    multi_normal = np.random.normal(size = (sim_period, 4))<br\/>    cholesky = np.linalg.cholesky(covMatrix)<br\/>    <br\/>    sim_return = sim_mean + np.inner(cholesky, multi_normal)<br\/>    <br\/>    sim_portfolio[:,i] = <br\/>    np.cumprod(np.inner(weights, sim_return.T)+1) * principal<\/pre>\n<p class=\"wp-block-paragraph\" id=\"ed9c\"><strong>multi_normal<\/strong>:<\/p>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1jrK0IeGsOMKePg_tq-0NAQ.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"9b8f\">It could be seen from the above figure, except for Evergreen (2603), which has serious fat-tail problem, the distribution of return for other 3 targets are roughly close to the normal distribution, so this we apply the normal distribution to each target.<\/p>\n<p class=\"wp-block-paragraph\" id=\"835d\"><strong>cholesky<\/strong>:<\/p>\n<p class=\"wp-block-paragraph\" id=\"012b\">When dealing with multi-asset investment portfolios, the lower triangular matrix of the covariance matrix is decomposed through cholesky to deal with the correlation problem between securities.<\/p>\n<p class=\"wp-block-paragraph\" id=\"c544\">Subsequently, take the inner product of the above two matrices to obtain the simulated return trend of each target; finally multiply the weight ratio of each target (also the inner product) and the initial principal to complete the simulation calculation of the investment portfolio path.<\/p>\n<h2 class=\"wp-block-heading\" id=\"dfd3\"><strong>Visualize Result of Simulation<\/strong><\/h2>\n<pre class=\"wp-block-preformatted\">plt.rcParams['font.sans-serif'] = ['Arial Unicode MS'] \uff03 Enter Chineseplt.figure(figsize=(15,8)) \uff03Set the size of graph<br\/>plt.plot(sim_portfolio)<br\/>plt.ylabel('\u6295\u8cc7\u7d44\u5408\u7d2f\u7a4d\u50f9\u503c\u8b8a\u52d5', fontsize = 15)<br\/>plt.xlabel('\u6a21\u64ec\u671f\u9593', fontsize = 15)<br\/>plt.title('\u6a21\u64ec\u8def\u5f91', fontsize = 20)<br\/>plt.show()<\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1mTznb21auD5LO_UwivxGDw.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"3a2b\">Through the simulation results this time, it can be inferred from the path at the bottom of the chart that the downside risk of the portfolio in the next month will not exceed -16% at most; while the upside return may be at most 25%. Therefore, the portfolio has lower downside risk and higher probability of upside.<\/p>\n<h2 class=\"wp-block-heading\" id=\"1924\"><strong>Conclusion<\/strong><\/h2>\n<p class=\"wp-block-paragraph\" id=\"39be\">Through the above process, I believe readers can understand the execution process of the Monte Carlo method and know that it is supported by statistical theory; however, because the Monte Carlo method is based on random probability The possible future trend does not mean that the market will be completely the same as the predicted result. If there is a large fluctuation in the market leading to extreme values, the reference of the Monte Carlo method will be reduced. Therefore, in order to maintain a leading position in the market, it is not only necessary to have clear and logical analysis results supported by data, but also to keep abreast of the flow of information. TEJ also welcomes readers to purchase the solutions in\u00a0<a href=\"https:\/\/eshop.tej.com.tw\/E-Shop\/index\" rel=\"noreferrer noopener\" target=\"_blank\"><strong>TEJ E Shop<\/strong><\/a>, I believe that readers have complete After the database, you can easily complete the trend simulation of your own asset allocation, and grasp the overall pulse of the market.<\/p>\n<h2 class=\"wp-block-heading\" id=\"9bea\"><strong>Source Code<\/strong><\/h2>\n<ul class=\"wp-block-list\">\n<li><a class=\"ek-link\" href=\"https:\/\/gist.github.com\/tej87681088\/da8869c000842b7b9dbbb7d7a1adc03a#file-tejapi_medium-17-ipynb\" rel=\"noopener\" target=\"_blank\">Click here to go Github<\/a><\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"deaf\"><strong>Extended Reading<\/strong><\/h2>\n<ul class=\"wp-block-list\">\n<li><a class=\"ek-link\" href=\"\/en\/insight\/portfolio-var\/\">Portfolio VaR<\/a><\/li>\n<li><a class=\"ek-link\" href=\"\/en\/insight\/arima-garch-modelpart-2\/\">ARIMA-GARCH Model(Part 2)<\/a><\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"afb2\"><strong>Related Link<\/strong><\/h2>\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/medium.com\/r?url=https%3A%2F%2Fapi.tej.com.tw%2Fdatatables.html%3Fdb%3DTWN%26t%3D%25E5%258F%25B0%25E7%2581%25A3%25E8%25B3%2587%25E6%2596%2599%25E5%25BA%25AB\" rel=\"noopener\" target=\"_blank\">TEJ API<\/a><\/li>\n<li><a href=\"https:\/\/eshop.tej.com.tw\/E-Shop\/Edata_intro\" rel=\"noreferrer noopener\" target=\"_blank\">TEJ E-Shop<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Monte Carlo Simulation Highlights Preface The purpose of Monte Carlo simulation is to\u00a0estimate the likely outcome of an uncertain event, and it works by modeling the variables of the uncertain event by assuming a probability distribution. Also, each forecast period is constantly recomputing the results with a random set of numbers, resulting in a large [\u2026]<\/p>\n","protected":false},"featured_media":2262,"template":"","tags":[50,65,70,71],"insight_category":[13],"class_list":["post-2268","insight","type-insight","status-publish","has-post-thumbnail","hentry","tag-market-data","tag-python","tag-tej-api","tag-quantitative-strategy","insight_category-quant-research"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/2268","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\/2262"}],"wp:attachment":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media?parent=2268"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/tags?post=2268"},{"taxonomy":"insight_category","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight_category?post=2268"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}