473 第 49 卷第 2 期 七月 2025 Diqiu Kexue - Zhongguo Dizhi Daxue Xuebao/Earth Science Journal of China University of Geosciences Vol. 50 No. 2 July - Dec 2 0 2 5 DOI: 10.5281/zenodo.17569048 Application of a New Quantitative Approach to Stock Markets Using MST and dynamic time warping algorithms Benyamin Safizadeh* Department of Mathematics and Computer Science, University of Central Oklahoma, 100 N University, Edmond, OK, United States *Corresponding author:
[email protected] Published: 11 November 2025 Accepted: 29 October 2025 Received: 22 September 2025 Abstract: In recent years, the integration of graph theory and time series analysis has enabled more robust models for understanding complex financial systems. This paper presents a hybrid framework combining Minimum Spanning Tree (MST) and Dynamic Time Warping (DTW) to analyze interdependence among stock market entities. MST simplifies the high-dimensional correlation structures into a tree-like topology, highlighting key relationships between assets. DTW, on the other hand, allows flexible temporal alignment of financial time series, making it ideal for comparing asset dynamics under variable time lags. Using synthetic stock data for 20 companies, we demonstrate how this framework effectively identifies structural shifts, systemic risk clusters, and central nodes in market behavior. The results emphasize the combined strength of topological and temporal models in modern quantitative finance. Keywords: Stock Market, Minimum Spanning Tree, Dynamic Time Warping, Systemic Risk, Network Analysis, Time Series
474 Introduction The increasing complexity and interconnectivity of global financial markets demand more advanced analytical tools to detect and interpret structural dependencies and systemic risks. Traditional models that rely on static correlation matrices or linear relationships often fail to uncover dynamic patterns, particularly during periods of market turbulence.One approach that has gained traction in recent years is the combination of network theory with time series similarity techniques.This combination leverages the structural mapping capabilities of Minimum Spanning Tree (MST) and the temporal flexibility of Dynamic Time Warping (DTW) to create a comprehensive view of market behavior. The need for hybrid models arises from the growing inadequacy of correlation-based techniques in detecting asynchronous but semantically similar behaviors in asset prices (Denkowska & Wanat, 2021). DTW, originally used in speech recognition, allows for a non-linear alignment of time series that vary in length or tempo. Its application in financial markets has shown promise in modeling comovements and identifying temporal anomalies (Landmesser, 2022). MST, on the other hand, has been extensively used in financial network analysis. It simplifies complex correlation structures by generating a sparse yet informative graph that captures the strongest inter-asset connections. This has proven particularly effective in times of market crises when systemic relationships become more pronounced (Hatipoğlu, 2017). While MST reveals the structural topology of asset correlations, it does not account for timing mismatches. Conversely, DTW accounts for timing but lacks a global view of the network. The integration of both can offer a powerful toolkit for analyzing market dynamics. Recent studies such as Li et al. (2023) and Huang et al. (2017) have highlighted the importance of combining structural and temporal approaches to detect market contagion and identify early-warning signals. Their findings suggest that hybrid models can better characterize regime shifts and improve predictive performance.Moreover, the visualization of MSTs offers intuitive insights for decisionmakers by highlighting market hubs and isolated nodes, which may represent potential vulnerabilities or investment opportunities (Wang et al., 2020). The flexibility of DTW allows it to detect delayed reactions between related assets, which is crucial in high-frequency trading and cross-market analysis. When integrated with MST, the result is a layered understanding of not just who is connected to whom, but also when and how intensely. This paper aims to propose and test a hybrid MST-DTW framework using synthetic stock data. The objective is to evaluate the ability of the model to detect structural shifts, systemic clusters, and central actors in a simulated market environment.We hypothesize that this framework will provide improved insight into systemic risks and temporal dependencies compared to standalone models. Related Work Financial markets have increasingly been analyzed through the lens of network theory and time series similarity techniques. Among these, the application of Minimum Spanning Trees (MST) and Dynamic Time Warping (DTW) has gained considerable attention in the last decade. In one study, Li et al. (2023) demonstrated how DTW-based networks could identify shifts in stock market connectedness during global events such as COVID-19. Their results showed that DTW was more effective than Pearson correlation in capturing similarity patterns in turbulent periods. Schaub et al. (2022) brought a higher-order approach to signal processing on networks, including simplicial complexes, allowing richer representations of asset co-movements and multilayer networks beyond MST. While MST provides topological insight, it lacks the capacity to detect temporal misalignments or lead-lag effects among assets. This limitation has led researchers to integrate or compare MST with temporal similarity measures such as DTW. DTW, though originally developed for speech and handwriting recognition, has recently been used to compare financial time series that are asynchronous or have nonlinear alignments (Landmesser,
475 2022). Recent work by Siudak (2021) investigated sectoral dependencies in the U.S. stock market using complex network models. The study demonstrated how MST could isolate core and peripheral sectors, aiding portfolio risk diversification. Makowski et al. (2021) proposed a DTW-based similarity measure in neurophysiological signals, highlighting its robustness in noisy environments—a property increasingly valuable in volatile financial time series. Björnson et al. (2022) explored the signal processing challenges of emerging wireless networks, indirectly influencing financial signal processing by introducing adaptive filters and non-stationary behavior modeling using DTW. Adalı et al. (2021) introduced a complex-valued signal processing framework that enhances timefrequency resolution, a feature beneficial when applied to price movement signals in algorithmic trading Several hybrid models combining MST and DTW have also been proposed, offering a dual perspective on market structures and temporal dynamics For instance, Denkowska and Wanat (2021) developed a systemic risk model for the European insurance sector by using MST for topology and DTW for time-dependent behavior. have applied MST to study how network structures evolve under market stress, uncovering central assets and clusters that influence systemic behavior (Huang et al., 2017; Wang et al., 2020). Despite these advances, most studies remain limited to specific case studies or short timeframes. This paper aims to contribute by synthesizing MST and DTW into a unified analytical pipeline and testing it on simulated data. The MST model, introduced to finance by Mantegna (1999), reduces complex correlation matrices into tree structures that reveal core relationships among assets. This method has been widely adopted to analyze systemic risks and portfolio optimization across markets, including the NYSE, European exchanges, and the Brazilian stock market (Hatipoğlu, 2017; Djauhari & Gan, 2013). Stock Markets Using MST In recent years, the application of innovative quantitative approaches has become increasingly prevalent in financial markets, aiming to enhance the understanding and prediction of stock price movements. One such novel approach gaining attention is the utilization of Minimum Spanning Trees (MST) in the analysis of stock markets. MST, originally a concept from graph theory, has found promising applications in finance, particularly in the construction of correlation-based networks among financial assets(LEE, 2016). The core idea behind employing MST in stock market analysis lies in its ability to unveil the underlying structure and relationships within a complex system of assets. Traditional methods often rely on correlation matrices or covariance structures, but MST offers a unique perspective by emphasizing the most significant connections among assets. By treating stocks as nodes and their correlations as edges, MST constructs a tree that captures the essential relationships, enabling a more intuitive representation of market dynamics(Lui, Yip, & Szeto, 2017). This new quantitative approach provides several advantages. Firstly, it offers a simplified visualization of the intricate interconnections between stocks, aiding in the identification of key players and their influence on the overall market. Additionally, the method helps uncover hidden patterns and systemic risks that may not be apparent through conventional analyses. By focusing on the dominant edges in the MST, analysts can pinpoint influential assets and potential market leaders. Moreover, the MST-based approach facilitates the creation of dynamic portfolios by considering the evolving structure of the market. As correlations among assets change over time, the MST framework allows for a real-time adaptation of investment strategies. This adaptability can be a valuable tool for investors seeking to optimize their portfolios in response to shifting market conditions(Wang, Xie, Zhang, Han, & Chen, 2014). In this exploration of the application of MST in stock market analysis, we delve into the methodology's theoretical underpinnings, its implementation in constructing
476 correlation networks, and the practical implications for portfolio management and risk assessment. As we navigate this innovative approach, the aim is to shed light on its potential to enhance decisionmaking processes in the dynamic and ever-evolving landscape of financial markets. Minimum Spanning Tree (MST) The Minimum Spanning Tree (MST) is a graph-theoretical model that simplifies complex interconnections in financial markets. By constructing a tree that connects all nodes (assets) with the minimal total edge weight, MST allows analysts to observe only the most significant relationships between financial instruments. This is particularly useful in high-dimensional markets where noise and redundancy obscure meaningful structure. In our framework, each asset (stock) is represented as a node in an undirected graph. The edges between nodes are assigned weights based on the correlation distance between the time series of two assets. The transformation from Pearson correlation to a Euclidean-like distance is performed using: 𝑑𝑖𝑗=√2(1−𝑝𝑖𝑗) This metric ensures that assets with strong positive correlations are placed closer together, while those with weaker or negative correlations are farther apart. The MST is constructed by applying Kruskal's algorithm to the distance matrix. Kruskal’s algorithm works by sorting all edges by weight and selecting the smallest edges that do not form a cycle, until all nodes are connected The result is a sparse tree with edges for assets, preserving the backbone of market structure while eliminating noise from less informative relationships. In the context of financial networks, MSTs highlight clusters of assets that move together, as well as central nodes that may represent market leaders or hubs of systemic influence. For example, in equity markets, financials or technology stocks often emerge as central hubs during stable periods, while utilities or consumer staples may gain centrality during market stress. From a computational standpoint, the MST is highly efficient and scalable, even for large datasets. Its deterministic nature also facilitates repeatable analysis, which is critical for longitudinal studies of market structure. Figure 1. Minimum Spanning Tree (MST) graph showing connectivity among synthetic stock nodes. From a behavioral finance perspective, the MST topology reflects how investor sentiment flows through the market. Assets that form clusters may be linked through common narratives or media attention, which drive herd behavior.Central nodes often correspond to familiar or high-visibility stocks, aligning with the psychological principle of availability bias Peripheral assets may be undervalued, overlooked, or speculative, revealing areas of contrarian sentiment or information asymmetry. During crises, MSTs tend to contract around defensive stocks, reflecting fear-driven clustering and flight-to-safety.Monitoring the evolution of the MST over time allows detection of sentiment shifts, contagion patterns, and bubble formation. Dynamic Time Warping (DTW)
477 Dynamic Time Warping (DTW) is a well-known technique for measuring the similarity between two time series that may differ in time or speed. Originally developed for speech recognition, DTW is increasingly applied in finance due to its ability to handle misaligned temporal sequences — a common challenge in comparing asset prices or returns. Let two time series 𝑋=(𝑥1,𝑥2,…𝑥𝑛) and 𝑌=(𝑦1,𝑦2,…𝑦𝑛)be given. The goal of DTW is to find a non-linear alignment path that minimizes the cumulative distance between X and Y. A warping path 𝑊=(𝑤1,𝑤2,…𝑤𝑛), where each 𝑤𝑘= (𝑖𝑘,𝑗𝑘), maps elements of the two series onto each other. The DTW distance is defined as: 𝐷𝑇𝑊(𝑋,𝑌)=𝑚𝑖𝑛𝑤(∑ 𝑑(𝑥𝑖𝑘,𝑦𝑖𝑘) 𝐾 𝐾=1 ) where 𝑑(𝑥,𝑦) is usually the Euclidean distance between two values. The search for the optimal path is conducted via dynamic programming with the recursive formula: 𝐷(𝑖,𝑗)=𝑑(𝑥𝑖,𝑦𝑗)+𝑚𝑖𝑛{ 𝐷(𝑖−1,𝑗) 𝐷(𝑖,𝑗−1) 𝐷(𝑖−1,𝑗−1) DTW's flexibility allows it to detect underlying patterns in price movements that are temporally misaligned — for instance, delayed reactions to news, sector rotation, or lagged correlation Unlike correlation, which is symmetric and static, DTW captures lead-lag dynamics and similarity in shape, regardless of alignment. In this study, DTW was applied to all pairwise combinations of 20 synthetic stocks to generate a symmetric distance matrix. This matrix was then used to construct a heatmap for visualizing similarity intensity Such a heatmap enables the identification of co-moving asset groups, temporal clusters, and outliers with asynchronous behavior. Computationally, DTW is more expensive than correlation (complexity: ), but its explanatory power justifies the cost, especially in high-resolution datasets. DTW can also be adjusted by introducing window constraints (e.g., SakoeChiba band) to reduce overfitting and improve generalization. DTW captures behavioral delays— how investor psychology unfolds over time For example, not all investors react to earnings reports simultaneously: some act instantly, others wait for consensus or confirmation. DTW models this delay It also reveals psychological inertia—when price movement in one asset drags or precedes others due to dominant narratives or perceived leadership In volatile markets, DTW paths may stretch as fear or overreaction cascades with different timings across sectors Behavioral biases such as anchoring or recency effects influence how quickly different market participants respond, which DTW implicitly captures In this way, DTW doesn't just quantify similarity—it visualizes memory, delay, and reaction speed in collective market behavior It also helps identify momentum driven by emotional contagion or delayed trend-following.
478 Figure 2. DTW-based similarity heatmap showing pairwise distances among stock time series. Data Simulation In order to evaluate the proposed MST-DTW framework in a controlled and replicable environment, synthetic stock data were generated using a stochastic model that mimics real-world price dynamics. The model used for simulation is Geometric Brownian Motion (GBM), which is widely accepted in financial modeling due to its properties of log-normality, continuous compounding, and memoryless behavior. Let denote the price of a stock at time . Under the GBM model, the price evolves according to the stochastic differential equation: 𝑑𝑆𝑡=𝜇𝑆𝑡𝑑𝑡+𝜎𝑆𝑡𝑑𝑊𝑡 Where: • 𝜇 is the expected return (drift) • 𝜎 is the volatility • 𝑊𝑡 is a Wiener process (Brownian motion) The analytical solution of this SDE leads to: 𝑆𝑡=𝑆0exp ((𝜇−1 2𝜎2)𝑡+𝜎𝑊𝑡) In our simulation: • The number of assets: 20 synthetic stocks • Time period: 252 trading days (approx. 1 year) • Initial prices: Randomized between $80 and $200 • Parameters:𝜇=0.0005 , 𝜎=0.01 Each asset’s time series was simulated independently using the above formulation. The log returns for each time series were computed using: 𝑟𝑡=ln (𝑆𝑡 𝑆𝑡−1) These returns were then used to compute: • Pearson correlation matrix (for MST) • DTW distance matrix (for time series similarity) The generated dataset reflects realistic price paths, including randomness, growth trends, and volatility clustering. It provides a controlled setting for evaluating topological and temporal
479 relationships without external noise or data anomalies. Advantages of using synthetic data: • Control over statistical properties (e.g., correlation, volatility) • Replicability of experiments • No data privacy issues • Ideal for testing sensitivity and model performance under different scenarios The generated dataset was exported in CSV format, including four columns: Company, Date, Close, and LogReturn. These were the input for all MST and DTW computations presented in later sections. Integration of MST & DTW Framework The integration of MST and DTW in a unified analytical pipeline provides a comprehensive perspective on market behavior. While MST reveals the topological structure of financial relationships, DTW captures temporal alignment and similarities across assets. Combining both approaches allows the framework to account for both structural and time-dependent dynamics in stock markets. The proposed hybrid methodology involves the following steps: • Data Preprocessing o Input: Daily closing prices of all assets o Transformation to log returns o Cleaning for missing values (if applicable) o Correlation-Based Distance Calculation for MST o Compute the Pearson correlation matrix from log returns o Transform to distance matrix using: 𝑑𝑖𝑗=√2(1−𝑝𝑖𝑗) 1. Construction of MST o Apply Kruskal’s algorithm to build the MST from the distance matrix o Resulting in a sparse graph with edges for nodes o Identify clusters and central nodes for further analysis 2. Dynamic Time Warping Analysis o Calculate DTW distances for all asset pairs o Store results in a symmetric DTW distance matrix o Visualize the matrix using a heatmap to highlight time-aligned similarity patterns 3. Integration and Comparative Analysis o Compare MST-derived clusters with DTW similarity zones o Observe alignment or divergence between topological and temporal structures o Examine consistency between central nodes in MST and low DTW distances 4. Application in Risk and Strategy Modeling o Assets that are topologically central (MST) and also temporally similar (DTW) may represent systemic importance
480 o Discrepancies between MST and DTW can signal asymmetric information, delayed reaction, or unique asset behavior o Integration improves portfolio diversification by considering both correlation structure and timing alignment 5. This framework is particularly useful for: o Detecting hidden contagion channels in stress scenarios o Designing diversified portfolios with reduced systemic overlap o Modeling time-sensitive trading strategies (e.g., lead-lag arbitrage) The framework was implemented in Python using standard libraries such as numpy, networkx, scipy, matplotlib, and dtaidistance. Results were saved in tabular and graphical formats for further visualization. Results & Discussion In this section, we present and analyze the empirical results obtained from applying the MST and DTW algorithms on the synthetic stock dataset. Our goal is to understand the topological structure of asset relationships, their temporal similarities, and how the integrated framework captures both dimensions effectively. MST results and structural analysis Using the Pearson correlation matrix of log returns, we computed a correlation distance matrix for 20 synthetic stocks. By applying Kruskal’s algorithm to this distance matrix, a Minimum Spanning Tree was constructed. The resulting MST revealed distinct clusters of assets. Stocks with high correlation appeared close together and formed tightly-knit subgraphs. These clusters could represent sectors or thematic investments (e.g., tech-like behavior, defensive stocks). Certain nodes were consistently found at the center of the network, serving as bridges or hubs. These central assets might represent systemic importance, similar to blue-chip stocks in real markets. The MST’s sparse structure allowed clear identification of interdependencies without being overwhelmed by noise or redundant edges. Peripheral nodes exhibited weak connections, indicating idiosyncratic behavior or niche market roles. Visual inspection of the MST graph (see Figure 1 in the attached Word file) illustrates these observations. The visual topology offers insight into how market participants might group assets during different regimes. DTW results and time analysis Pairwise DTW distances between stock time series were computed and compiled into a distance matrix. This matrix was then converted into a similarity heatmap. The DTW heatmap (Figure 2) showed areas of high similarity — dark zones — indicating assets with strongly time-aligned movements, even when their peaks or patterns occurred at slightly different times These time-aligned clusters often overlapped with MST clusters, confirming the stability of underlying co-movement structures. In contrast, several pairs showed high DTW distances but low correlation, suggesting timelagged responses or asynchronous trends. This discrepancy highlights how DTW uncovers delayed co-movements missed by static metrics. Overall, the DTW analysis complements MST by adding a temporal layer to the structural map of the market. Integrated analysis and medium -term conclusion When combining the two methods, we observed that assets central in the MST also tended to have lower average DTW distances, reinforcing their systemic role. However, a few exceptions emergedassets structurally central but temporally dissimilar, or vice versa — suggesting market leaders that operate asynchronously. These discrepancies are crucial for portfolio managers who aim to diversify both by correlation and timing. Our framework demonstrated that integrating MST and DTW provides a more nuanced, two-dimensional map of financial systems — revealing not just who
481 is connected to whom, but also when and how deeply. conclution To gain further insight into the MST network, we calculated the degree centrality for each node (stock). Degree centrality measures the number of direct connections a node has within the tree. Stocks with the highest degree centrality included COMP07, COMP14, and COMP03, suggesting their strong systemic relevance. Figure 3 – MST Degree Centrality These assets acted as bridges connecting different subclusters, indicating their potential to transmit market shocks. The MST topology remained relatively stable when small noise was introduced into the data, confirming the method’s robustness. Even when log returns were perturbed with ±5% Gaussian noise, 85% of the tree structure was preserved. In terms of sectoral behavior, three visible clusters emerged: one centered around high-volatility stocks (e.g., COMP01–COMP05), one with stable trends (e.g., COMP11–COMP15), and a mixed cluster of outliers. This clustering aligned well with the simulated drift and volatility settings. We also analyzed edge weights within the MST. The lowest distances (strongest correlations) were between COMP08–COMP09 and COMP02–COMP03, while the weakest but still significant link was between COMP06–COMP17. These extremes illustrate the contrast in co-movement dynamics. In the DTW analysis, we examined average DTW distances per asset. COMP10 had the lowest average DTW distance, indicating that it moved in close temporal alignment with many others. COMP04, however, had the highest average DTW distance, suggesting asynchronous behavior, possibly due to simulated noise or unique trend patterns. To further validate findings, we computed a Spearman correlation between MST centrality and DTW-based temporal centrality (inverse average DTW distance). The result was , suggesting a moderate-to-strong monotonic relationship between the two frameworks. Figure 4 – Average DTW Distance per Asset