<?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 Rui Zhang on Medium]]></title>
        <description><![CDATA[Stories by Rui Zhang on Medium]]></description>
        <link>https://medium.com/@rui-zhang-ocean?source=rss-3d4f41f85622------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sUG_QPRuccASUoOCZOuLog.jpeg</url>
            <title>Stories by Rui Zhang on Medium</title>
            <link>https://medium.com/@rui-zhang-ocean?source=rss-3d4f41f85622------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 07:54:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rui-zhang-ocean/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[How to collect data from Statistics Canada using Python]]></title>
            <link>https://medium.com/data-science/how-to-collect-data-from-statistics-canada-using-python-db8a81ce6475?source=rss-3d4f41f85622------2</link>
            <guid isPermaLink="false">https://medium.com/p/db8a81ce6475</guid>
            <category><![CDATA[macroeconomics]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[statistic-canada]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rui Zhang]]></dc:creator>
            <pubDate>Wed, 13 Jan 2021 18:31:40 GMT</pubDate>
            <atom:updated>2023-12-22T15:59:45.453Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/hands-on-tutorials">Hands-on Tutorials</a></h4><h4>A step by step tutorial on Statistics Canada API and python library</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5XHp-lt1zxRYKjqfcQHGng.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@fiveamstories">Alex Shutin</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p><a href="https://www.statcan.gc.ca/eng/start">Statistics Canada</a> provides a wide range of data for public use, including data for Canada’s economy, society and environment. In addition to manually browsing the webpage to access the data, Statistics Canada also provides <a href="https://www.statcan.gc.ca/eng/developers/wds/user-guide#a12-3">Web Data Service</a>, i.e. API access to their database. What’s even better, there is a python library <a href="https://stats-can.readthedocs.io/en/latest/">stats_can</a> that wraps up the API commands and allows users to write simple codes to read data automatically. This article will provide a step by step tutorial on how to achieve that.</p><h3>Identify desired data item and its vectorID</h3><p>Go to Statistics Canada subpage <a href="https://www150.statcan.gc.ca/n1/en/type/data?MM=1">Data</a>, input keywords, for instance, GDP, and click on the search icon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-arXKCF9pt3Ty9VE3yafA.png" /></figure><p>Locate the desired item in returned results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6786dhaDmanOW2A_6jEnkg.png" /></figure><p>On the <a href="https://www150.statcan.gc.ca/t1/tbl1/en/tv.action?pid=3610043401">GDP</a> page, click on Add/Remove data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BENUMVTJe958Qk2j6phYKg.png" /></figure><p>Click on the tab Customize layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qoe8C4sTS2n4Xi8p9xmTag.png" /></figure><p>Scroll down and tick the option Display Vector identifier and coordinate, then click the button Apply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CnFETJAHn6LKFWPA_fwCJg.png" /></figure><p>Now the table will be reorganized and you will find a new column Vector, here we will select GDP for all industries, so the targeted vectorID is v65201210. This will be used later in the Python codes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ckeKcvqFiNloeH2kUBzuZw.png" /></figure><h3>Install stats_can in Python</h3><p>The library can either be installed with conda or pip:</p><pre>conda install -c conda-forge stats_can</pre><p>Or:</p><pre>pip install stats-can</pre><h3>Collect the data</h3><p>We will use the function <a href="https://stats-can.readthedocs.io/en/latest/stats_can.html#stats_can.sc.vectors_to_df">stats_can.sc.vector_to_df</a> to read data from Statistics Canada. The syntax of the function is as below:</p><pre>df = stats_can.sc.vectors_to_df(vectors, periods = n, start_release_date = None, end_release_date = None)</pre><p>It returns DataFrame of vectors with n periods data or over range of release dates. The function wraps up two API commands, which are get_bulk_vector_data_by_rangeand get_data_from_vectors_and_latest_n_periods to turn the resulting list of JSONs into a DataFrame.</p><p>For instance, with the vectorID v65201210 for GDP, you can run following codes to collect GDP for the last 6 months:</p><pre>import stats_can</pre><pre>df = stats_can.sc.vectors_to_df(&#39;v65201210&#39;, periods = 6)</pre><p>You can rename the index and column to make the table look nicer:</p><pre>df.columns = [&#39;GDP&#39;]<br>df.index.names = [&#39;Date&#39;]</pre><p>the returned table looks like below:</p><pre>Date        GDP        <br>2020-05-01  1726385.0<br>2020-06-01  1833032.0<br>2020-07-01  1879281.0<br>2020-08-01  1896592.0<br>2020-09-01  1912085.0<br>2020-10-01  1920056.0</pre><h3>An example that collects and visualizes multiple economic indexes</h3><p>In a recent <a href="https://towardsdatascience.com/a-deep-learning-based-method-for-synthesizing-data-with-an-application-in-financial-transactions-9c3936423d9a">project</a> on forecasting sales with synthetic data, I collected multiple eco indexes such as GDP, CPI, unemployment rate, etc. to build a multi-variant regression model for the purpose of forecasting financial transaction counts.</p><p>Firstly, I figured out vectorIDs for all eco indexes I plan to use, including GDP, CPI, TSX, unemployment rate and exchange rate (USD to CAD), and put them into a dictionary:</p><pre>eco_vec_map = {&#39;CPI&#39;:&#39;v41690973&#39;,<br>               &#39;Exchange_Rate_USD&#39;:&#39;v111666275&#39;,<br>               &#39;GDP&#39;:&#39;v65201210&#39;,<br>               &#39;Unemployment_Rate&#39;:&#39;v91506256&#39;,<br>               &#39;TSX&#39;:&#39;v122620&#39;}</pre><p>Secondly, I converted values from the dictionary into a list and run the function, with an input of periods = 36 (i.e. the last 3 years), the function automatically recognized the vector list and returned tables with multiple columns:</p><pre>vectors = list(eco_vec_map.values())<br>df = stats_can.sc.vectors_to_df(vectors, periods = 36)</pre><p>I then renamed the columns with their eco index name, note that a mapping trick is used here, so that you won’t have to worry about the order of the columns:</p><pre>inv_map = {v: k for k, v in eco_vec_map.items()}<br>df.columns = df.columns.to_series().map(inv_map)<br>df.index.names = [&#39;Date&#39;]</pre><p>The returned table looked like below:</p><pre>Date        TSX       CPI    GDP       Unemployment_Rate  Exchange_Rate_USD<br>2017-09-01  NaN       NaN    1905358.0 NaN                NaN<br>2017-10-01  16025.59  130.9  1907384.0 NaN                NaN<br>2017-11-01  16067.48  131.3  1917258.0 5.4                1.2769<br>2017-12-01  16209.13  130.8  1922552.0 5.3                1.2771<br>...<br>2020-08-01  16514.44  137.0  1904249.0 11.0               1.3222<br>2020-09-01  16121.38  136.9  NaN       8.4                1.3228<br>2020-10-01  NaN       NaN    NaN       8.1                1.3215</pre><p>Finally, I visualized all columns of the table:</p><pre>df.plot(subplots = True, figsize = (14,8), layout = (3,2));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*Xj080i1rPfZOjQP1adPw1Q.png" /></figure><p>It showed that except CPI, other eco indexes experienced a sharp decline or increase near March-April 2020, which is likely impacted by the pandemic.</p><h3>Summary</h3><p>This article provided detailed instructions on how to collect data using Statistics Canada’s library in Python. The major steps are:</p><ul><li>Identify vectorIDs for targeted data items.</li><li>Install stats_can library and call functionstats_can.sc.vectors_to_df to collect data and store as a DataFrame table.</li></ul><p>I had a difficult time finding good tutorials online so I wrote this article hoping to help others. For any questions or suggestions, don’t hesitate to reach out to me via <a href="http://www.linkedin.com/in/rui-zhang-ocean">Linkedin</a>. I’d be happy to connect :)</p><h3>References:</h3><p>[1] Web Data Service User Guide, Statistics Canada. <a href="https://www.statcan.gc.ca/eng/developers/wds/user-guide#a12-3">https://www.statcan.gc.ca/eng/developers/wds/user-guide#a12-3</a></p><p>[2] A python library for reading data from Statistics Canada. <br><a href="https://stats-can.readthedocs.io/en/latest/index.html#">https://stats-can.readthedocs.io/en/latest/index.html#</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db8a81ce6475" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-collect-data-from-statistics-canada-using-python-db8a81ce6475">How to collect data from Statistics Canada using Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A deep learning based method for synthesizing data with an application in financial transactions]]></title>
            <link>https://medium.com/data-science/a-deep-learning-based-method-for-synthesizing-data-with-an-application-in-financial-transactions-9c3936423d9a?source=rss-3d4f41f85622------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c3936423d9a</guid>
            <category><![CDATA[synthetic-data]]></category>
            <category><![CDATA[sales-prediction]]></category>
            <category><![CDATA[making-sense-of-big-data]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[editors-pick]]></category>
            <dc:creator><![CDATA[Rui Zhang]]></dc:creator>
            <pubDate>Thu, 07 Jan 2021 22:24:54 GMT</pubDate>
            <atom:updated>2021-01-13T20:30:48.352Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/making-sense-of-big-data">Making Sense of Big Data</a></h4><h4>How to forecast tabular transaction data using variational autoencoder and general linear regression</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*efaHYtt6CgLJpQbVJQ9zcg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@claybanks">Clay Banks</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><h3>Background</h3><p>Sales forecasting plays an extremely important role in business planning. It is a useful tool that extracts information from past and current sales data to intelligently predict future performances. With an accurate sales forecast in hand, decision makers can optimize marketing strategies and business expansion plans with more confidence. For instance, if your sales forecast says that 50% of your annual sales would occur during Christmas, you will need to ramp up your inventory and production in the fall to prepare for the sales peak. You may also want to hire more salespeople after Thanksgiving. If you have accurate sales forecasts for your competitors, and thus a better understanding of their priorities and targeting, you can get a head start when planning for promotion campaigns. A good sales forecast can inform many other aspects of your business.</p><p>For this project, I implemented a framework to predict sales using historical transaction records from a payment app. The framework applies macroeconomic indexes to constrain total transaction numbers in future and tabular variational autoencoders (TVAE) to simulate individual transaction records. Some sample codes are provided in this article, for details of the codes, please check out my <a href="https://github.com/rui-zhang-ocean/Predict_Transactions">Github</a>.</p><h3>Data</h3><p>The dataset used in this project is from a payment app, a tabular data with over 3 million transaction records from September 2018 to January 2020. Each record contains customer (age, gender, address, etc.), account (account type, bank, etc.), transaction (transaction type, amount, date, etc.) and retailer information (retailer name, sectors, etc.). As a starting point, I selected variables as follows: `Account Type`, `Consumer Gender`, `Consumer Age`, `Transaction Date`, `Normalized Retailer`, `SIC Description (sector)` and `Purchase Amount`.</p><p>Table 1. Samples of selected variables in the tabular data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F5EBuLq1PuHqkARO" /></figure><h3>Methods</h3><p>Synthetic data generators take input tabular data, learn a model from it, and output new synthetic data which has similar statistical properties as the input data. It is often used when regulations or other privacy concerns restrict access to the original data, or the original data is expensive to collect, or simply not available. According to a recent benchmark <a href="https://github.com/sdv-dev/SDGym">study</a> on synthetic data generation techniques from MIT, tabular variational autoencoder (TVAE) synthesizer outperformed other synthesizers and is recommended.</p><p>The basic idea of autoencoders is to construct an encoder and a decoder as neural networks and to learn the best encoding-decoding scheme using an iterative optimization process. The encoder is similar to dimensionality reduction techniques such as principal component analysis (PCA) which converts input data into representations in latent space, and a decoder randomly samples from the latent space and reverses that into tabular data. The training is regularized to avoid overfitting and ensure that the latent space has good properties that enable generative processes.</p><p>Here I used TVAE synthesizer to load historical transaction data as input, train the model, and output simulated transaction data. The output data reflects the consumption habits of the customers from the historical time period, but lacks constraint of the total transaction counts. Therefore, I set up a generalized linear regression model among historical transaction counts and macroeconomic indexes (GDP, CPI, unemployment rate, etc.) and apply that to forecast future transaction counts. Besides, I also need to forecast future economic indexes based on historical indexes. The proposed workflow is as follow:</p><ul><li>Given a specific year and month in future, for instance, February 2021, forecast the macroeconomic indexes based on the historical indexes.</li><li>Forecast the transaction counts N in Feb 2021 using the regression model.</li><li>Generate N transaction records using the trained TVAE synthesizer.</li></ul><h4>Feature engineering and retailer embedding</h4><p>I start with data cleaning and feature engineering. The tabular data was well maintained with less than 2% missing or invalid values (i.e. negative age), so for missing or invalid values I simply removed them.</p><p>Categorical variables with a number of values smaller than 10 were treated with one-hot-encoding, including `Account Type` (debit or credit), `Consumer Gender` (male or female) and `SIC Description`. Note that `SIC Description` only kept top 9 values with maximum counts and grouped the remaining records into `other`.</p><p>I treated `Age` as a continuous numerical variable at first but the synthesized age distribution didn’t look optimal. A large chunk of the spectrum between 30 to 50 years old were missing. I fixed it by converting age into `age range` (i.e. 20–25, 25–30, 30–35, etc.) as the model input, and later convert the simulated range back to `Age` by randomly selecting a number from each range. This is a classical approach to transform continuous numerical values into discrete fixed width bins, and consider these discrete values as categories.</p><p>I broke down `Transaction Date` into two categorical values: `period of month` and `day of week`. `period of month` contains variables `start` (1–10 days of a month), `mid` (11–20 days of a month) and `end` (21 to the end of the month days) which refers to different periods of any given month. `day of week` refers to an individual day of the week (Mon, Tue, etc.). This approach ignored the annual and monthly but focused on weekly and daily variations. The reason is that when forecasting transaction counts using macroeconomic indexes, which are often released monthly, we would have incorporated annual and monthly variability, thus the synthesizer doesn’t necessarily need to include that information from historical records.</p><p>`Normalized Retailer` is the most tricky variable to deal with. It contains over 2000 retailers so embedding is needed to reduce the dimensions to a manageable level. Here I applied `item2vec` to convert `Normalized Retailers` into 10 dimension embeddings. To provide readers with some context, in the natural language processing (NLP) domain, `word2vec` learns word embeddings that preserve the semantic characteristics of words and the relations between words by treating each sentence as `sets of words` that share the similar context. `item2vec` is one of its variants in the non-NLP domain, where it takes `sets of items` as analog as sentences (`sets of words`) to be the context and find out the relations between items. There are two major advantages of using embedding instead of one-hot-encodings. First, the reduced dimensions are manageable with limited memory. Second, it represents the distance or similarity of variables better.</p><blockquote>“Researchers from the Web Search, E-commerce and Marketplace domains have realized that just like one can train word embeddings by treating a sequence of words in a sentence as context, the same can be done for training embeddings of user actions by treating sequence of user actions as context.”</blockquote><blockquote>— Mihajlo Grbovic, Airbnb</blockquote><p>The biggest challenge of training item embedding is how to define the `sets of items`, or how to find out the most relevant context for those items. For this project, I tested a few different grouping approaches on retailers: a) group retailers that have transactions with the same customer on the same date. b) group retailers that belong to the same sector and have transactions on the same date. c) group retailers that belong to the same sector and have transactions with the same customer.</p><p>It turns out that option C performs best, I plotted the scatter map of the retailers’ vectors after reducing the 10 dimensions to 2 dimensions. The color map indicates different sectors. It shows that the embedding can group retailers reasonably well.</p><p>Figure 1. Retailer embedding clustered by sectors</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_N5wTzI7W5P3UP_HUGQtsw.png" /></figure><p>I used the word2vec module from <a href="https://pypi.org/project/gensim/">gensim</a> to train the retailer2vec model. The word2vec module considers each sentence as the `sets` and has a parameter window size to determine the scope that we searched for `context` of each word. By contrast, in our retailer2vec implementation, the `meaning` of a retailer should be captured by all its neighbors in the same set. In other words, we should consider all retailers that belong to the same sector and have transactions with the same customer to define the `meaning` for each of those retailers. The window size then needs to be changed according to the size of each retailer set.</p><p>To address this problem without modifying the underlying code of the gensim library, one approach is to define a super large window size (e.g. 999999), which is way larger than the length of any retailer set in the training data. Although this workaround is not ideal, it does achieve acceptable results. The best option might be modifying the underlying codes in gensim. Below is sample code that train the embedding using word2vec.</p><pre>from gensim.models import Word2Vec</pre><pre>model = Word2Vec(sentences = training_data,<br>                 iter = 10,<br>                 min_count = 5,<br>                 size = 10, <br>                 workers = 4, <br>                 sg = 1, <br>                 hs = 0, <br>                 negative = 10, <br>                 window = 999999)</pre><p>When reversing synthesized retailer embeddings back to retailers, the model will only check distances among retailers in the synthesized sector (`SIC Description`), and pick up the closest one.</p><h4>Train TVAE synthesizer</h4><p>After feature engineering, I got an input matrix of 46 columns and over 3 million records. I used TVAE synthesizer from <a href="https://github.com/sdv-dev/SDGym">SDgym</a>, where training and generating samples are both well wrapped up in the module. Note that the function requires specification of categorical columns and ordinal columns. However, when I explicitly specify categorical columns for the one-hot-encoded variables, the synthesized data had trouble producing reasonable results. An alternative would be to assume all one-hot-encoded variables as continuous numerical values and select the absolute maximum of synthesized results among all columns, which works just fine. More validations can be found in section 4. Below is the sample code of training TVAE synthesizer and checking out the output sample.</p><pre>from sdgym.synthesizers import TVAESynthesizer</pre><pre>synthesizer = TVAESynthesizer()<br>synthesizer.fit(data)<br>sample = synthesizer.sample(1)</pre><p>Considering the large size of the input matrix, it is recommended to train the synthesizer with GPU. Google Colab with free GPU access or Google Cloud Platform with 300$ credit for any new users would be a good start.</p><h4>Collect and forecast economic indexes</h4><p>I started with 5 common macroeconomic indexes which are: gross domestic product (GDP), consumer price index (CPI), Toronto stock exchange (TSX), unemployment rate and exchange rate (CAD to USD). To build a regression model among the eco indexes and transaction counts, I will need to collect that data first. Statistics Canada provides <a href="https://www.statcan.gc.ca/eng/developers/wds/user-guide#a12-3">API services</a> which provide access to data and metadata released on each business day. The API commands are further wrapped up by a Python library <a href="https://stats-can.readthedocs.io/en/latest/">stats_can</a> which can be easily called within any script to retrieve the latest eco index data. All a user needs to do is to specify a `vectorID` for the desired index as the input. It is worth noting that by default the `vectorID` is not shown on the index table of Statistics Canada website, the user needs to turn on `Display Vector identifier and coordinate` in the table settings to make it visible. I will give an introduction on how to use stats_can to automatically retrieve data from Statistics Canada in a different <a href="https://towardsdatascience.com/how-to-collect-data-from-statistics-canada-using-python-db8a81ce6475">article</a>. Below is the sample code of retrieving eco indexes from Statistics Canada using stats_can.</p><pre>import stats_can</pre><pre>eco_vec_map = {&#39;CPI&#39;:&#39;v41690973&#39;,<br>               &#39;Exchange_Rate_USD&#39;:&#39;v111666275&#39;,<br>               &#39;GDP&#39;:&#39;v65201210&#39;,<br>               &#39;Unemployment_Rate&#39;:&#39;v91506256&#39;,<br>               &#39;TSX&#39;:&#39;v122620&#39;}<br>vectors = list(eco_vec_map.values())<br>N = 36<br>df = stats_can.sc.vectors_to_df(vectors, periods = N)</pre><p>I used <a href="https://facebook.github.io/prophet/">prophet</a>, an open source library developed by Facebook, to predict the economic indexes. The library is for forecasting time series data based on an additive model where non-linear trends are fit with yearly, weekly, and daily seasonality, plus holiday effects. For instance, given GDP records in the last three years (36 monthly records in total), we can predict GDP for the next month. Below is the sample code of predicting eco indexes using prophet.</p><pre>from fbprophet import Prophet</pre><pre>m = Prophet()<br>m.fit(df_input)<br>future = m.make_future_dataframe(periods = 1, freq = &quot;MS&quot;)    <br>forecast = m.predict(future)</pre><h4>Generalized linear regression model</h4><p>I started with a multiple variable linear regression as baseline, but found the forecasted transaction counts could be negative sometimes. A natural alternative would be to use a generalized linear model (GLM). Here I used a GLM with Poisson distribution and a logarithm link function, correlating historical monthly transaction counts with monthly economic indexes. Below is the sample code of training the GLM using scikit-learn.</p><pre>from sklearn.linear_model import TweedieRegressor<br>from sklearn import preprocessing</pre><pre>glm = TweedieRegressor(power = 1, alpha = 0.5, link=&#39;log&#39;)<br>scaler = preprocessing.StandardScaler().fit(X_train)<br>X_train_scaled = scaler.transform(X_train)<br>glm.fit(X_train_scaled, y_train)</pre><p>Ideally the forecasted transaction counts can be verified as the process continues with more data coming in every month.</p><h3>Results</h3><p>To verify if the synthesized data exhibits similar statistical properties as the input data. I examined the age and purchase amount distribution, bar plots of purchase amount for top sectors and top retailers (Table 2).</p><p>Although the synthesized purchase amount can reflect the total distribution well, it has trouble resolving sales for each retailer, to deal with that, I applied a post-correction to `Transaction Amount` for each retailer by scaling with the average transaction amounts for each retailer from input data. With that post-correction, the purchase amount per retailer for synthesized data fits much better with input data, although some outliers are missed.</p><p>Table 2. Comparison between input and synthesized data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxTPCaWmiaOcyPx-YgGuSA.png" /></figure><h3>Discussion</h3><p>This project provides a framework to forecast sales using historical transaction records from a payment app. The basic idea is to forecast total sales volume using macroeconomic indexes and then produce synthesized transaction records to fill that volume. The framework utilizes methods such as item embedding, tabular variational autoencoder (TVAE), time series forecasting and generalized linear models. It produces reasonably well forecasts that can be used to inform many aspects of a retailer’s business.</p><p>However, there is still room for improvements. The retailer embedding can be improved by defining more sets that correlates relevant retailers. For instance, for the largest group `restaurant`, if we can scrape tags or consumption level ($$$) from apps such as Yelp, and define sets based on those information for training, the retailer embedding could better represent relations among all restaurants, which eventually could improve sales for the restaurant retailers. For now we still need post-correction on sales to get a better sales distribution for each retailer, it is expected that an improved retailer embedding could help getting rid of the post-correction.</p><p>For future work, I plan to deploy the model on Google Cloud Platform. At the start of every month, the model will automatically collect economic indexes from last month, forecast indexes and total transactions for the current month, and then generate current month transactions in detail. It will also allow retraining of the synthesizers when new transaction records come in and forecast months in the further future.</p><h3>References</h3><p>[1] L. Xu, M. Skoularidou, A. Cuesta-Infante, K. Veeramachanen, Modeling Tabular Data Using Conditional GAN. (2019), <a href="https://arxiv.org/abs/1907.00503">https://arxiv.org/abs/1907.00503</a></p><p>[2] O. Barkan, N. Koenigstein, Item2Vec: Neural Item Embedding for Collaborative Filtering. (2017), <a href="https://arxiv.org/abs/1603.04259">https://arxiv.org/abs/1603.04259</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c3936423d9a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-deep-learning-based-method-for-synthesizing-data-with-an-application-in-financial-transactions-9c3936423d9a">A deep learning based method for synthesizing data with an application in financial transactions</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>