<?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 Oleg Testov on Medium]]></title>
        <description><![CDATA[Stories by Oleg Testov on Medium]]></description>
        <link>https://medium.com/@oleg_testov?source=rss-e823e36f29c0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*M3Ll617927pspHieYg_NBw.png</url>
            <title>Stories by Oleg Testov on Medium</title>
            <link>https://medium.com/@oleg_testov?source=rss-e823e36f29c0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:35:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oleg_testov/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[Multi-security model for intraday volume forecasting]]></title>
            <link>https://medium.com/machine-learning-with-market-data/multi-security-model-for-intraday-volume-forecasting-f07343f16810?source=rss-e823e36f29c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f07343f16810</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[predictive-analytics]]></category>
            <dc:creator><![CDATA[Oleg Testov]]></dc:creator>
            <pubDate>Wed, 28 Dec 2022 12:12:07 GMT</pubDate>
            <atom:updated>2022-12-29T08:19:50.825Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/machine-learning-with-market-data/trading-volume-prediction-on-the-example-of-nasdaq-index-futures-6033de7ba716">the previous article</a>, we described an example of a simple but effective approach to predicting intraday trading volume. In this post we describe a more advanced approach that addresses a number of issues.</p><p>First, predicting trading volume independently for each security creates model management issues as the number of securities (and, therefore, models) goes into hundreds or thousands. Second, the approach does not support forecasts for newly listed securities (similarly, there is no fast way to get a forecast for a security that a model hasn’t been pretrained on). Finally, considering a model trained on multiple securities enables predictions for an individual security to benefit from the information about other securities.</p><p>To address the above, let’s try to apply the approach of using multi-series models, in which training is performed simultaneously on multiple timeseries. Note that a similar approach was also used in a number of winning strategies in <a href="https://www.sciencedirect.com/science/article/pii/S0169207021001874">M5 Competition</a>.</p><p>In our experiments below, we train LightGBM on multiple securities while making security ID one of the features. We compare its performance to the models trained individually for each security and to a simple benchmark.</p><p>We find that the multi-security model performs as well as models trained on individual securities while offering the benefits of easier management and the ability to make forecasts for newly listed securities.</p><h3>Problem Definition</h3><p>Predict trading volume for each of the given securities in the next 10 minutes.</p><p>Dataset:</p><ul><li>US equities trades/bars (NYSE TAQ) from 2022–02–10 to 2022–10–10</li><li>validation set from 2022–08–09 to 2022–09–08</li><li>test set from 2022–09–09 to 2022–10–10</li></ul><p>Input:</p><ul><li>past trading volume</li></ul><p>Output:</p><ul><li>prediction for the next 10-minute period for each security</li></ul><h3>Features</h3><p>We limit our attention to the lagged values of trading volume for lags 1, 2, 3, 39, 40, the ID of the day’s period (e.g., ‘9:30’, ‘9:40’, etc), and for the multi-symbols model, the ticker.</p><p>To illustrate the lag features: if it’s 10am on a Tuesday, lag 1 carries the volume just traded between 9:50am and 10am, lag 39 is the volume traded Monday (yesterday) between 10am and 10:10am. US trading day is six and a half hours between 9:30am and 4pm, which corresponds to 39 10-minute intervals.</p><p>The data set for a single security is illustrated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*y7E429EY0me-phfNMMkPkQ.png" /></figure><p>The data set with multiple securities stacks datasets with individual securities on top of each other and includes the ‘ticker’ feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*A4MFI-a1dOfmVc88osgHHg.png" /></figure><h3>Experimental setup</h3><h4>ML model</h4><p>LightGBM with the default parameters except for boosting_type=&#39;dart&#39;. Experiment 3 includes a grid search over key hyperparameters for accuracy (num_leaves, max_depth, min_data_in_leaf).</p><h4>Validation</h4><p>We train the model on the training set iteratively optimizing the loss function. We also compute the performance of the model in each iteration on the validation set according to the evaluation metric. We return the model from the iteration that resulted in the best value of the eval metric on the validation set.</p><h4>Preprocessing</h4><p>We normalize volumes by the number of shares outstanding. The volumes are adjusted for corporate actions with the adjustment date and the number of shared outstanding as of the last day of the data set (2022–10–10).</p><h4>Benchmark</h4><p>Our benchmark method returns the actual value for the last period as a prediction for the next one except for the first period of the day (9:30am-9:40am) for which the trading volume from the same interval of the previous trading day is returned.</p><h3>Experiment #1: Train model on all S&amp;P 500 symbols</h3><p>Our first experiment includes all tickers of S&amp;P 500. By design, the multi-security model trains on 500 times more data than each of the 500 single-security models.</p><p>We perform a grid search over some of the key model hyperparameters. We discuss hyperparameter tuning in more details in Experiment #2. The other parameters of the experiment remain the same.</p><p>Encouragingly for the multi-security model, its performance is on par with the single-security models and far outperforms the benchmark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8MwL-aXMxXo55qcfNmfFqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tOncPuqjFDD1fRQwht2YFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h3pu6QZ9lEMdclD8GGxL0Q.png" /></figure><h3>Experiment #2: Compare training models with and without hyperparameter optimization (for the top 100 S&amp;P 500 symbols)</h3><p>In the second experiment we tune the values of num_leaves, max_depth, min_data_in_leaf for the single and multi security models.</p><p>Hyperparameter tuning is important for the multi-security model: in particular, the tuned model results in much lower MAPE values. R2 is not improved by much. There is little benefit in tuning for the single-security models. Our intuition is that simpler single-security models work well with the default parameters while a much more complicated (in terms of the input data) multi-security models benefit from tuning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d215X161yTXztO9k4dhC_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V648vW_ZJlgzdBVO0Kyx-Q.png" /></figure><p>In the first two experiments, we got interesting results, but let’s check reliability of the findings.</p><h3>Experiment #3: Training models on sets of 50 randomly selected S&amp;P 500 securities</h3><p>This experiment aims to gain statistically significant insights into the relative performance of single and multi-securities models.</p><pre>- Repeat 50 times (for each experiment):<br>    - pick 50 securities uniformly at random from the S&amp;P 500 securities<br>    - train the multi-security model on the selected securities<br>    - train 50 single-security models<br>    - for each security compute the metrics on the test set for:<br>        - the multi-security model<br>        - individually trained single-security model<br>        - the benchmark<br>- Compare the performance across 50 experiments and 50 securities</pre><p>The metrics for the multi-security and individual models are pretty similar and both are much better than the benchmark.</p><p>We compare both the means and the medians for each of the three competing models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EPl6BVUttI50PiWrRDGoag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aiost22_JcRUkkZH_889qQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQIOaRatf2cPf_t7ZOj5RA.png" /></figure><p>Next, we take a closer look at the relative performance of the multi and single models.</p><pre>- for each experiment:<br>  - for each security:<br>    - compute the difference between the metrics of multi and single models<br>      - MAPE: delta = single - multi<br>      - R2: delta = multi - single<br>      (positive values of delta reflect better performance of multi over single)</pre><p>We can see that the performance of the models is nearly identical: we cannot conclude that either one is better.</p><p>The 95% confidence intervals below for MAPE and R2 are roughly centered around zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a8U0E5qFJQz3CtXQJNhaHw.png" /></figure><p>We include the intervals based on percentiles as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvcW9BWGcKUxxOvbVF50NA.png" /></figure><p>We contrast the relative performance of multi vs single discussed above with the relative performance of benchmark vs single.</p><p>The relative performance of the benchmark model and the single model shows that the single model is likely to outperform the benchmark. The 95% confidence interval for the difference in performance is above zero for both R2 and MAPE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMRsgeaTw_PnO2e6qMYpQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PVzeqAQsIMzcn6v13C1pQg.png" /></figure><h3>Experiment #4: Applying a pretrained multi-security model to make predictions for new securities</h3><p>Our next experiment explores the performance of a multi-security model on securities that it was not trained on. This allows, for example, making predictions for newly listed securities.</p><p>We measure the quality of such predictions relative to the predictions made by the multi-security model with all symbols present and relative to the predictions of single-security models.</p><p>We take the top 50 of S&amp;P 500 symbols by market cap, train a multi-security model on them, remove 5 symbols from the set, and train another multi-symbol model on the remaining 45 symbols. We also train 5 single-symbol models on the removed symbols. We then make forecasts for the 5 symbols using the three models above.</p><p>The other parameters of the experiment remain the same.</p><p>We remove securities 23–27 (tickers: ABBV, KO, MRK, ORCL, PEP) for the results reported below. Removing randomly selected securities produced similar results that we discuss in the next experiment.</p><p>The table below summarizes the results for the 5 removed securities. The metrics for “multi with all symbols” and “multi with removed symbols” are similar for all 5 securities. The metrics for the single-secuity model are also similar on all symbols except PEP where the single-security model has better MAPE and MAE values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ggfDzr0J6PiDjTJdZ85koA.png" /></figure><p>The results for the model with removed symbols are encouraging for the use case of forecasing volumes for newly listed symbols.</p><p>The next experiment on clustering shows that predictions for unseen symbols are better when the unseen symbols come from the same “cluster” as the symbols used for training the model.</p><h3>Experiment #5: Compare metrics on new securities for “random” model vs “cluster” model</h3><p>In this experiment, we compare the performance of 2 types of models on new securities. The first type of models is trained on a random sample of S&amp;P 500 securities. The second type of models is trained on similar securities to the ones predictions are made for. We also use single-security models as an additional benchmark.</p><p>To select similar securities (a “cluster”), we look for the securities that are close in terms of the capitalization, trading volume and volume volatility. The volume is normalized by the outstanding shares.</p><p>We define a cluster by applying three conditions:</p><ul><li>0.31-quantile to 0.69-quantile by market capitalization</li><li>0.31-quantile to 0.69-quantile by trading volume</li><li>0.31-quantile to 0.69-quantile by standard deviation of volume</li></ul><p>The cluster size is 50 securities.</p><p>The experiment is defined as follows.</p><pre>- Repeat 50 times (for each experiment):<br>  - pick 45 securities uniformly at random from the cluster and consider <br>    the remaining 5 securities as &quot;new&quot; securities<br>  - train the multi-security model on the selected 45 cluster securities<br>  - remove the 5 new securities from S&amp;P 500 and pick 45 securities <br>    uniformly at random from the remaining 495 symbols<br>  - train the multi-security model on the selected 45 random securities<br>  - train 5 single-security models on the 5 new securities<br>  <br>  - for each of the 5 new securities compute metrics on the test set for:<br>    - the multi-security model trained on 45 cluster securities<br>    - the multi-security model trained on 45 random securities<br>    - the single-security model trained on the new security<br>- Compare the performance across all 250 trials <br>  (50 experiments * 5 securities)</pre><p>The mean and median of the metrics (across all results) for each model type are shown in the charts below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYUW8lrW_ysWXlNsIT3Jww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZPRhPabjfChD1ysj8QQuEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*npT1lI4TGcsfjJ7BZT8qXQ.png" /></figure><p>The cluster model has the best results in most of the cases, although it is close to the other two types of models.</p><p>We plan to continue research in this direction, including adding other features used in clustering, as well as applying more advanced clustering methods.</p><h3>Conclusions</h3><p>The main takeaways of the experiments are summarized below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Din_lsSovlPkKtJsj80o1Q.jpeg" /></figure><p>Multi-security models are more convenient to work with and allow making predictions on new securities. Their performance when using data normalization and hyperparameter optimization is similar to separately trained single-security models. In many cases it is even better, but so far it has not been possible to achieve a statistically significant advantage. Preliminary results of new research show that security clustering can improve the performance of multi-security models on new securities.</p><h3>Notes</h3><h4>Other benchmarks</h4><p>We intend to expand the set of benchmarks to other statistical models and in particular exponential smoothing models such as Holt-Winters.</p><h4>Other multi-series approaches</h4><p>We intend to experiment with other approaches to make predictions based on multiple time series. In particular, neural net-based approaches such as the one implemented in <a href="https://unit8.com/resources/training-forecasting-models/">Darts</a>, as well as applying more advanced security clustering.</p><h4>Notebooks with source code</h4><p>Coming soon.</p><p>Thank you for your time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f07343f16810" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-with-market-data/multi-security-model-for-intraday-volume-forecasting-f07343f16810">Multi-security model for intraday volume forecasting</a> was originally published in <a href="https://medium.com/machine-learning-with-market-data">Smart Compliance AI Lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trading volume prediction on the example of Nasdaq index futures]]></title>
            <link>https://medium.com/machine-learning-with-market-data/trading-volume-prediction-on-the-example-of-nasdaq-index-futures-6033de7ba716?source=rss-e823e36f29c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6033de7ba716</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[market-research]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[futures-trading]]></category>
            <dc:creator><![CDATA[Oleg Testov]]></dc:creator>
            <pubDate>Tue, 07 Jun 2022 13:04:02 GMT</pubDate>
            <atom:updated>2025-07-02T15:32:50.522Z</atom:updated>
            <content:encoded><![CDATA[<h3>Trading volume prediction</h3><p>Working at <em>OneTick</em> and engaging with clients in the field of financial markets, we constantly face interesting and in-demand tasks. One example is the task of predicting trading volume, which is relevant for several reasons: it helps improve execution quality for large orders and assists in identifying market anomalies that may indicate manipulative behavior. In addition, volume prediction can help in the development of trading systems, e.g. when extrapolating indicators using volume.<br>In this article, I show an example of building a relatively simple, but quite effective model for predicting the trading volume of Nasdaq index futures for 10 minutes ahead.</p><p><strong>Approach</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SMOXzOCxaXHe-jXC" /></figure><p>To solve the described problem, we are going to use machine learning, which, of course, is not surprising.<br>In order to improve the prediction quality of the model, we try to cover market trends more broadly and consider not only the trading volumes of Nasdaq index futures directly, but also combine them with ETF and options data.<br>We also try different methods of data preprocessing, compare different ML models, and select the most suitable options.</p><p><strong>Loading data</strong></p><p>We are going to use tick-by-trade data for the period from April 1, 2021, to March 31, 2022 (1 year). Our focus is on the E-mini NASDAQ-100 futures, with the goal of predicting the trading volume for the next 10-minute interval. For this purpose, we select the six main contracts traded during this period: NQ\H21, NQ\M21, NQ\U21, NQ\Z21, NQ\H22, and NQ\M22.</p><p>There is one nuance here. If we simply join the futures together, we face the effect of a smooth attenuation of the volumes of the old futures and a smooth increase of the volumes of the new futures near the expiration date.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q_QCNPs7EvwHllUyutF4jA.png" /><figcaption>NQ\H22 (upper chart) and NQ\M22 (lower chart) on the same timeline</figcaption></figure><p>However, adding up the volume of contracts aligns the chart and makes it stable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pqv8aKg79KRbkZnhamGJnA.png" /></figure><p>Thus, after loading the futures data, we summarize the volumes of different futures into a single time series, although this only plays a significant role at moments close to expiration dates.</p><p>With ETF time series everything is quite simple, we just take the data of the Invesco QQQ ETF (QQQ) ticker, and no additional manipulation is required.</p><p>The third time series we consider is options on the QQQ ETF. Since there is a huge pool of options contracts for different strike prices and expiration dates, we look at all trading days during the specified time period (1 year) and, for each day, identify the top 5 contracts with the largest volume. As a result, we get a smaller set of main symbols, then we sum up their volumes and build a single time series. Just to note, this data is only used as an additional feature when predicting the volume of Nasdaq E-minis.</p><p>To create the features from tick data, it is convenient to turn to the power of the <em>OneTick</em> platform using the Python library <a href="https://medium.com/machine-learning-with-market-data/pandas-like-onetick-api-for-market-data-c4c3665c751b"><em>onetick-py</em></a> (or <em>otp</em>). We can easily access any market data and quickly apply various filters and aggregations, since <em>onetick-py</em> has a pandas-like syntax familiar to most analysts, and the <em>OneTick</em> platform offers a significant degree of parallelization for the tasks being performed.</p><p><em>Let’s try it! A small example for getting futures data. Here is how easy it is with onetick-py:</em></p><pre>data = data.agg({&#39;VOLUME&#39;: otp.agg.sum(&#39;SIZE&#39;)},<br>                bucket_interval = 600)<br>fut_df = otp.run(data, apply_times_daily=True)</pre><p>Raw tick data (trades) are aggregated into buckets (intervals) of 600 seconds = 10 minutes. Filtering by time is also performed since we consider only the main equities trading session with a duration of 6.5 hours = 390 minutes: from 9:30am to 4:00pm. Thus, each trading day is divided into 390 minutes / 10 minutes = 39 intervals.</p><p><em>Learn more about onetick.py here: </em><a href="https://medium.com/machine-learning-with-market-data/pandas-like-onetick-api-for-market-data-c4c3665c751b"><strong><em>Pandas-like OneTick API for Market Data</em></strong></a></p><p>otp returns data in a pandas dataframe. ETF and options are loaded the same way.</p><p>The resulting data for feature creation looks like this:</p><pre>columns = [&#39;VOLUME_fut&#39;, &#39;VOLUME_etf&#39;, &#39;VOLUME_opt&#39;]<br>ts[columns]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*oMhog5JeXCuZhlJtjg1ZSA.png" /><figcaption>Input data</figcaption></figure><p><strong>Data overview</strong></p><p>Initial analysis of the data shows the presence of strong periodicity, as well as outliers.</p><pre>ts.iloc[-250:].plot(y=&#39;VOLUME_fut&#39;, x=&#39;Time&#39;, figsize=[20, 8])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7U5jEoJuZrhUlv9ehX-Khg.png" /><figcaption>Chart of Nasdaq Index Futures (a small piece of data)</figcaption></figure><pre>fig, ax = plt.subplots(figsize=(20, 8))<br>plt_pacf = plot_acf(ts[&#39;VOLUME_fut&#39;], <br>                    ax = ax, <br>                    lags = np.arange(150), <br>                    auto_ylims = True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qCoIXCUS5n3lZIbUj0HrEA.png" /></figure><pre>fig, ax = plt.subplots(figsize=(20, 8))<br>plt_pacf = plot_pacf(ts[&#39;VOLUME_fut&#39;], <br>                     ax = ax, <br>                     lags = np.arange(200), <br>                     auto_ylims = True, <br>                     method=&#39;ywm&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0jBCtRFHNB42tTxuOWD5pA.png" /></figure><p>The autocorrelation diagram clearly shows the seasonal component with a period of 39, that is, 1 trading session. The partial autocorrelation diagram also shows a strong dependence of the current volume value not only on the nearest previous value of the time series but also on values near the current time one trading session ago (e.g. lags with values 38, 39, 40, 41).<br>Each trading day, for futures as well as for ETFs and options, represents a U-shaped figure from the beginning to the end of the main trading session. This can be seen if we average the values of the trading volume for each intraday bucket over all the data (1 year — from April 1, 2021, to March 31, 2022), and then plot it as a graph (distribution of the average volume value to the time of each 10-minute interval).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vA-QH_YJDOEVmiDYJivqlw.png" /><figcaption>Futures chart (volumes aggregated by intraday buckets)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NiG5tYKacDptJI8T95zYdA.png" /><figcaption>ETF chart (volumes aggregated by intraday buckets)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9g7HepFZKH8FqgwBzb4fLA.png" /><figcaption>Options chart (volumes aggregated by intraday buckets)</figcaption></figure><p><strong>Data preprocessing</strong></p><p>To improve the quality of training models, it is important to eliminate the effects described in the previous section.<br>First of all, let’s deal with extreme outliers, for this, we limit the maximum (and minimum) value of the volume using several standard deviations added to the average value of the trading volume.<br>In order to avoid any data leakage, we calculate the standard deviation based on the training sample only.</p><pre>means = ts.loc[train_indexes].mean(numeric_only=True)<br>stds = ts.loc[train_indexes].std(numeric_only=True)</pre><pre>for column in columns:<br>    up_border = means[column] + std_num * stds[column]<br>    down_border = max(0, means[column] - std_num * stds[column])<br>    ts[column] = ts[column].clip(lower=down_border, upper=up_border)</pre><p>We use a large value of std_num = 4, so this preprocessing has little effect on the source data, however, this protects us from abnormal values and possibly incorrect data.</p><p>Next, let’s address the issue of intraday seasonality in the data.</p><p>To tackle this, we tested two approaches:<br>- adding the time (hh:mm of the end of each 10-minute interval) as a feature<br>- normalization by intraday averaging</p><p>Both methods showed similar performance. The first is simpler; the second, more broadly applicable.</p><p>The idea behind adding the “hhmm” feature is straightforward and doesn’t require much explanation. However, the normalization approach using intraday averages deserves a closer look.</p><p>First, we calculate the average trading volume for each intraday time bucket over the previous 20 days. We experimented with different window sizes, but increasing it beyond 20 days resulted in only marginal gains.</p><pre>bins = 39<br>window_days = 20</pre><pre>ts_agg = ts.groupby(by=&#39;hhmm&#39;).rolling(window_days).mean()<br>ts_agg = ts_agg.shift(1).reset_index(level=0).sort_index()</pre><p>Then subtract the resulting value from the current value of the trading volume.</p><pre>ts_unseason = ts.join(ts_agg[columns], <br>                      lsuffix=&#39;_orig&#39;,<br>                      rsuffix=&#39;_agg&#39;)</pre><pre>ts_unseason[columns] = ts[columns] - ts_agg[columns]</pre><pre>ts_unseason</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*F8cz_t2JtjXfutT15XvNIg.png" /><figcaption>Fields ‘VOLUME_fut’, ‘VOLUME_etf’, ‘VOLUME_opt’ after preprocessing</figcaption></figure><p>Thus, we are trying to eliminate the repeating U-shape of the data and get more even stationary data.<br>Our assumption is confirmed by the data charts. The partial autocorrelation diagram of the preprocessed data shows the absence of explicit correlation dependencies, except for the nearby values of the time series (lags 1, 2, 3, 4), which reflects a fairly high-quality elimination of seasonality in the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t1AtzpKUzDPcbuglWXHW0A.png" /><figcaption>Chart of futures data after preprocessing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3zsGmwaR9nqSTE2aEF1Rg.png" /><figcaption>Partial autocorrelation after preprocessing</figcaption></figure><p>Trading volumes charts of ETFs and options have a similar appearance.</p><p><strong>Features</strong></p><p>So our goal is to predict the values of futures trading volume.<br>Based on the previously conducted research, we are going to build a fairly simple model. The previous values of the time series — futures, ETF, and options — will be used as features. We select the nearest values of the series — lags 1, 2, 3, 4 — giving the greatest contribution, as well as values near 1 trading session ago — lags 38, 39, 40, 41.<br>Thus, we get 24 features: 8 previous values of futures trading volume, 8 — of ETF trading volume, 8 — of options trading volume.</p><pre>periods = [1, 2, 3, 4, 38, 39, 40, 41]<br>target = [&#39;VOLUME_fut&#39;]<br>features_columns = []<br>for column in columns:<br>    for lag in periods:<br>        feature_col_name = f&#39;{column}_lag_{lag}&#39;<br>        df[feature_col_name] = df[column].shift(lag)<br>        features_columns.append(feature_col_name)</pre><p>Next, let’s evaluate the importance of features.<br>To ensure both interpretability and robustness, we use SHAP values derived from a trained CatBoost model. This approach provides a reliable estimate of feature contributions and offers intuitive visualizations that aid in understanding model behavior.</p><pre>cat = CatBoostRegressor(iterations=1000)<br>cat.fit(df.loc[train_indexes][features_columns],<br>        df.loc[train_indexes][target],<br>        verbose=0,<br>        plot=False)<br>explainer = shap.TreeExplainer(cat)<br>shap_values =\<br>    explainer.shap_values(df.loc[train_indexes][features_columns])<br>shap.summary_plot(shap_values,<br>                  df.loc[train_indexes][features_columns])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*7Sc9MgzZbx-W1RYRbDX9Fw.png" /><figcaption>Feature importance</figcaption></figure><p>To select the optimal subset of features for training, we identify the smallest number of features whose cumulative SHAP value accounts for at least 95% of the total importance. This adaptive selection strategy allows us to exclude redundant inputs and build more efficient models without sacrificing performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*r8qXLGvZZpyxvn6PvG_dmQ.png" /></figure><p><strong>Splitting and scaling</strong></p><p>Before proceeding with the training process, we perform standard procedures:</p><ul><li>define training, validation, and test data sets for correct fitting and testing models</li><li>scale of features to a single range in an attempt to simplify and improve the quality of training models</li></ul><p>The fitting of the scaler is made, of course, only on training data in order to avoid data leakage (similar to what we did when eliminating outliers in the data preprocessing section).</p><pre>test_size = .1<br>x_train, x_test, y_train, y_test = \<br>    train_test_split(df[top_features], df[target], <br>                     test_size=test_size, <br>                     shuffle=False)</pre><pre>val_size = .1<br>val_size /= (1 - test_size)<br>x_train, x_val, y_train, y_val = \<br>    train_test_split(x_train, y_train, <br>                     test_size=val_size, <br>                     shuffle=False)</pre><pre>scaler = MinMaxScaler()<br>scaler.fit(x_train)</pre><pre>x_train = pd.DataFrame(data=scaler.transform(x_train), <br>                       index=x_train.index, <br>                       columns=x_train.columns)<br>x_val = pd.DataFrame(data=scaler.transform(x_val), <br>                     index=x_val.index, <br>                     columns=x_val.columns)<br>x_test = pd.DataFrame(data=scaler.transform(x_test), <br>                      index=x_test.index, <br>                      columns=x_test.columns)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ceo6UH2WKjW_n1jSKH0Efg.png" /><figcaption>x_train</figcaption></figure><p><strong>Training and validation of models</strong></p><p>For comparison, 4 types of models are selected: XGBoost Regressor, CatBoost Regressor, CascadeForest Regressor, and DNN (multilayer perceptron).<br>A similar approach is applied to each type of model, simple but quite effective:</p><ul><li>in the first stage, we optimize the hyperparameters of the model using walk-forward validation, that is, we calculate the value of the estimated metric averaged over all folds (training + validation subsamples) for each set of hyperparameters being tested</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*IhqtR-QimJhwVZqUbl6sMw.png" /><figcaption>Walk-forward validation: iterations of training on different folds (from top to bottom). Blue — training subsample, red — validation subsample</figcaption></figure><p><em>Note: if in the process of walk-forward validation we use N folds, then we also have N trained models (each trained and validated on its training + validation subsample).</em></p><ul><li>next, we select a set of hyperparameters that showed the best value of the generalized (averaged over all folds) evaluation metric</li><li>then, we select a set of models (N models, each of which is trained and tested on its fold) corresponding to the best available set of hyperparameters</li><li>finally, to obtain the final prediction, we use an ensemble approach, averaging the predictions of all the models selected in the previous step</li></ul><p>As the tests show, the use of an ensemble model allows to obtain a better and more stable predictive system.</p><p><strong>Evaluation of models</strong></p><p>Consider the results obtained. We verified that the relative prediction quality of various types of models on validation and test data was consistent with each other, which increases the likelihood of the representativeness of the comparison results on the test sample.</p><p>Let’s plot the predicted and actual trading volume of E-mini NASDAQ-100 futures for various types of models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MtboDHuxevJPopSQ76lrsA.png" /><figcaption>XGBoost prediction on the test sample</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kl7yYJDJIpl2ojm0DX4_Cg.png" /><figcaption>CatBoost prediction on the test sample</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E67mjmWAHQJPPZR2d8jmxA.png" /><figcaption>CascadeForest prediction on the test sample</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*UsPmQQg2CRQ2k_g5NYa2KA.png" /><figcaption>DNN prediction on the test sample</figcaption></figure><p>At first glance, all models describe the test data well, for a more accurate assessment, we calculate the exact values of the quality evaluation metrics.</p><p>In total, 4 metrics were selected:</p><ul><li>Mean Average Error (MAE)</li><li>Mean Average Percentage Error (MAPE)</li><li>R-squared (R2)</li><li>Mean Average Error / Standard Deviation of Volume (MAE/StdDev)</li></ul><p>In addition, we build a baseline model of the following type:<br>- let’s take the original time series and remove seasonality from it by subtracting intraday averaged values (since this was done in the preprocessing section)<br>- then assume that the current value of the series is equal to the previous value of the series<br>- in the end, we add the seasonal component back</p><p>Now we can compare models not only with each other but also with respect to the baseline model.</p><p>The table below summarizes the final results:</p><pre>               <strong>MAE         MAPE     R2       MAE/StdDev   </strong><br><strong>Baseline       </strong>2517.9539   21.11%   0.6939   38.15%<br><strong>XGBoost        </strong>2164.3319   18.44%   <strong>0.7704</strong>   32.79%    <br><strong>CatBoost       2129.0891</strong>   <strong>17.34%</strong>   0.7606   32.26%    <br><strong>DNN            </strong>2206.7617   19.37%   0.7647   33.44%    <br><strong>CascadeForest  </strong>2200.6267   18.99%   0.7658   33.34%</pre><p>A significant advantage of advanced models over the baseline model is visible. The results of advanced types of models are quite close, but CatBoost slightly outperforms the others overall.</p><p><strong>Future research</strong></p><p>There is a significant field for further research.<br>First of all, we aim to explore more data preprocessing methods.<br>For example, partial autocorrelation shows the presence of weak weekly seasonality. Its elimination will help slightly improve the results.<br>Secondly, it is interesting to try to use additional features, such as the bid/ask ratio of volumes, volume profile, news data, etc.<br>Finally, it is important to test other machine learning models, for example, more complex neural network architectures such as LSTM and GAN.</p><p>We are also developing the <em>OneTick Data Science Framework</em>, which enables fast and convenient execution of ML experiments, as well as result tracking and storage.</p><p>We’ll cover these directions in future articles.</p><p>The notebook with the final research (without testing preliminary hypotheses) is presented here: <a href="https://github.com/onemarketdata/ml/tree/master/research/volume_prediction">VolumePrediction (github.com)</a></p><p>Thank you for your time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6033de7ba716" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-with-market-data/trading-volume-prediction-on-the-example-of-nasdaq-index-futures-6033de7ba716">Trading volume prediction on the example of Nasdaq index futures</a> was originally published in <a href="https://medium.com/machine-learning-with-market-data">Smart Compliance AI Lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>