# Exploring the S and P 100 Index Stocks Using Graph Machine Learning

### Explore how to use the Java-based graph analysis library JGraphT and the diagramming library mxGraph to visualize the changes of correlation between the S&P 100 Index stocks over time.

· Database Zone · Tutorial
Save
5.56K Views

In a previous post of this series [1], we introduced how to use the Python-based graph analysis library NetworkX [2] and Nebula Graph [3] to analyze the character relationships in “Game of Thrones”.

In this post, we are going to explore how to use the Java-based graph analysis library JGraphT [4] and the diagramming library mxGraph [5] to visualize the changes of correlation between the S&P 100 Index stocks [6] over time.

## Dataset Processing

The main analysis method used in this post refers to [7] and [8]. There are two datasets: the vertex set and the edge set.

### Stock Data (Vertex Set)

Select the following S&P 100 Index stocks, and model each stock as a vertex. The properties of each vertex are the stock code and the industry of the listed company.

Table 1: The vertex set sample

Vertex ID Code Industry Company Name
1 AAPL Consumer Electronics Apple Inc. (AAPL)
2 ABBV Drug Manufacturers—General AbbVie Inc. (ABBV)
3 ABT Medical Devices Abbott Laboratories (ABT)
4 ACN Information Technology Services Accenture plc (ACN)
5 AIG Insurance—Diversified American International Group, Inc. (AIG)
6 ALL Insurance—Property & Casualty The Allstate Corporation (ALL)
7 AMGN Drug Manufacturers—General Amgen Inc. (AMGN)
8 AMT REIT—Specialty American Tower Corporation (REIT) (AMT)
9 AMZN Internet Retail Amazon.com, Inc. (AMZN)

### Stock Relationship (Edge/Relationship Set)

Each edge has only one property, i.e. the weight. The weight of an edge indicates the daily return rate similarity of the listed companies represented by the vertices (stocks) on both ends of the edge. The similarity algorithm refers to [7] and [8]: Analyze the time-series correlation of the individual stocks’ daily return rateover a period of time (from 2014-01-01 to 2020-01-01), and define the distance between the individual stocks (i.e. the edge weight) as follows.

Through such processing, we get the range of the distance as [0,2]. That means the more distant the two stocks, the lower the correlation between their return rates.

Table 2: The edge set sample

Source vertex ID Target vertex ID Edge weight
1 2 1.4206879982683
1 4 1.37090336100054
1 6 1.39684994985333

Such a vertex set and an edge set form a graph network, which can be stored in the Nebula Graph database.

## JGraphT

JGraphT is an open-source Java class library that provides not only a variety of efficient and common graph data structures but also many useful algorithms for solving the most common graph problems. The features of JGraphT are as follows:

• Supports directed edges, undirected edges, weighted edges, non-weighted edges, etc.
• Supports simple graphs, multigraphs, and pseudographs.
• Provides dedicated iterators (DFS, BFS, etc.) for graph traversals.
• Provides a large number of commonly used graph algorithms, such as path lookup, isomorphism detection, coloring, common ancestors, wandering, connectivity, matching, cycle detection, partitioning, cutting, flow, and centrality.
• Provides easy import from/export to GraphViz. The exported GraphViz file can be applied by the visualization tool Gephi for analysis and demonstration.
• Supports convenient graph network generating while used with tools such as JGraphX，mxGraph，and Guava Graphs Generators.

Next, let’s try it out.

1. Create a directed graph in JGraphT.
Java

x
15

1
`import org.jgrapht.*;`
2
`import org.jgrapht.graph.*;`
3
`import org.jgrapht.nio.*;`
4
`import org.jgrapht.nio.dot.*;`
5
`import org.jgrapht.traverse.*;`
6

7
`import java.io.*;`
8
`import java.net.*;`
9
`import java.util.*;`
10

11
`Graph<URI, DefaultEdge> g = new DefaultDirectedGraph<>(DefaultEdge.class);`
12

13
`URI google = new URI("http://www.google.com");`
14
`URI wikipedia = new URI("http://www.wikipedia.org");`
15
`URI jgrapht = new URI("http://www.jgrapht.org");`

Java

`xxxxxxxxxx`
1

1
`g.addVertex(google);`
2
`g.addVertex(wikipedia);`
3
`g.addVertex(jgrapht);`

Java

`xxxxxxxxxx`
1

1
`// Add edges to create a linked structure`
2

3
`g.addEdge(jgrapht, wikipedia);`
4
`g.addEdge(google, jgrapht);`
5
`g.addEdge(google, wikipedia);`
6
`g.addEdge(wikipedia, google);`

## The Nebula Graph Database

JGraphT usually uses local files as data sources. That’s fine when you’re doing static network research, but if the graph network is constantly changing, like a graph network of the stock data, which changes every day, it’s a little bit of a hassle to generate a new static file, then load it and then analyze it every time. Ideally, the entire change process can be written to a database persistently, and subgraphs or the complete graph can be loaded directly from the database in real-time for analysis. In this post, we use Nebula Graph as the graph database for storing the graph data.

Nebula Graph’s Java client nebula-java [11] provides two ways of accessing Nebula Graph. One is interacting with the query engine layer [13] through the graph query language nGQL [12], which is usually suitable for accessing subgraphs and supports complex semantics; The other is to directly interact with the underlying storage layer (the storaged process) [14] through the APIs, which is used to obtain the complete set of vertices and edges. In addition to accessing Nebula Graph itself, nebula-java provides examples of interacting with Neo4j [15], JanusGraph [16], Spark [17], and others.

In this post, we use the APIs to access the storage layer (the storaged process) directly to get all the vertices and edges. The following two interfaces can be used to read all the vertex and edge data.

Java

`xxxxxxxxxx`
1

1
`// space is the name of the graph space to be scanned, and returnCols is the vertex/edge and its properties to be read.`
2
`// Format of returnCols parameter: {tag1Name: prop1, prop2, tag2Name: prop3, prop4, prop5}`
3
`Iterator<ScanVertexResponse> scanVertex(`
4
`            Stringspace, Map<String, List<String>>returnCols);`
5
`Iterator<ScanEdgeResponse> scanEdge(`
6
`            Stringspace, Map<String, List<String>>returnCols);`

1. Initialize a client and a ScanVertexProcessor. ScanVertexProcessor is used to decode the read vertex data:
Java

`xxxxxxxxxx`
1

1
`MetaClientImpl metaClientImpl = new MetaClientImpl(metaHost, metaPort);`
2
`metaClientImpl.connect();`
3
`StorageClient storageClient = new StorageClientImpl(metaClientImpl);`
4
`Processor processor = new ScanVertexProcessor(metaClientImpl);`

1. Call the scanVertex interface, which returns an iterator for the scanVertexResponse object:
Java

`xxxxxxxxxx`
1

1
`Iterator<ScanVertexResponse> iterator =`
2
`                storageClient.scanVertex(spaceName, returnCols);`

1. Keep reading the data in the scanVertexResponse object that the iterator points to until all of the data is read. The read vertex data is saved and later added to the graph structure of JGraphT.
Java

`xxxxxxxxxx`
1
10

1
`while (iterator.hasNext()) {`
2
`  ScanVertexResponse response = iterator.next();`
3
`  if (response == null) {`
4
`    log.error("Error occurs while scan vertex");`
5
`    break;`
6
`  }`
7
`  `
8
`  Result result =  processor.process(spaceName, response);`
9
`  results.addAll(result.getRows(TAGNAME));`
10
`}`

Reading edge data is similar to the above process.

## Analyze the Graph in JGraphT

1. Create an undirected and weighted graph in JGraphT :
Java

`xxxxxxxxxx`
1

1
`Graph<String, MyEdge> graph = GraphTypeBuilder`
2
`                .undirected()`
3
`    .weighted(true)`
4
`    .allowingMultipleEdges(true)`
5
`    .allowingSelfLoops(false)`
6
`    .vertexSupplier(SupplierUtil.createStringSupplier())`
7
`    .edgeSupplier(SupplierUtil.createSupplier(MyEdge.class))`
8
`    .buildGraph();`

1. Add the vertex and edge data read in the last step from the Nebula Graph space to the graph:
Java

`xxxxxxxxxx`
1
10

1
`for (VertexDomain vertex : vertexDomainList){`
2
`    graph.addVertex(vertex.getVid().toString());`
3
`    stockIdToName.put(vertex.getVid().toString(), vertex);`
4
`}`
5

6
`for (EdgeDomain edgeDomain : edgeDomainList){`
7
`    graph.addEdge(edgeDomain.getSrcid().toString(), edgeDomain.getDstid().toString());`
8
`    MyEdge newEdge = graph.getEdge(edgeDomain.getSrcid().toString(), edgeDomain.getDstid().toString());`
9
`    graph.setEdgeWeight(newEdge, edgeDomain.getWeight());`
10
`}`

1. Like the analysis algorithms mentioned in [7] and [8], use Prim’s minimum-spanning tree algorithm for the preceding graph and call the encapsulated drawGraph interface to draw the graph.

Prim’s algorithm is an algorithm in graph theory that searches for a minimum spanning tree in a weighted connected graph. In other words, the tree formed by the edge subset searched by this algorithm not only includes all vertices in the connected graph but also has the minimum sum of weights of all edges.

Java

`xxxxxxxxxx`
1

1
`SpanningTreeAlgorithm.SpanningTree pMST = new PrimMinimumSpanningTree(graph).getSpanningTree();`
2

3
`Legend.drawGraph(pMST.getEdges(), filename, stockIdToName);`

1. The drawGraph method encapsulates parameter settings such as the layout of the drawing. This method renders stocks in the same sector in the same color, grouping close stocks together.
Java

`xxxxxxxxxx`
1
80

1
`public class Legend {`
2
`  `
3
`...`
4
`  `
5
`  public static void drawGraph(Set<MyEdge> edges, String filename, Map<String, VertexDomain> idVertexMap) throws IOException {`
6
`     // Creates graph with model`
7
`     mxGraph graph = new mxGraph();`
8
`     Object parent = graph.getDefaultParent();`
9

10
`     // set style`
11
`     graph.getModel().beginUpdate();`
12
`     mxStylesheet myStylesheet =  graph.getStylesheet();`
13
`     graph.setStylesheet(setMsStylesheet(myStylesheet));`
14

15
`     Map<String, Object> idMap = new HashMap<>();`
16
`     Map<String, String> industryColor = new HashMap<>();`
17

18
`     int colorIndex = 0;`
19

20
`     for (MyEdge edge : edges) {`
21
`       Object src, dst;`
22
`       if (!idMap.containsKey(edge.getSrc())) {`
23
`         VertexDomain srcNode = idVertexMap.get(edge.getSrc());`
24
`         String nodeColor;`
25
`         if (industryColor.containsKey(srcNode.getIndustry())){`
26
`           nodeColor = industryColor.get(srcNode.getIndustry());`
27
`         }else {`
28
`           nodeColor = COLOR_LIST[colorIndex++];`
29
`           industryColor.put(srcNode.getIndustry(), nodeColor);`
30
`         }`
31
`         src = graph.insertVertex(parent, null, srcNode.getName(), 0, 0, 105, 50, "fillColor=" + nodeColor);`
32
`         idMap.put(edge.getSrc(), src);`
33
`       } else {`
34
`         src = idMap.get(edge.getSrc());`
35
`       }`
36

37
`       if (!idMap.containsKey(edge.getDst())) {`
38
`         VertexDomain dstNode = idVertexMap.get(edge.getDst());`
39

40
`         String nodeColor;`
41
`         if (industryColor.containsKey(dstNode.getIndustry())){`
42
`           nodeColor = industryColor.get(dstNode.getIndustry());`
43
`         }else {`
44
`           nodeColor = COLOR_LIST[colorIndex++];`
45
`           industryColor.put(dstNode.getIndustry(), nodeColor);`
46
`         }`
47

48
`         dst = graph.insertVertex(parent, null, dstNode.getName(), 0, 0, 105, 50, "fillColor=" + nodeColor);`
49
`         idMap.put(edge.getDst(), dst);`
50
`       } else {`
51
`         dst = idMap.get(edge.getDst());`
52
`       }`
53
`       graph.insertEdge(parent, null, "", src, dst);`
54
`     }`
55

56

57
`     log.info("vertice " + idMap.size());`
58
`     log.info("colorsize " + industryColor.size());`
59

60
`     mxFastOrganicLayout layout = new mxFastOrganicLayout(graph);`
61
`     layout.setMaxIterations(2000);`
62
`     //layout.setMinDistanceLimit(10D);`
63
`     layout.execute(parent);`
64

65
`     graph.getModel().endUpdate();`
66

67
`     // Creates an image than can be saved using ImageIO`
68
`     BufferedImage image = createBufferedImage(graph, null, 1, Color.WHITE,`
69
`                                               true, null);`
70

71
`     // For the sake of this example we display the image in a window`
72
`     // Save as JPEG`
73
`     File file = new File(filename);`
74
`     ImageIO.write(image, "JPEG", file);`
75

76
`   }`
77
`  `
78
`  ...`
79

80
`}`

1. Visualize the data.

The color of each vertex in Figure 1 represents its industry. We can see that the stocks with high business similarity have been clustered together, but some stocks with no obvious correlation have also been clustered together, the reason for which needs to be studied separately.

Figure 1: Clustering based on the stock data from 2014-01-01 to 2020-01-01

1. Some other dynamic exploration based on different time windows.

The preceding conclusion is mainly based on the stock aggregation from 2014-01-01 to 2020-01-01. We also made other attempts: Use a sliding window of 2 years and the same analysis method to observe if the clustered groups would change over time.

Figure 2: Clustering based on the stock data from 2014-01-01 to 2016-01-01

Figure 3: Clustering based on the stock data from 2015-01-01 to 2017-01-01

Figure 4: Clustering based on the stock data from 2016-01-01 to 2018-01-01

Figure 5: Clustering based on the stock data from 2017-01-01 to 2019-01-01

Figure 6: Clustering based on the stock data from 2018-01-01 to 2020-01-01

## Disclaimer

This post should not be taken as investment advice. Due to the situation of trade suspension, circuit breakers, trading limits, transfers, mergers and acquisitions, changes of the main business, etc., the data processing in this post may be incorrect. We have not checked all the data piece by piece.

Limited by time, this post only selects the data of 100 stock samples in the past six years, and only adopts the method of minimum expansion tree to do the clustering and classification. In the future, maybe we can use larger data sets (such as U.S. stocks, derivatives, and digital currencies) to try more methods in machine learning.

For the code used in this post, please see [18].

## References

[1] Analyzing Relationships in Game of Thrones With NetworkX, Gephi, and Nebula Graph (Part One) https://nebula-graph.io/posts/game-of-thrones-relationship-networkx-gephi-nebula-graph/

[2] Analyzing Relationships in Game of Thrones With NetworkX, Gephi, and Nebula Graph (Part Two) https://nebula-graph.io/posts/game-of-thrones-relationship-networkx-gephi-nebula-graph-part-two/

[3] NetworkX: a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. https://networkx.github.io/

[4] Nebula Graph: A powerfully distributed, scalable, lightning-fast graph database written in C++. https://nebula-graph.io/

[5] JGraphT: a Java library of graph theory data structures and algorithms. https://jgrapht.org/

[6] mxGraph: JavaScript diagramming library that enables interactive graph and charting applications. https://jgraph.github.io/mxgraph/

[7] Bonanno, Giovanni & Lillo, Fabrizio & Mantegna, Rosario. (2000). High-frequency Cross-correlation in a Set of Stocks. arXiv.org, Quantitative Finance Papers. 1. 10.1080/713665554.

[8] Mantegna, R.N. Hierarchical structure in financial markets. Eur. Phys. J. B 11, 193–197 (1999).

[12] Nebula Graph Query Language (nGQL). https://docs.nebula-graph.io/manual-EN/1.overview/1.concepts/2.nGQL-overview/

[13] Nebula Graph Query Engine. https://github.com/vesoft-inc/nebula-graph

[14] Nebula-storage: A distributed consistent graph storage. https://github.com/vesoft-inc/nebula-storage

[15] Neo4j. www.neo4j.com

[16] JanusGraph. janusgraph.org

[17] Apache Spark. spark.apache.org.

Topics:
nebula graph, graph database, machine learning, stocks, data science, ai artificial intelligence, database

Published at DZone with permission of Jamie Liu.

Opinions expressed by DZone contributors are their own.