<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Marco Lomele on Medium]]></title>
        <description><![CDATA[Stories by Marco Lomele on Medium]]></description>
        <link>https://medium.com/@marcolomele?source=rss-f3ff793a48f7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pL46N7tbHTAnahRw3Wts9g.jpeg</url>
            <title>Stories by Marco Lomele on Medium</title>
            <link>https://medium.com/@marcolomele?source=rss-f3ff793a48f7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 05:15:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marcolomele/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Cracking the Brand Factor with Bayesian Marketing Mix Modelling]]></title>
            <link>https://medium.com/@marcolomele/cracking-the-brand-factor-with-bayesian-marketing-mix-modelling-51a007e87520?source=rss-f3ff793a48f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/51a007e87520</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[econometrics]]></category>
            <category><![CDATA[marketing-mix-modeling]]></category>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[marketing-analysis]]></category>
            <dc:creator><![CDATA[Marco Lomele]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 10:38:12 GMT</pubDate>
            <atom:updated>2024-09-02T15:30:45.626Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring the Marketing-Brand-Sales relationship with Bayesian Vector Auto-Regression and Impulse Response Functions.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kKJA2U2v-fjj6A9Vo1E5JA.png" /></figure><h3>The Secret Sauce</h3><p>Is the iPhone superior to Samsung’s phones? Does Nike make better shoes than Adidas? How can Prada sell a plain white T-shirt at €100? The products of some companies just feel more valuable than others and we are willing to spend more money on them, even if we can get the same features at a lower cost. This is the power of a <strong>brand</strong>.</p><p>A company’s brand is the set of qualities that create recognition, customer loyalty, and distinction from competitors. Therefore, companies must leverage marketing to elevate their brand and boost sales. However, putting a<strong> number on brand</strong> and comparing it across time is difficult. How did Apple’s brand change between this month and last month?</p><p>At <a href="https://nepa.com/">Nepa</a>, we strive to solve this problem. We combine data-driven technologies with human analysis to track brands and help clients define budget-efficient marketing strategies. Given that we can quantify brand value, we can explore this more nuanced question:</p><blockquote><em>Is there a causal relationship between marketing, brand, and sales?</em></blockquote><p>In this article, we present our research towards this question. First, you will learn about Marketing Mix Modelling (MMM), a statistical method to study the effectiveness of marketing. Then, we will look into our <strong>econometrics model</strong> and how we enhanced it with Bayesian statistics. Finally, we will simulate marketing campaigns with Impulse Response Functions.</p><h3>Marketing meets Statistics</h3><p>Marketing Mix Modelling (MMM)<strong> </strong>is rooted in the history of marketing science and statistics. The “marketing mix” was introduced in the late 1940s as the set of variables marketers control to influence consumer decisions, like price and promotion. Nowadays, companies collect data about their mix in the form of time series. A <strong>time series</strong> is a sequence of measurements of some variable taken at equal intervals in time.</p><p>Marketing Mix Modelling is applying statistics to these time series. At its core, MMM aims to optimise marketing spend by identifying which media channels deliver the <strong>highest return on investment</strong> (ROI). This means finding which advertisements produce the most sales revenue without costing too much.</p><h4>Baseline Sales</h4><p>The fundamental idea of MMM is that not all sales happen because of marketing. Total sales, what the company measures, is made of incremental sales and baseline sales. Incremental sales happen because of marketing. Baseline sales represent the demand for a product in the <strong>absence of marketing</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZCgttVXBe5_w1Nz-ZDl1-Q.png" /><figcaption>MMM distinguishes between baseline sales and actual sales.</figcaption></figure><p>Baseline sales are driven by many factors, including <strong>brand equity</strong>. If all companies stopped advertising their products, it is reasonable to think that consumers would purchase from the companies they know and feel better about. Nonetheless, marketing is necessary to build the brand of a company and without it, brand value decreases.</p><h4>Media Spending</h4><p>MMM also points out that spending data is misleading. First, it does not account for <strong>carry-over effects</strong>, the prolonged impact that advertising has on sales because consumers take time to decide what to buy.</p><p>Second, it omits the <strong>diminishing returns</strong> of the channels. Channels saturate when no more new customers can be reached. At that point, purchasing more ads will only increase the frequency of exposure among the same audience, resulting in minimal additional impact on sales and a less efficient use of the marketing budget.</p><p>As a solution, MMM applies two transformations to media spending:</p><ul><li><strong>Adstock</strong> for carryover effects, which spreads out spending in time;</li><li><strong>Saturation</strong> for diminishing returns, which squishes the extreme values of the data.</li></ul><p>Common MMM techniques model the relationship between sales and spending in different media channels. While these solutions have been effective for short-term scenarios, they omit brand and thus overlook the causal relationship between marketing, brand value, and baseline sales.</p><h3>Problem Representation</h3><h4>Vector Auto-Regression</h4><p>We explore the relationship between marketing, brand value, and baseline sales using a Vector Auto-Regressive (VAR) process. The <strong>process of a time series</strong> is a mathematical function that describes how the target series is generated at each time step.</p><p>Take daily ice cream sales as an example. A good process for ice cream sales will consider the factors causing ice cream demand, such as the season of the year, the weather, and the presence of special events. These are called <strong>exogenous</strong> <strong>components</strong> because they are external variables. The challenge in time series modelling is that exogenous variables are not always available or known, especially for more complex series.</p><p>One solution to define an <strong>auto-regressive</strong> process. This means that the value of the series at time <em>t</em> depends on some values of the series at times before <em>t</em>, called lags. Lags represent the <strong>endogenous component </strong>of a process since they originate within the process itself. If we notice a weekly pattern in ice cream demand, then we can use ice cream sales from 7 days ago to predict the sales of today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OdfNeAzZpnP_DpNIJpbPZA.png" /><figcaption>Example time series process for modelling ice cream sales.</figcaption></figure><p>VAR extends the principle of auto-regression to <strong>multiple time series</strong>. It is used to capture the relationships and interdependencies between multiple variables as they change over time. In essence, VAR defines a system of equations where each variable is influenced by its past values and the past values of all the other variables in the system.</p><h3>The Marketing-Brand-Sales Model</h3><p>We set baseline sales and brand value as the target variables, meaning that we build a 2-dimensional VAR process. Additionally, we include spending data for various marketing channels like Google Ads, TV, and Instagram.</p><p>We assume the following <strong>causal</strong> <strong>relationship</strong>: marketing activity increases the awareness and perception of the value of the brand, which in turn causes baseline sales to rise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFfvNJDMseWndGMbqCWQJg.png" /><figcaption>Assumed relationship: marketing improves brand value, which in turn increases baseline sales.</figcaption></figure><p>Mathematically, our VAR model is defined as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*baqfnA1AKd34Qow8" /></figure><p><em>Y(0,t)</em> is the value of baseline sales at time <em>t</em>, <em>Y(1,t)</em> is the value of brand at time <em>t</em>, <em>Y(0,t-i)</em> is the value of baseline sales i lags before <em>t</em>, and <strong><em>X</em></strong><em>(t-j)</em> is the value of marketing spending <em>j</em> lags before <em>t</em>. The lags of the target variables are the endogenous components and all the lags of <strong><em>X</em> </strong>are the exogenous components.</p><p>Looking at <em>Y(0,t)</em>, we have the following <strong>coefficients</strong>, which indicate the importance of the lags. <em>c(0,0,i)</em> and <em>c(0,1,i)</em> are the weights on the lagged values of baseline sales and the lagged values of brand respectively. <em>c(0,1,i)</em> is called an inter-series coefficients. <strong><em>d</em></strong><em>(0,j)</em> is the coefficients on the lagged values of spending, and <em>ε(0)</em> is the error term. The same logic applies to the computation of brand value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*l39YPlM5dZKVZWfo8Sf49g@2x.jpeg" /><figcaption>Example VAR process visualised.</figcaption></figure><h3>Bayesian Inference</h3><p>The next step is to learn the coefficients of the model such that it fits the data as closely as possible. We use Bayesian inference. Instead of treating coefficients as deterministic numbers, Bayesian inference handles each coefficient as an independent random variable with a <strong>probability distribution</strong>.</p><p>This is advantageous over frequentist statistical models for two reasons. First, it allows us to inject <strong>prior beliefs</strong> about the coefficients, which reduces the search space of the problem. Second, it allows us to <strong>quantify</strong> the <strong>uncertainty</strong> about the model’s results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GaVFutt6PvXqdsR8dErKug.png" /><figcaption>Bayes’ rule for the unnormalised posterior distribution.</figcaption></figure><p>To perform Bayesian inference, we follow <strong>Bayes’ rule.</strong> First, we define one <strong>prior </strong>distribution <em>P(θ)</em> for each coefficient <em>θ</em> of the model. Combined, these priors represent our belief about the parameters before seeing the data <em>D</em>. For example, we set a Half-Normal distribution on <strong><em>d</em></strong> because we assume it can only take positive values, since marketing spending will always increase the awareness of a brand, and so the number of baseline sales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7salQLdDacitPxEAf3ssA.png" /><figcaption>Half-Normal Distribution.</figcaption></figure><p>Next, we compute the <strong>likelihood</strong> <em>P(D | θ)</em> using the observed data, a new distribution expressing how likely it is to observe the data given each coefficient value.</p><p>The last step is to combine the prior and the likelihood, forming the unnormalised <strong>posterior</strong> distribution <em>P(θ | D)</em>. This third distribution represents the updated beliefs about the coefficients after considering the data. However, computing <em>P(θ | D) </em>is unfeasible due to the large number of coefficients in our model.</p><p>To overcome this issue, Bayesian inference approximates the posterior. The most popular approach are <strong>Markov Chain Monte Carlo</strong> (MCMC) algorithms. MCMC simulates draws from a probability distribution in the form of random walks. Over time, through complex accept-reject rules, the distribution of the samples converges to the distribution that is being simulated. Another effective solution could be Stochastic Variational Inference, which is faster but less accurate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DMpKePgU94h5v4Jy9n5ibw.png" /><figcaption>Markov Chain Monte Carlo sampling algorithm visualised.</figcaption></figure><p>The result is a large collection of numbers divided into groups of <strong>samples</strong> that act as possible coefficients for our model. Each sample of coefficients represents a slightly different model. Therefore, we take the average across the samples to get the final model.</p><h3>Testing the Model</h3><p>After estimating the coefficients of the model, we must verify if they are <strong>informative</strong>. We run two tests. First, we check the fit accuracy. This will show whether our Bayesian VAR has captured some relationship between marketing, brand value, and baseline sales. Second, we simulate marketing campaigns with Impulse Response Functions and compare the ROIs with historical data.</p><h4>Fit Accuracy</h4><p>We evaluate the fit of the model on the same data that was used to learn the coefficients because our scope is to test a hypothetical causal relationship, not to learn general patterns to forecast the future.</p><p>To compute fit accuracy, we give the model only some initial time steps. Then, we generate values to have a “predicted” series of the same length as the original series and compare the results. In particular, we compute the Symmetric Average Percentage Error (SMAPE) and the Mean Squared Error (MSE), two standard <strong>error metrics</strong> for time series analysis. The results are plotted below. The data has been scaled between 0 and 1 using MinMax.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x-d_BPAalW2fVN6X" /><figcaption>Fit accuracy for VAR.</figcaption></figure><p>A good fit and the low error metrics suggest that Bayesian VAR <strong>modelled effectively</strong> the series. Moreover, when looking at the mean intra-series coefficients we find non-zero values, highlighting a dynamic relationship between the two series. In particular, past values of the brand have a stronger effect on baseline sales than vice-versa, supporting our initial hypothesis.</p><h4>Simulating Marketing Campaigns</h4><p>We simulate a marketing campaign with our model by generating an <strong>Impulse Response Function (IRF)</strong>. The IRF of a model describes the evolution of the target variables following a voluntary change in one of the exogenous variables, called impulse or “shock”.</p><p>The typical shape of an IRF resembles the movement of the water when you throw a rock in a puddle. Before the throw (the shock), the water is static (the system is stable). Immediately after the throw, there is a splash (a peak), but then the movement slows down (effect decay) until it becomes perfectly static again (back to stability).</p><p>In the context of MMM, a shock is defined as <strong>spending money</strong> in a marketing channel. Assuming that the model is correct, we can use its IRF to simulate a marketing campaign in a complete vacuum, without effects from external factors. In practice, the IRF is calculated as follows:</p><ol><li>Define the shock <em>s</em> and when it will be applied, say at some time <em>t*</em>.</li></ol><p>2. For all time steps before <em>t*</em>, spend 0 in all the marketing channels, which produces 0 baseline sales and 0 brand value.</p><p>3. At <em>t*</em>, spend <em>s </em>amounts of money in one channel.</p><p>4. For all time steps after <em>t*</em>, return to spending 0 in all channels.</p><p>The <strong>effect</strong> of that single investment will <strong>propagate</strong> in the model and produce a 2-dimensional response curve. Each point on the response curve of baseline sales is the sales revenue at a specific time generated by the shock. These are not incremental sales, because their value is the result of past baseline sales, past brand values, and past marketing spending.</p><p>Using the example model we simulate a marketing campaign of about €130,000 in Google Ads:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FShqVAkcxIsmFfAivK_-Iw.png" /><figcaption>Impulse Response function for Google Ads.</figcaption></figure><p>The get the ROI of the simulated marketing campaign, we sum all the values of the response curve on baseline sales, subtract the shock, and divide by the shock. The sales revenue generated by the campaign is approx. €240,000, which converts to an ROI of 169%.</p><p>The <strong>shape</strong> of the <strong>IRF</strong> is also informative. Brand value responds quickly to the shock, with a very steep initial increase. In contrast, baseline sales grow slower and peak 7 weeks after brand value. 75 weeks after the campaign, baseline sales return to 0, indicating that the effect of the Google Ads campaign has fully dissolved.</p><p>The last step is to find the shock yielding the <strong>highest ROI</strong> and compare that ROI with historical data. Due to decreasing marginal returns on the channels, we expect that some shocks will be more profitable than others. The ROIs for different channels are displayed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eJmmX9XIiD-7zGkUSCMIFA.png" /><figcaption>Comparing ROIs across marketing channels.</figcaption></figure><p>The results support the theory, and all channels have an optimal shock level. Additionally, we find that some channels are more profitable than others and that some shocks produce negative ROIs, meaning that the marketer would lose money.</p><h3>Future Developments</h3><p>The purpose of this article was to explore a plausible relationship with a novel approach. We hope that our analysis can serve as inspiration for anyone who continues pursuing this research.</p><p>Our approach is statistically robust, interpretable, and easily adaptable to various datasets. Target variables can be added to study even more complex relationships between advertisements and sales, and priors can be modified to best suit the context in which the model is used.</p><p>The main challenge is to isolate the causal effect between variables. Customers are influenced by countless factors when making purchasing decisions, and react to different marketing based on the product they are looking for. Moreover, companies run advertisements in parallel, making it difficult to determine which channel caused a sale. Finally, there is the topic of touchpoint attribution in path analysis.</p><p>Our goal is to incorporate the brand factor in Marketing Mix Modelling tools that update in real-time, as we believe it will grant us superior understanding of the marketing industry. We are certain that this project has been a significant step towards this goal.</p><p>If you are curious about how we can quantify brand and what other advanced tools we offer, follow our <a href="https://nepa.com/blog/">blog</a> and check our <a href="https://nepa.com/">website</a>!</p><figure><a href="https://www.linkedin.com/in/marco-lomele"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FLNzotC8NB10aHYffXNoWA.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51a007e87520" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evolutionary Portfolio Optimisation]]></title>
            <link>https://medium.com/@marcolomele/evolutionary-portfolio-optimisation-e37873e8cf61?source=rss-f3ff793a48f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e37873e8cf61</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[evolutionary-algorithms]]></category>
            <category><![CDATA[financial-analysis]]></category>
            <category><![CDATA[portfolio-optimisation]]></category>
            <dc:creator><![CDATA[Marco Lomele]]></dc:creator>
            <pubDate>Mon, 15 Apr 2024 11:12:26 GMT</pubDate>
            <atom:updated>2024-06-10T21:55:17.673Z</atom:updated>
            <content:encoded><![CDATA[<h4>Maximising the Sharpe Ratio of a Markowitz Model Portfolio using the Covariance Matrix Adaptation Evolution Strategy</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_pOdNkvazk91af8RdA7jEA.jpeg" /><figcaption>Charles Darwin’s finches.</figcaption></figure><p>Evolutionary Algorithms are a prominent optimisation technique in computer science, known for their robustness and versatility. The Markowitz Model addresses a classic problem in finance: explaining how to create a lucrative investment portfolio with minimal risk.</p><p>In this article, we will combine these topics. We will implement an evolutionary strategy known as Covariance Matrix Adaptation to find the most efficient portfolio of stocks over the past 15 years</p><h3>Evolutionary Algorithms</h3><p><a href="https://www.sciencedirect.com/topics/computer-science/evolutionary-algorithms#:~:text=Evolutionary%20Algorithms%20(EAs)%20are%20efficient,solutions%20of%20complex%20optimization%20problems.">Evolutionary Algorithms</a> are a family of techniques used to solve optimisation problems.</p><p>Given an objective function <em>f</em>, called the fitness function, we want to find the input <em>x</em> that maximises the output value <em>f(x)</em> subject to some constraints.</p><p>This process involves exploring the solution space — a complete set of potential solutions generated by all possible input combinations.</p><h4>Inspired By Nature</h4><p>Darwinian natural selection has created the best problem solver in nature: the human brain. Evolutionary Algorithms replicate many of its key principles.</p><p><strong>Selection</strong></p><p>A population of individuals exists in an environment with limited resources, which creates competition. Each individual is unique, and those with better traits have a higher chance of surviving. The fittest individuals reproduce more frequently, which gradually improves the overall quality of the population.</p><p>Selection can be visualized using the adaptive landscape metaphor. By examining all possible combinations of two traits, we can identify pairs that increase the chances of survival. Over time, the population evolves towards these advantageous combinations. Selection reduces diversity in the population and improves its fitness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ee95f8taf3ER9miyTO4kuw.jpeg" /><figcaption>The Adaptive Landscape. Selection will push the population towards high-fitness regions.</figcaption></figure><p><strong>Variation</strong></p><p>As individuals live and reproduce, they experience small, random variations in their DNA. These mutations slightly alter traits, which can lead to improvements or declines in fitness. Overall, variation introduces novelty into the population, counteracting the decrease in diversity caused by the selection process.</p><h4>Framework</h4><p>This is the general scheme of any Evolutionary Algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J3CjTIPeJ3p5_LUudQHBYg.png" /><figcaption>General scheme of Evolutionary Algorithms</figcaption></figure><p>Evolution is represented by the blue loop. Once initialized, it repeatedly cycles between selecting parents, applying variation, generating offspring, and selecting which offspring will join the population. The process is repeated for many generations until a predefined termination condition is met.<em> </em>Below are the key components of any Evolutionary Algorithm:</p><ul><li>Representation: how individuals are defined.</li><li>Individuals: the static entities of a population.</li><li>Population: multiple sets of diverse individuals that evolve in fitness.</li><li>Fitness function: how individuals are evaluated.</li><li>Selection mechanisms: criteria for choosing which individuals survive and become parents, operating on the population level.</li><li>Variation mechanisms: process for generating new individuals, operating on the individual level.</li><li>Termination: condition to stop the evolution.</li></ul><p><strong>Optimisation</strong></p><p>In optimisation problems, individuals are called “candidate solutions” because they represent a potential solution to the problem at hand. Each individual/candidate possesses a set of traits/parameters that determine the value of a fitness/objective function. Over successive generations, these candidate solutions are iteratively updated so they converge towards the optimum of the objective function.</p><p>Searching the solution space involves the exploration-exploitation tradeoff. At an early stage, the population is randomly initialised, and therefore exploration (i.e. variation) is emphasised to move away from low-fitness regions.</p><p>At a later stage, the population starts to concentrate on high-fitness regions, and exploitation (i.e. selection) becomes crucial to focus on such areas. Failure to balance this trade can lead to premature convergence or inefficient search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ugwbvby9Ul5rtbhwTxjS3Q.png" /><figcaption>The exploration-exploitation tradeoff while searching the solution space.</figcaption></figure><h3>Covariance Matrix Adaptation</h3><p>In 2016, Nikolaus Hansen introduced the <a href="https://arxiv.org/pdf/1604.00772.pdf">Covariance Matrix Adaptation (CMA) Evolution Strategy (ES)</a>, a novel optimisation algorithm that explores the solution space by evolving the statistics of a search distribution.</p><p>The main idea is to generate points from the search distribution, select the best ones according to a fitness function, and update the distribution so the points of the next generation on average will have higher fitness. Visually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tSKqH5nB8CqegEdKMQSwnQ.png" /><figcaption>CMA-ES visualized. The red plus is the mean of the updated search distribution and the circle is its covariance.</figcaption></figure><p>Imagine a space where the fitness function defines the top right corner to be the optimal point. CMA-ES works as follows. First, it samples points from the search distribution. These are the black dots on the left. Then, it selects the points closer to the optimum, as shown in the middle. Finally, it mutates the mean and covariance of the search distribution, ending the evolutionary cycle going from generation <em>g </em>to<em> </em>generation <em>g+1.</em></p><h4>Selection</h4><p>At each generation <em>g=1,2,…</em>, we sample a total of <em>λ</em> points from a multivariate normal distribution <em>𝒩</em>. These points are the candidate solutions for the new generation. Since they are used to search the solution space, we call them search points. The <em>k</em>-th search point is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AoeGAdJNFS2T7xhR4N-i_Q.png" /></figure><p>where <strong><em>m</em></strong><em>⁽ᵍ⁾ </em>is the mean of search distribution, <em>σ⁽ᵍ⁾ </em>is the step size, and <em>C⁽ᵍ⁾ </em>is the covariance matrix. Using the sampled search points, we update the parameters of the search distribution.</p><h4>Mutation</h4><p><strong>Mean</strong></p><p>The mean <strong><em>m</em></strong><em>⁽ᵍ⁺¹⁾</em> of the search distribution at generation <em>g+1 </em>is a weighted average of the top <em>μ </em>search points that we sampled in the previous step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpHHR4xD0XK_FBlMuntkxA.png" /></figure><p>The top search points are those points that maximise the fitness function, as shown by the subscript <em>i: λ, </em>which stands for “<em>i-</em>th fittest” point. We then set the weights to be larger for the fittest points to ensure that they have a greater impact on the mean of the next generation.</p><p><strong>Covariance Matrix</strong></p><p>The covariance matrix <em>C⁽ᵍ⁺¹⁾ </em>of the search distribution at generation <em>g+1 </em>is a weighted combination of the previous covariance matrix <em>C⁽ᵍ⁾</em>, (1) a rank-<em>μ </em>update, and (2) a rank-one update. In particular:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kUtkZHI5nHb3dJ9c9YawXA.png" /></figure><p>(1) Rank-<em> μ </em>update: uses the standardised and weighted sample covariance matrix. These weights are different from those of the previous steps. We call it sampled because:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SizKp0eEH_uGuoMQm9HSjg.png" /></figure><p>(2) Rank-one update: leverages the concept of the evolution path. An evolution path is a trajectory traced across the search space by the mean as it evolves through generations. We add learning rate factors, discount paths of older generations, and use a specific value of <em>μ </em>to get the new path:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*nqOxY1eBqrAczZyFPVy7Mg.png" /></figure><p><strong>Step Size</strong></p><p>The step size <em>σ⁽ᵍ⁺¹⁾ </em>of the search distribution at generation <em>g+1 </em>is computed using another evolutionary path and the step size’s expected length. Intuitively, there are three scenarios.</p><p>1. If steps are pointing in similar directions, they are correlated, and the same distance could be covered by longer and fewer steps; step size should be increased.</p><p>2. If steps are pointing in opposite directions, they are anti-correlated and cancel each other out; step size should be decreased.</p><p>3. If steps are perpendicular, they are uncorrelated, and no improvement can be made. We are in the ideal scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eXfrHJNstyQrAFIqGOSjDQ.png" /><figcaption>Correlated (left), anti-correlated (centre), and uncorrelated (right) steps.</figcaption></figure><h3>Portfolio Optimisation</h3><p>To test the effectiveness of CMA-ES for optimising multivariate functions, we explore a popular problem in finance: portfolio optimisation using the Markowitz model.</p><p>This problem is suitable for testing CMA-ES because it provides a large solution space and also has an exact solution that can be derived analytically.</p><p>We will begin with a brief overview of the Markowitz model. Following that, we will apply CMA-ES to optimize a real portfolio and then compare its performance against PyPortfolioOpt, a widely used Python library.</p><h4>Markowitz Model</h4><p>The <a href="https://en.wikipedia.org/wiki/Markowitz_model">Markowitz Model</a> is a portfolio optimisation model that introduces the concept of an efficient portfolio.</p><p>Given a portfolio with <em>n</em> assets, the investor achieves efficiency on that portfolio if he/she allocates assets in a way that either maximises the portfolio’s expected return for a given level of risk (variance) or minimises the portfolio’s risk for a given level of expected return.</p><p>Risk is quantified by the variance of an asset; higher variance indicates more unpredictable returns. The asset allocation within the portfolio is determined by a vector <strong><em>w</em></strong>, which consists of percentage values that sum to 1, representing the proportion of the portfolio invested in each asset.</p><p>Under certain assumptions, the set of all optimal portfolios forms what is known as the efficient frontier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_cLpK3xrXojC-CKtbaG2lg.png" /><figcaption>The blue line is the efficient frontier and the red dots are inefficient portfolio allocations.</figcaption></figure><p>One way to choose a point on the efficiency frontier is by maximising the <a href="https://www.investopedia.com/terms/s/sharperatio.asp">Sharpe ratio</a>. Assuming a risk-free rate of <em>0</em>, which represents the return on an investment with no risk, the Sharpe ratio is defined as the ratio between the portfolio’s expected returns to its standard deviation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X06rZz5h2cU0fY6SaLqiCw.png" /></figure><p><em>θ</em><strong><em> </em></strong>holds the average returns of each asset, <em>Σ </em>is the variance-covariance matrix between the returns, and <strong><em>w </em></strong>is the weight vector indicating the allocation of the assets in the portfolio.</p><p>Intuitively, the ratio measures how much excess return you receive for the extra volatility that you endure for holding a riskier asset. The asset with the higher Sharpe ratio is typically preferred because it suggests that it has more effectively used risk to achieve returns.</p><h4>Experiment</h4><p>We have a portfolio with ten assets: Apple (AAPL), Amazon (AMZN), Gold (GLD), Alphabet (GOOGL), Goldman Sachs (GS), Meta (META), Netflix (NFLX), Pfizer (PFE), Siemens (SIEGY), and Toyota (TM).</p><p>The optimisation problem is:</p><blockquote><em>What allocation of assets maximises the Sharpe ratio of our portfolio?</em></blockquote><p><strong>Data Processing</strong></p><p>First, we download closing price data from Yahoo Finance using <a href="https://pypi.org/project/yfinance/"><em>yfinance</em></a> and compute daily log returns. The full code is available on my <a href="https://github.com/MarcoLomele/cma_study/tree/main">GitHub</a>.</p><pre>$ python -m pip install yfinance<br><br>import yfinance as yf<br>from datetime import datetime<br><br>def calc_returns(prices):<br>    return np.log(prices/prices.shift(1)).dropna()<br><br># Time window for experiment<br>start_date = datetime(2023, 1, 1)<br>end_date = datetime(2024,3,1)<br><br># Assets in portfolio, sorted by ticker. <br>stocks = &#39;AAPL AMZN GLD GOOGL GS META NFLX PFE SIEGY TM&#39;<br><br># Price data from Yahoo Finance<br>prices = yf.Tickers(stocks)<br>prices = prices.history(start = start_date, end = end_date)[&#39;Close&#39;]<br>daily_returns = calc_returns(prices)</pre><p>Then, we compute the expected returns, the standard deviation, and the Sharpe ratio of the portfolio.</p><pre>def expected_returns(weights, mean_returns):<br>    return np.dot(weights, mean_returns)<br><br>def portfolio_std(weights, returns_covmat):<br>    return np.sqrt(np.dot(weights.T, np.dot(returns_covmat, weights)))<br><br>def sharpe_ratio(weights, mean_returns, returns_covmat):<br>    weights /= np.sum(weights)<br>    R = expected_returns(weights, mean_returns)<br>    sigma_p = portfolio_std(weights, returns_covmat)<br>    return (R) / sigma_p<br><br># Compute returns&#39; statistics<br>returns = daily_returns<br>mean_returns = returns.mean()<br>returns_covmat = returns.cov()</pre><p><strong>Optimisation</strong></p><p>Next, we code the optimisation problem with CMA-ES. This involves formulating the fitness function, defining the evolution strategy with the <a href="https://pypi.org/project/cma/"><em>cma</em></a> library, and initialising the allocation weights uniformly across assets.</p><p>The fitness function integrates the Sharpe ratio with a scaled penalty factor to discourage allocation weights from falling below zero. It’s important to note that the sign of the fitness function is inverted because <em>cma</em> minimises the value of the objective function it receives, whereas we aim to maximise the Sharpe ratio.</p><pre>$ python -m pip install cma<br><br>def objective_function(weights, mean_returns, returns_covat, alpha_penalty):<br>    fitness = sharpe_ratio(weights, mean_returns, returns_covat) <br>    fitness += alpha_penalty * min(0, weights.min())<br>    return -1*fitness<br><br># Uniform weight initialisation<br>num_assets = returns.shape[1]<br>initial_weights = np.ones(num_assets) / num_assets<br><br>initial_sigma = 1<br>alpha_penalty = 100<br><br># Evolutinary Algorithm initialisation<br>es = cma.CMAEvolutionStrategy(initial_weights, initial_sigma)<br><br>while not es.stop():<br>    candidate_solutions = es.ask()<br>    objective_values = [<br>        objective_function(s, mean_returns, returns_covmat, alpha_penalty)<br>        for s in candidate_solutions]<br>    es.tell(candidate_solutions, objective_values)<br>    es.disp()<br><br># Solution<br>cma_solution = np.round(es.result.xbest, 5)<br>cma_solution = list(zip(stocks.split(), cma_solution))<br>cma_sharpe = -es.result.fbest</pre><p>For each generation, <em>es.ask()</em> samples search points from the search distribution, <em>objective_function </em>evaluates the candidates, and <em>es.tell() </em>updates the parameters of the search distribution. The loop is repeated until <em>es.stop()</em> becomes <em>True</em>.</p><p><strong>Benchmark</strong></p><p>To assess the results, we run the same maximisation problem using the <em>pypfopt</em> library, which finds the optimal solution analytically and can therefore be treated as the benchmark.</p><pre>$ python -m pip install pypfopt<br><br>from pypfopt.efficient_frontier import EfficientFrontier<br>ef = EfficientFrontier(mean_returns, returns_covmat)<br>weights = ef.max_sharpe(risk_free_rate = 0.0)<br><br># Solution<br>benchmark_solution = list(ef.clean_weights().items())<br>benchmark_sharpe = ef.portfolio_performance(risk_free_rate = 0.0)[2]</pre><h4><strong>Results</strong></h4><p>To compare the two approaches, we simulate three different investment strategies. In particular, we look at 1 year, 7 years, and 15 years of investing. For each time window, we plot a histogram comparing the distribution of optimal allocation weights that have been found with the two methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*O_0eXYW5Z_VciVYwiF4o9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*5MH8lnWb7hOS0yPCXhSfHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*-Wag5oPTtemNrb4Wxmm_Og.png" /></figure><p>Across all three time frames, CMA-ES maintains a 99.5% accuracy relative to the benchmark and consistently achieves a Sharpe ratio that is within 0.01 of the benchmark level. This alignment is also visually apparent, with the weights set by CMA-ES matching those of the benchmark.</p><p>CMA-ES exhibits a more conservative investment strategy compared to the benchmark. For example, in the medium-term scenario, CMA-ES diversifies its portfolio by including all stocks. In contrast, the benchmark case is more aggressive, excluding GOOGL, GS, META, PFE, and SIEGY.</p><p>However, CMA-ES’s conservative strategy underperforms. The expected return on some stocks is more risky, and their inclusion negatively impacts the Sharpe ratio. To mitigate this, we could set a no-investment threshold that defaults weights to <em>0%</em> once certain weight values are surpassed.</p><h4>50 Stocks</h4><p>We repeat the experiment with 15 years of returns data for 50 randomly chosen stocks.</p><p>CMA-ES achieves an accuracy score of 95%. The conservative approach is still present but less evident from the picture, as now some weights are set to extremely small values. Below is the distribution of optimal allocation weights across the two methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*bwUdyRrGVJ3xpfxCDK-qDA.png" /></figure><p>The stocks receiving the highest weight by CMA-ES are Eli Lilly And Co (LLY), Nvidia (NVDA), and Gold (GLD). McDonald&#39;s (MCD), Walmart (WMT), and Advanced Micro Devices (AMD) follow in this order. The benchmark also finds these stocks but puts GLD first, then LLY, and NVDA.</p><h3>Conclusion</h3><p>CMA-ES has proven to be an effective optimisation algorithm that, with minor fine-tuning, could potentially identify the optimal solution. It also showed exploratory capabilities by proposing solutions that differed in some parts from the benchmark but still achieved a Sharpe ratio close to the optimum. This feature could prove crucial in scenarios where no exact analytical solution exists.</p><p>To fully appreciate the potential of Evolutionary Algorithms, we must look for more advanced applications. For instance, a recent <a href="https://arxiv.org/pdf/2403.13187.pdf">paper</a> used CMA-ES in Model Merging of Large Language Models (LLMs). The authors successfully combined two Math LLMs and one Japanese LLM to solve Japanese math questions in Japanese.</p><p>To learn more about this paper, please refer to the <a href="https://github.com/MarcoLomele/cma_study/tree/main/Evolutionary%20Model%20Merge">presentation</a> I delivered at Bocconi University. Feel free to connect with me on <a href="https://www.linkedin.com/in/marco-lomele">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e37873e8cf61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Temporal Edge Regression with PyTorch Geometric]]></title>
            <link>https://pub.towardsai.net/temporal-edge-regression-with-pytorch-geometric-3267d79cfa03?source=rss-f3ff793a48f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3267d79cfa03</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[graph-neural-networks]]></category>
            <dc:creator><![CDATA[Marco Lomele]]></dc:creator>
            <pubDate>Thu, 28 Sep 2023 22:02:31 GMT</pubDate>
            <atom:updated>2023-10-03T06:48:05.076Z</atom:updated>
            <content:encoded><![CDATA[<h4>Graph Neural Networks and Transformers for Time Series Forecasting on Heterogeneous Graphs to Predict Butter Trade Volumes.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5JP8gfTfEx4xDh9DOLWuA.jpeg" /><figcaption>Source: Image by the author.</figcaption></figure><h3>Graphs and Time</h3><p>Graphs are becoming one of the favorite tools of data scientists. Their inherent structure allows for efficient storage of complex information, such as the ongoing protein interactions in your body or the ever-evolving social network surrounding you and your friends.</p><p>Additionally, graphs can be adapted to temporal scenarios. They can vary from the simple static form, where there is no notion of time, to a fluid spatiotemporal setup, where the topology is fixed but the features change at regular intervals, to the chaotic, fully continuous and time-dynamic mode, where everything can change at any time. [1]</p><p>Graph Neural Networks (GNNs) are used to process graphs, and many have already demonstrated exceptional results for recommendation systems, supply chain optimization, and road traffic prediction. [2] Nonetheless, most GNNs operate on static graphs, limiting their use for temporal problems.</p><p>What happens then when we have time series data stored within graphs for which we want to predict future values? It turns out that the Transformer could be a solution, as it has already shown remarkable performance in time series forecasting scenarios. [3]</p><h3>Our Goal</h3><p>To study the effectiveness of combining GNNs and Transformers for time series forecasting on graphs, we will be solving an edge weight prediction problem. Using the data provided by <a href="https://vespertool.com/">Vesper</a>, we will create a sequence of spatio-temporal graphs acting as snapshots of the global trade market of butter. Our goal is then to</p><blockquote>forecast worldwide butter trade volumes for the next three months.</blockquote><h3>Trade Data</h3><p>All countries publish their trade records on a monthly basis. Each record indicates the reporting country, the partner country in the transaction, the product, and its traded volume (our target variable). Since each trade is logged twice, we focus on exports.</p><p>The data at our disposal ranges from January 2015 to April 2023, totaling more than 153,000 transactions. The dataset lists 242 “countries,” including the exports of regions that aggregate multiple countries together, which means that there are 242*241 = 58,322 possible country pairs. Across all months, each pair is an individual time series that we will be forecasting.</p><p>We also include other data series as features to support our model’s learning. In particular, we define country-specific features, such as domestic butter production or GDP, and pair-specific attributes, such as the traded volume or the exchange rate.</p><h3>Building Graphs with PyTorch Geometric</h3><p>We proceed by segmenting the data monthly. We designate two types of nodes: one for the exporter (<em>exp_id</em>) and another for the importer (<em>imp_id</em>). Undirected edges are then used to indicate the relationship between two countries.</p><p>In this manner, we can assign distinct country-specific features to the various types of nodes and embed the pair-specific attributes on the edges. The resulting graph for each month is heterogeneous, fully connected, and bipartite. It can be visualized as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDf97nFUbfm5swe5KJytXQ.png" /><figcaption>Heterogeneous, fully connected, and bipartite graph for each month. Source: Image by the author.</figcaption></figure><p>Altogether, we end up with a sequence of graphs, each serving as a static snapshot of the market’s status at the end of a specific month. Assuming that the data series for the features are updated more rapidly compared to trade data, we can create graphs for the three most recent months we aim to predict, which we refer to as the target months. These graphs are identical to the historical months but lack trade information in the edges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1wMTZvvHL082hhWe9NAM0Q.png" /><figcaption>Sequence of monthly snapshots. Source: Image by the author.</figcaption></figure><p>In Python, we construct a heterogeneous graph using the HeteroData object from the PyTorch Geometric (PyG) library. [4]</p><pre>!pip install torch_geometric<br><br>import torch<br>from torch_geometric.data import HeteroData<br>from torch_geometric.transforms import ToUndirected<br><br>def generate_monthly_snapshot(monthly_data):<br>    &quot;&quot;&quot;<br>    Generate a HeteroData object as snapshot of one month.<br><br>    Args:<br>        monthly_data (list): List of pandas dataframes with trade <br>                             and features&#39; data for one month. <br><br>    Returns:<br>        HeteroData: Object containing node features and edge attributes.<br>    &quot;&quot;&quot;<br>    monthly_snp = HeteroData()<br><br>    # Ingesting the data<br>    trade_figs = monthly_data[0]<br>    exporters_features = monthly_data[1]<br>    importers_features = monthly_data[2]<br>    edge_attrs = monthly_data[3]<br><br>    # Creating the nodes<br>    exp_ids = trade_figs[&#39;exp_id&#39;].unique(),<br>    exp_ids = torch.from_numpy(exp_ids).to(torch.int64)<br><br>    exporters_ftrs_arr = exporters_features.values<br>    exporters_ftrs_arr = np.vstack(exporters_ftrs_arr).astype(np.float64)<br><br>    exporters_ftrs_tensor = torch.tensor(exporters_ftrs_arr, <br>                                         dtype=torch.float)<br>    monthly_snp[&#39;exp_id&#39;].x = exporters_ftrs_tensor<br><br>    imp_ids = trade_figs[&#39;imp_id&#39;].unique(),<br>    imp_ids = torch.from_numpy(imp_ids).to(torch.int64)<br><br>    importers_ftrs_arr = importers_features.values<br>    importers_ftrs_arr = np.vstack(importers_ftrs_arr).astype(np.float64)<br><br>    importers_ftrs_tensor = torch.tensor(importers_ftrs_arr, <br>                                       dtype=torch.float)<br>    monthly_snp[&#39;imp_id&#39;].x = importers_ftrs_tensor<br><br>    # Creating the edges<br>    edge_index = torch.stack([<br>        torch.tensor(trade_figs[&#39;exp_id&#39;].values, dtype=torch.long),<br>        torch.tensor(trade_figs[&#39;imp_id&#39;].values, dtype=torch.long)],<br>        dim=0)<br><br>    monthly_snp[&#39;exp_id&#39;, &#39;volume&#39;, &#39;imp_id&#39;].edge_index = edge_index<br><br>    vol = torch.from_numpy(trade_figs[&#39;volume&#39;].values).to(torch.float)<br>    monthly_snp[&#39;exp_id&#39;, &#39;volume&#39;, &#39;imp_id&#39;].edge_label = vol<br><br>    edge_attrs_arr = edge_attrs.values<br>    edge_attrs_arr = np.vstack(edge_attrs_arr).astype(np.float64)<br>    edge_attrs_tensor = torch.tensor(edge_attrs.values).to(torch.float)<br>    monthly_snp[&#39;exp_id&#39;, <br>                &#39;volume&#39;, &#39;imp_id&#39;].edge_attrs = edge_attrs_tensor<br><br>    monthly_snp[&#39;exp_id&#39;, &#39;volume&#39;,<br>                &#39;imp_id&#39;].edge_label_index = monthly_snp[&#39;exp_id&#39;, <br>                            &#39;volume&#39;,&#39;imp_id&#39;].edge_index.clone()<br><br>    monthly_snp = ToUndirected()(monthly_snp)<br>    del monthly_snp[(&#39;imp_id&#39;, <br>                     &#39;rev_volume&#39;, &#39;exp_id&#39;)][&#39;edge_label&#39;]<br><br>    return monthly_snp</pre><p>Note that trade volume data is stored in variable <em>vol</em>, and it is assigned to the edge weights, called <em>edge_label</em> in PyG, instead of the edge attributes. The resulting HeteroData object for January 2015 is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DBpjmSwxp82jd5u1n0R4yw.png" /></figure><p>It contains the following variables:</p><ul><li><em>exp_id</em>: a list of node features per exporting node.</li><li><em>imp_id</em>: a list of node features per importing node.</li><li><em>edge_index</em>: a list of node indices denoting the connections of the edges.</li><li><em>edge_label</em>: a list of the edge labels, where our target variable is stored.</li><li><em>edge_label_index</em>: a list mirroring <em>edge_index</em>, for the edge labels.</li><li><em>edge_attr</em>: a list of edge attributes per edge.</li></ul><p>With the graphs ready, we can proceed to define the individual components of our model.</p><h3>The Model — Individual Components</h3><p>Taking inspiration from the <em>time-and-graph</em> approach, we employ an Encoder-Decoder architecture. [5] The three crucial units are:</p><ul><li>GNN Encoder: to generate static node embeddings.</li><li>Transformer: to create temporal node embeddings.</li><li>Edge Decoder: to extrapolate predictions.</li></ul><h4>GNN Encoder</h4><p>Similar to how Convolutional Neural Networks work with images, GNNs perform an optimizable transformation on all the features of a graph, preserving the data distributions within that graph. [6] They are used to convert a complex graph schema into vectors of numbers known as node embeddings. Naturally, some information loss is unavoidable. Therefore, the better the GNN, the lower the loss. For more information on GNNs, you can refer to this Medium <a href="https://towardsdatascience.com/an-introduction-to-graph-neural-network-gnn-for-analysing-structured-data-afce79f4cfdc">article</a>.</p><p>In our case, we deploy the GATv2Conv operator, which introduces attention to rank neighboring nodes based on their significance in creating each node embedding. [7] In Python:</p><pre>import torch.nn as nn<br>import torch.nn.functional as F<br>from torch_geometric.nn import GATv2Conv<br>from torch.nn import BatchNorm<br><br>class GNNEncoder(nn.Module):<br>    &quot;&quot;&quot;<br>    GNN Encoder module for creating static node embeddings. <br><br>    Args:<br>        hidden_channels (int): The number of hidden channels.<br>        num_heads_GAT (int): The number of attention heads.<br>        dropout_p_GAT (float): Dropout probability.<br>        edge_dim_GAT (int): Dimensionality of edge features.<br>        momentum_GAT (float): Momentum for batch normalization.<br>    &quot;&quot;&quot;<br><br>    def __init__(self, hidden_channels, num_heads_GAT,<br>                 dropout_p_GAT, edge_dim_GAT, momentum_GAT):<br><br>        super().__init__()<br><br>        self.gat = GATv2Conv((-1, -1), hidden_channels,<br>                              add_self_loops=False, heads=num_heads_GAT,<br>                              edge_dim=edge_dim_GAT)<br><br>        self.norm = BatchNorm(hidden_channels, momentum=momentum_GAT,<br>                               affine=False, track_running_stats=False)<br><br>        self.dropout = nn.Dropout(dropout_p_GAT)<br><br>    def forward(self, x_dict, edge_index, edge_attrs):<br>        &quot;&quot;&quot;<br>        Forward pass of the GNNEncoder.<br><br>        Args:<br>            x_dict (torch.Tensor): node types as keys and node features <br>                                   for each node as values.<br>            edge_index (torch.Tensor): see previous section. <br>            edge_attrs (torch.Tensor): see previous section.<br><br>        Returns:<br>            torch.Tensor: Static node embeddings for one month.<br>        &quot;&quot;&quot;<br>        x_dict = self.dropout(x_dict)<br>        x_dict = self.norm(x_dict)<br>        nodes_embedds = self.gat(x_dict, edge_index, edge_attrs)<br>        nodes_embedds = F.leaky_relu(nodes_embedds, negative_slope=0.1)<br>        return nodes_embedds</pre><h4><strong>Transformer</strong></h4><p>Transformers are a remarkable architecture capable of making sequence-to-sequence predictions and serve as the foundation of large language models like ChatGPT. [8] Through complex attention mechanisms, they can quantify the relationships of embeddings relative to input order. Then, they generate a relevant prediction (as an embedding) for the next element in the sequence. To understand Transformers on a deeper level, I recommend this YouTube <a href="https://www.youtube.com/watch?v=zxQyTK8quyY&amp;t=583s&amp;pp=ygUJc3RhdHF1ZXN0">video</a>.</p><p>We implement a transformer to extrapolate the temporal dynamics across the static monthly snapshots and generate a “temporal” node embeddings for the month under prediction. After applying positional encoding, as shown on PyTorch’s <a href="https://pytorch.org/tutorials/beginner/transformer_tutorial.html">website</a>, we define:</p><pre>class Transformer(nn.Module):<br>    &quot;&quot;&quot;<br>    Transformer-based module for creating temporal node embeddings.<br><br>    Args:<br>        dim_model (int): The dimension of the model&#39;s hidden states.<br>        num_heads_TR (int): The number of attention heads.<br>        num_encoder_layers_TR (int): The number of encoder layers.<br>        num_decoder_layers_TR (int): The number of decoder layers.<br>        dropout_p_TR (float): Dropout probability.<br>    &quot;&quot;&quot;<br><br>    def __init__(<br>        self, dim_model, num_heads_TR, num_encoder_layers_TR,<br>        num_decoder_layers_TR, dropout_p_TR):<br><br>        super().__init__()<br><br>        self.pos_encoder = PositionalEncoding(dim_model)<br>        self.transformer = nn.Transformer(<br>            d_model=dim_model,<br>            nhead=num_heads_TR,<br>            num_decoder_layers=num_encoder_layers_TR,<br>            num_encoder_layers=num_decoder_layers_TR,<br>            dropout=dropout_p_TR)<br><br>    def forward(self, src, trg):<br>        &quot;&quot;&quot;<br>        Forward pass of the Transformer module.<br><br>        Args:<br>            src (torch.Tensor): Input sequence with dimensions <br>                                (seq_len, num_of_nodes, node_embedds_size).<br>            trg (torch.Tensor): Last element of src, with dimensions <br>                                (1, num_of_nodes, node_embedds_size).<br><br>        Returns:<br>            torch.Tensor: Temporal node embeddings for the month<br>                          under prediciton.<br>        &quot;&quot;&quot;<br>        src = self.pos_encoder(src)<br>        trg = self.pos_encoder(trg)<br>        temporal_node_embeddings = self.transformer(src, trg)<br>        return temporal_node_embeddings</pre><h4><strong>Edge Decoder</strong></h4><p>This unit receives the temporal node embeddings and makes inferences for the target variable. In practice, the embeddings are passed through two linear layers that reduce the dimensionality of a pair of node embeddings to a single number: the predicted trade volume between a specific pair of countries. For a refresher on linear layers, I invite you to read this Medium <a href="https://towardsdatascience.com/everything-you-need-to-know-about-neural-networks-and-backpropagation-machine-learning-made-easy-e5285bc2be3a">article</a>.</p><pre>class EdgeDecoder(nn.Module):<br>    &quot;&quot;&quot;<br>    Edge Decoder module to infer the predictions. <br><br>    Args:<br>        hidden_channels (int): The number of hidden channels.<br>        num_heads_GAT (int): The number of attention heads in GAT layer.<br>    &quot;&quot;&quot;<br><br>    def __init__(self, hidden_channels, num_heads_GAT):<br><br>        super().__init__()<br><br>        self.lin1 = nn.Linear(2 * hidden_channels * num_heads_GAT, <br>                              hidden_channels)<br>        self.lin2 = nn.Linear(hidden_channels, 1)<br><br>    def forward(self, z_dict, edge_label_index):<br>        &quot;&quot;&quot;<br>        Forward pass of the EdgeDecoder module.<br><br>        Args:<br>            z_dict (dict): node type as keys and temporal node embeddings <br>                           for each node as values. <br>            edge_label_index (torch.Tensor): see previous section.<br><br>        Returns:<br>            torch.Tensor: Predicted edge labels.<br>        &quot;&quot;&quot;<br>        row, col = edge_label_index<br><br>        z = torch.cat([z_dict[&#39;exp_id&#39;][row], z_dict[&#39;imp_id&#39;][col]], <br>                      dim=-1)<br>        z = self.lin1(z)<br>        z = F.leaky_relu(z, negative_slope=0.1)<br>        z = self.lin2(z)<br>        return z.view(-1)</pre><h3>The Model — All Together</h3><p>The full model is initialized as follows:</p><pre># Any HeteroData object, needed for model initialization.<br>hetero_data_init = monthly_data[0] <br><br>device = torch.device(&#39;cuda&#39; if torch.cuda.is_available() else &#39;cpu&#39;)<br><br>hidden_channels = 32<br><br>num_heads_GAT = 4<br>dropout_p_GAT = 0.3<br>edge_dim_GAT = 7<br>momentum_GAT = 0.1<br><br>num_heads_TR = 4<br>num_encoder_layers_TR = 2<br>num_decoder_layers_TR = 2<br>dropout_p_TR = 0.3<br><br>model = Model(hidden_channels=hidden_channels,<br>              num_heads_GAT=num_heads_GAT,<br>              dropout_p_GAT=dropout_p_GAT,<br>              edge_dim_GAT=edge_dim_GAT,<br>              momentum_GAT=momentum_GAT,<br>              num_heads_TR=num_heads_TR,<br>              num_encoder_layers_TR=num_encoder_layers_TR,<br>              num_decoder_layers_TR=num_decoder_layers_TR,<br>              dropout_p_TR=dropout_p_TR).to(device)</pre><p>To understand how the model is constructed and the interplay between the three units, I will guide you through the training process of one epoch. After setting the number of months to predict (3 in our case) and choosing the optimizer with its learning rate (Adam, 0.00005), we run:</p><pre>for epoch in range(1, epochs + 1):<br>    <br>    # Train phase<br>    for m in range(5, tot_num_months - num_predicting_months):<br>        m_lag4 = monthly_snapshots_list[m - 4]<br>        m_lag3 = monthly_snapshots_list[m - 3]<br>        m_lag2 = monthly_snapshots_list[m - 2]<br>        m_lag1 = monthly_snapshots_list[m - 1]<br>        m = monthly_snapshots_list[m]<br><br>        m_lag4 = m_lag4.to(device)<br>        m_lag3 = m_lag3.to(device)<br>        m_lag2 = m_lag2.to(device)<br>        m_lag1 = m_lag1.to(device)<br>        m = m.to(device)<br><br>        historical = [m_lag4, m_lag3, m_lag2, m_lag1]<br><br>        train_loss = train(historical, m)<br>        train_pred, train_target, train_rmse = test(historical, m)</pre><p>Here,<em> monthly_snapshots_list i</em>s the sequence of monthly snapshots, and <em>tot_num_months</em> equals its length. To capture the temporal trends, we implicitly set in <em>range(5, …)</em> a window with a horizon of 4. This setup ensures that <em>historical</em> always holds the four months leading up to the month under prediction, named <em>m</em>. During training, we slide this window along the sequence of monthly snapshots, updating <em>m </em>with each iteration.</p><p>For the <em>train</em> and <em>test</em> functions, we follow a typical structure inspired by the “Training a Heterogeneous GNN” section of this Google Colab <a href="https://colab.research.google.com/drive/1N3LvAO0AXV4kBPbTMX866OwJM9YS6Ji2?usp=sharing#scrollTo=azGW0k2pJoS7">notebook</a>. The functions send <em>historical</em> and <em>m</em> to the model, which is initialized in its complete form like this:</p><pre>class Model(nn.Module):<br>    &quot;&quot;&quot;<br>    The complete model.<br><br>    Args:<br>        See previous code snippets.<br>    &quot;&quot;&quot;<br><br>    def __init__(self, hidden_channels, num_heads_GAT, dropout_p_GAT, <br>                 edge_dim_GAT, momentum_GAT, num_heads_TR, <br>                 num_encoder_layers_TR, num_decoder_layers_TR, <br>                 dropout_p_TR):<br>        <br>        super().__init__()<br><br>        self.encoder = GNNEncoder(hidden_channels, num_heads_GAT, <br>                                  dropout_p_GAT, edge_dim_GAT, <br>                                  momentum_GAT)<br><br>        self.encoder = to_hetero(self.encoder, <br>                                 metadata=hetero_data_init.metadata(), <br>                                 aggr=&#39;sum&#39;)<br><br>        self.transformer = Transformer(hidden_channels * num_heads_GAT, <br>                                       num_heads_TR, <br>                                       num_encoder_layers_TR, <br>                                       num_decoder_layers_TR, dropout_p_TR)<br><br>        self.decoder = EdgeDecoder(hidden_channels, num_heads_GAT)</pre><p>The <em>to_hetero</em> function adapts the GATv2Conv operator to heterogeneous graphs. Next, we define the forward pass, summarised by the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IhAhZi-iUrZZ3TK5kY47GQ.png" /><figcaption>Single forward pass to generate predictions for the target month m. Source: Image by the author.</figcaption></figure><p>First, each HeteroData object from the <em>historical</em> list is passed through the GNN Encoder. Next, the resulting static node embeddings are concatenated into the source tensor for the Transformer. The unit generates the temporal node embeddings for the month under prediction, which are subsequently fed to the Edge Decoder. The latter ultimately produces the predictions for month <em>m</em>. In Python:</p><pre>def forward(self, historical, m):<br>    &quot;&quot;&quot;<br>    Forward pass of the Model.<br><br>    Args:<br>        See previous code snippets.<br><br>    Returns:<br>        torch.Tensor: Predicted edge labels for the month <br>                      under prediciton, m.<br>    &quot;&quot;&quot;<br>    <br>    # GNN Encoder<br>    embedds_static_list = []<br>    for month in historical:<br>        x_dict = month.x_dict<br>        edge_index_dict = month.edge_index_dict<br>        edge_attrs_dict = month.edge_attrs_dict<br>        edge_label_index = month[&#39;exp_id&#39;, <br>                                 &#39;volume&#39;, &#39;imp_id&#39;].edge_label_index<br><br>        z_dict_month = self.encoder(x_dict, <br>                                    edge_index_dict, edge_attrs_dict)<br><br>        num_exp_nodes = z_dict_month[&#39;exp_id&#39;].size()[0]<br>        num_imp_nodes = z_dict_month[&#39;imp_id&#39;].size()[0]<br><br>        month_embedds = torch.cat((z_dict_month[&#39;exp_id&#39;], <br>                                   z_dict_month[&#39;imp_id&#39;]), 0)<br><br>        embedds_static_list.append(month_embedds)<br><br>    embedds_static = torch.stack(embedds_static_list)<br><br>    # Transformer (with positional encoding)<br>    src = embedds_static<br>    trg = embedds_static_list[3]<br>    trg = trg.unsqueeze(0)<br>    embedds_temp = self.transformer(src, trg)<br><br>    embedds_temp = embedds_temp.squeeze(0)<br>    embedds_exp, embedds_imp = embedds_temp.split([num_exp_nodes, <br>                                                   num_imp_nodes], <br>                                                   dim=0)<br><br>    # Prepare input for Edge Decoder. <br>    z_dict_m_temp = {&#39;exp_id&#39;: embedds_exp,<br>                     &#39;imp_id&#39;: embedds_imp}<br>    edge_label_index = m[&#39;exp_id&#39;, &#39;volume&#39;, &#39;imp_id&#39;].edge_label_index <br><br>    # Edge Decoder<br>    edge_label_pred_m = self.decoder(z_dict_m_temp, edge_label_index)<br>    return edge_label_pred_m</pre><p>For each training step, we compute the Mean Squared Error by comparing the model’s forecast to the actual trade volumes of the month under prediction. The loss is then back-propagated to each unit, with PyTorch ensuring that this occurs in a balanced manner.</p><p>At the end of the training phase, we slide the window once more and allow the model to compute the predictions for the first month in the target list. When the window is moved again, the historical list includes the last three training months plus the first target month, which has just been enriched with the predicted trade volumes. Therefore, as we slide the window into the future, the model will increasingly base of its forecasts on previous predictions it made.</p><p>After training our model for several epochs, we proceed to its evaluation.</p><h3>The Results</h3><p>To assess the effectiveness of our model, we benchmark its performance against traditional forecasting techniques by running PyCaret forecasting experiments on a subset of trade routes. [9] The model achieves perfect predictions for when trade doesn’t occur, and performs relatively well on pairs with extremely high volumes. Both scenarios involve trades of outlying amounts, making their predictions easier to make. In contrast, trade routes with average volumes are more challenging to distinguish, explaining the model’s inconsistent performance in such cases.</p><p>Future developments will focus on enhancing the model’s ability to capture the complexity within the data by:</p><ul><li>expanding the set of features;</li><li>optimizing the architecture and hyperparameters;</li><li>exploring methods from the PyG Temporal library;</li><li>increasing the size of the training and testing datasets. [10]</li></ul><h3>The Verdict</h3><p>In this article, we created a sequence of static heterogeneous graphs to represent the global trade market of butter. We then implemented a model that slides along that sequence and uses a Graph Neural Network and a Transformer to extrapolate relationships within and across snapshots. Finally, we tested the model’s performance against traditional forecasting methods to quantify its relative improvement.</p><p>Given the size of the problem and the various facets of improvement we discussed, it is premature to draw a conclusion on the effectiveness of combining GNNs with Transformers for making time series predictions on graphs.</p><p>However, graphs have demonstrated their strength in representing temporal problems. Due to their holistic nature, they allowed us to learn relationships between pairs of nodes by drawing insights from other pairs, which becomes useful in the future if the graph structure changes. In contrast, traditional forecasting methods work on an individual series completely in isolation and lack this advantage.</p><p>For those interested in the full story of the butter trade challenge, feel free to read this other Medium <a href="https://medium.com/vespertool/buttering-up-global-trade-forecasting-8c309714ef38">article</a> that I wrote. If this article has inspired you and helped you to better understand time series forecasting on graphs, I invite you to connect with me on <a href="https://www.linkedin.com/in/marco-lomele/">LinkedIn</a>!</p><h3>Acknowledgments</h3><p>Data provided by <a href="https://vespertool.com/">Vesper</a>, the most comprehensive and user-friendly commodity intelligence platform. Project ideator: <a href="https://www.linkedin.com/in/ea-werner-a840b3a7/?lipi=urn%3Ali%3Apage%3Ad_flagship3_detail_base%3B4Phej1%2BhTni6xKazufOA7A%3D%3D">Ea Werner</a>.</p><h3>Bibliography</h3><ol><li>Machine Learning on Dynamic Graphs and Temporal Graph Networks | MLSYS 2021. (n.d.). YouTube. <a href="https://youtube.com/watch?v=xzcYyIiFXcY&amp;list=PLG2m1ulw_f2Xz4FIVR0Bcuew8sZ%20S9hm-z&amp;index=1">https://youtube.com/watch?v=xzcYyIiFXcY&amp;list=PLG2m1ulw_f2Xz4FIVR0Bcuew8sZ%20S9hm-z&amp;index=1</a></li><li>Zhou, J. (2018, December 20). Graph Neural Networks: A Review of Methods and Applications. arXiv.org. <a href="https://arxiv.org/abs/1812.08434">https://arxiv.org/abs/1812.08434</a></li><li>Yes, Transformers are Effective for Time Series Forecasting (+ Autoformer). (n.d.). <a href="https://huggingface.co/blog/autoformer">https://huggingface.co/blog/autoformer</a></li><li>Home — PYG. (n.d.). <a href="https://pyg.org/">https://pyg.org/</a></li><li>Huang. (2023, January 19). Temporal Graph Learning in 2023 — Towards Data Science. Medium. <a href="https://towardsdatascience.com/temporal-graph-learning-in-2023-d28d1640dbf2#a31b">https://towardsdatascience.com/temporal-graph-learning-in-2023-d28d1640dbf2#a31b</a></li><li>Labonne, M. (n.d.). Hands-on graph Neural networks using Python. O’Reilly Online Learning. <a href="https://www.oreilly.com/library/view/hands-on-graph-neural/9781804617526/">https://www.oreilly.com/library/view/hands-on-graph-neural/9781804617526/</a></li><li>Brody, S. (2021, May 30). How Attentive are Graph Attention Networks? arXiv.org. <a href="https://arxiv.org/abs/2105.14491">https://arxiv.org/abs/2105.14491</a></li><li>Vaswani, A. (2017, June 12). Attention is all you need. arXiv.org. <a href="https://arxiv.org/abs/1706.03762">https://arxiv.org/abs/1706.03762</a></li><li>Home — PyCaret. (2023, June 28). PyCaret. <a href="https://pycaret.org/">https://pycaret.org/</a></li><li>PyTorch Geometric Temporal Documentation — PyTorch Geometric Temporal documentation. (n.d.). <a href="https://pytorch-geometric-temporal.readthedocs.io/">https://pytorch-geometric-temporal.readthedocs.io/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3267d79cfa03" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/temporal-edge-regression-with-pytorch-geometric-3267d79cfa03">Temporal Edge Regression with PyTorch Geometric</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Buttering Up Global Trade Forecasting]]></title>
            <link>https://medium.com/vespertool/buttering-up-global-trade-forecasting-8c309714ef38?source=rss-f3ff793a48f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c309714ef38</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[international-trade]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[dairy-market]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Marco Lomele]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 12:43:19 GMT</pubDate>
            <atom:updated>2023-09-04T13:18:48.328Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dairy Meets Machine Learning: A Gentle Overview of Trade Volume Prediction using Graph Neural Networks and Transformers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uBm2D9vf41m9JJiO6A68ww.png" /></figure><h3>Delayed Taste</h3><p>Every minute, approximately 22 metric tons of butter are produced globally. This results in a complex trade landscape, with over 2,300 recorded transactions monthly. Given the vast uses of butter and its many derivative products, it is essential for buyers, sellers, and traders to monitor trade, ensuring they’re informed when making business decisions.</p><p>Yet, there is a challenge in accessing real-time insights. Due to the full reliance on governmental bodies for data collection, a notable delay exists. On average, it takes three months for all countries to report their trade volumes.</p><blockquote><em>Our goal? Eliminate the reporting lag entirely. We aim to implement state-of-the-art technologies to forecast the last three months of international trade volumes, effectively bridging the gap.</em></blockquote><p>Solving problems like this is at the core of <a href="https://vespertool.com/">Vesper</a>. We strive to build the most comprehensive commodity intelligence platform, and we combine quality data and professional expertise with Data Science to produce unique tools for our users.</p><p>In this article, we provide an overview of our implementation. We will begin by walking you through the dynamics of the butter market, followed by an introduction to our novel problem representation using temporal graphs. Then, you will learn the basics of our machine learning model, with a brief summary of each of its three crucial components. And last, we will give insight into the results.</p><h3>Butter Spreading All Over The World</h3><p>Butter is one of the most actively traded commodities in the dairy industry. Each month, an impressive 200,000 metric tons of butter cross international boundaries. These imports and exports can range from mere fractions to tens of thousands of metric tons.</p><p>The international butter market operates largely as an oligopoly. The three dominant surplus producers are the US, New Zealand, and the countries in the EU, all competing for the demand of the other countries. In 2022, the US exported over 80,000 metric tons, New Zealand almost 480,000 mt, and the EU 188,000 mt. That same year, the average butter exports per country were approximately 53 mt. While other countries produce butter domestically, they often turn to one of the three major players for additional supply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4YX740RXZ2FfwfB8bqVhPQ.png" /><figcaption>World dairy trade map for 2020. [1]</figcaption></figure><p>Over the years, many countries have established strong trade routes with these major producers, thanks to trade agreements and favourable geopolitical conditions. Consequently, trade interactions with these big players are generally consistent in volume and timing. This is relative to butter trades between other country pairs, which tend to be more sporadic. Often influenced by short-term events, their nature is considerably more ‘random’ and therefore harder to predict.</p><p>From a buyer’s standpoint, the choice of which major producer to source butter from depends on many factors. Since butter is a commodity, the differences are small, if not negligible. Therefore, the primary decision driver is the discrepancy in the offering prices of the big players, followed by tariffs and transportation costs.</p><h3>Problem Representation: A Vast Social Network.</h3><p>We use graphs to represent the dynamics of the butter trade market effectively. Unlike standard tables that list data points separately, graphs emphasise the links between them, preserving the valuable nuances of an interconnected network. This includes the types and strengths of relationships between data points.</p><p>To better visualise graphs, think of your social network of friends and colleagues. Each node is a person, and each edge represents your relationship with that person. Using graphs, we can represent your entire social network, preserving the unique qualities of the people as node features and the characteristics of the relationships saved as edge attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GxsW8CyCgf0Frwi8i8YeYg.png" /><figcaption>Using graphs to represent a social network.</figcaption></figure><p>Similarly, in our scenario, we use nodes to symbolise individual countries and edges to denote trade events between them. Each country possesses a set of distinct qualities called country-specific features (stored in the nodes), such as domestic butter production or GDP. Then, there are characteristics exclusive to the country pair, called pair-specific attributes (saved in the edges), such as the trade volume or the prevailing exchange rate between the respective currencies.</p><p>To create the graph, we use all our available import-export data from January 2015 onward. Firstly, we insert the available 242 nodes, one for each “country”. Then, we select all the recorded trades during that time window. The result is an impressive 267,376 edges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4LDMt4YFvxVGDZDxlgo3HQ.png" /><figcaption>One big graph containing all the trade data.</figcaption></figure><p>To better study the problem, we segment the data monthly. This yields a sequence of lighter graphs with approximately 2,000 edges, serving as a snapshot of the market’s monthly status. We can interpret this historical sequence of graphs as a general data series that groups the time series of many individual points. A time series is a set of measurements of a single variable over time, for instance, the trade volume between just one pair of countries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hf1URp7Uox4P7DRZ" /><figcaption>Sequence of monthly snapshots.</figcaption></figure><p>The key benefit of our graph-based representation is its ability to capture world-wide trends. By grouping all the country pairs in a single structure, we can study multiple routes simultaneously. In contrast, standard forecasting techniques can handle only a single data series at a time.</p><p>Moreover, because all the other variables we are interested in (country-specific features and pair-specific attributes) don’t suffer from such a long delay, we can already create the graphs for the three most recent months we aim at predicting, called the target months. With this historical sequence of graphs, we are ready to develop our machine learning model.</p><h3>Predicting Trade Volumes with Machine Learning</h3><p>For our problem, we will implement an approach that falls under supervised learning. First, we train the model by giving it both the feature data and the target variable.</p><p>After training our model on historical months, we will input a monthly snapshot from the target months, holding all country-specific features and pair-specific attributes but lacking trade volume data. It will process it, and then, based on the patterns it has learned during training, it will output the predicted trade volumes for each country pair.</p><p>Knowing the overarching approach, let’s dissect our model into its components. Afterwards, we will discuss the results. Our model’s key parts are:</p><ul><li>Graph Encoder: to condense the individual graph into a machine-readable format called embeddings.</li><li>Temporal Encoder: to extract the temporal relationships from previous monthly embeddings.</li><li>Edge Decoder: to translate the embeddings into predictions for trade volumes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lM9V6UBX2INS5cfeoT6tYQ.png" /><figcaption>Making predictions with our model.</figcaption></figure><h4>Graph Encoder: Back to Social Networks.</h4><p>For this component, we are interested in efficiently transforming all the data stored in the graph into a list of numbers. Due to the differences in form, some information loss is unavoidable. Our goal is to minimise this loss.</p><p>We deploy a Graph Neural Network (GNN). GNNs are capable of combining information from the individual node, its neighbourhood, and edge attributes. It’s like the saying that suggests a person is best defined by their closest friends. The GNN’s output is called node embeddings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fjyG8bf072Yaiald" /><figcaption>GNNs aggregate information from the neighbourhood of a node.</figcaption></figure><p>And much like in our social networks, where some friends are more influential to us than others, the same holds for nodes in a graph. In GNN jargon, this is called attention, and we use it in our model to rank which trade routes are most informative to predict other trade routes.</p><h4><strong>Temporal Encoder: Inspired by ChatGPT</strong></h4><p>This unit learns how a specific month is related to its predecessors. The idea is that a month’s market conditions are influenced by the market status of the preceding months. We deploy the Transformer, a cutting-edge architecture that lies at the foundation of language models like ChatGPT because of its power to make ‘sequence-to-sequence’ predictions.</p><p>Imagine a typing prediction scenario. Given a sentence (a sequence of words), the Transformer understands the order of the words and their significance in conveying the message, all relative to the general context of the phrase. It then outputs the word with the highest probability of being next in the sequence.</p><p>We cleverly apply this structure to our problem: each monthly snapshot is treated as a word, and the Transformer outputs the most probable node embeddings for the next month in the sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VKP6qe_5plOJg2ED" /><figcaption>Predicting the next monthly snapshot in the sequence.</figcaption></figure><h4><strong>Edge Decoder: Making Sense of Node Embeddings.</strong></h4><p>The purpose of this component can be seen as the inverse of the Graph Encoder. Instead of creating embeddings, it deciphers the embeddings it receives from the Temporal Encoder into predictions for the target variable. We implement two neural networks and set the goal of taking pairs of embeddings and extracting a single number: the forecast for the trade volume between two countries.</p><p>The result is a unit that can reconstruct the trade volume for each country pair within the graph for the month of interest. As such, the better the Edge Decoder, the closer the predictions will be to the actual values.</p><h3>The Results</h3><p>To evaluate the performance of our model, we take the three most recent months (with trade volume data available) and input them to the model. Then, we compare the predictions with the true values. To make the test valid, we never showed these three months to the model.</p><p>The model excels at predicting when no trade occurs between two countries. It also performs well with predicting when trade volumes are exceptionally high. This might be caused by the sheer size of the trade volumes, which significantly deviate from the mean value in the data and thus are easily recognisable by the model.</p><p>Interestingly, it struggles with average trade volumes. When we benchmark our predictions to traditional time-series forecasting methods, it becomes clear that, to enhance the accuracy of our model, we need to facilitate the distinction between average trade routes that are more similar to one another. This can be achieved by incorporating more data features, that help create a richer market representation, and by including trade information from other commodities.</p><p>Given these considerations, the average improvement of our model across all trade routes is negligible, and it is more informative to study individual pairs. Below, you can find performance of our model on two routes with very high volumes traded and one average. As you can see, the results differ a lot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hf8tclrZ82-CKUCMckEHg.png" /><figcaption>Sample table of results.</figcaption></figure><h3>Our Long Term Goal</h3><p>We are determined in continuing the development of this model, as we believe it has the potential to grant us prediction capabilities surpassing industry standards. Compared to traditional forecasting methods that work on a single time series in isolation, our solution predicts all trade volumes simultaneously.</p><p>Such a holistic approach is made possible thanks to graphs, which allow us to organise vast amounts of information into structures that accurately represent the monthly status of the market. This enables us to study the trade dynamics between any two countries by taking insights from similar trade routes, which becomes useful when in the future new trade relationships will form.</p><p>From a technical perspective, our approach also brings benefits. A single model working on multiple trade routes negates the need to develop many individual algorithms, one for each country pair, thereby saving time and energy resources.</p><p>While we currently aim at eliminating the reporting gap, our long term goal is to forecast trade volumes into the future, for any commodity. We are certain that this model has been a significant step towards achieving this goal.</p><p>If you are curious about what other advanced tools we work on, please follow our <a href="https://medium.com/vespertool">Medium</a> or visit our <a href="https://vespertool.com/product/outlook/">website</a>. For those interested in the technical implementation, we invite you <a href="https://medium.com/@marco.lomele03">here</a>!</p><h3>References</h3><ol><li><em>World Dairy Map 2020: Shifting gears in global dairy trade</em>. (n.d.). research.rabobank.com. <a href="https://research.rabobank.com/far/en/sectors/dairy/world-dairy-map-2020.html">https://research.rabobank.com/far/en/sectors/dairy/world-dairy-map-2020.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c309714ef38" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vespertool/buttering-up-global-trade-forecasting-8c309714ef38">Buttering Up Global Trade Forecasting</a> was originally published in <a href="https://medium.com/vespertool">Vesper</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>