top of page

Reading Financial Charts in Python I: When Stocks Move Together

Writer: Mic
Mic
Oct 27
7 min read

Updated: Nov 14

Owning sixteen stocks feels like diversification, but very often it could be a single bet wearing sixteen hats.

This post is about finding out which. We take one fixed dataset, calculate returns, and look at the same relationships twice: once as a heatmap and once as a network. Then we break both on purpose by changing thresholds and time windows.

This is not meant as a finance tutorial or a trading strategy. We will not make any predictions. We simply look at how to turn a correlation matrix into something readable, and how much of what you see is a consequence of your own choices.

I mean, I wrote 16 stocks and one bet with 16 hats ... for ChatGPT that is apparently 15 little people with a single bit hat...counting is definitely not its strong suite
I mean, I wrote 16 stocks and one bet with 16 hats ... for ChatGPT that is apparently 15 little people with a single bit hat...counting is definitely not its strong suite

The Baby Example: One Dataset, Fixed

Every chart in this post comes from the same table. So let's build it once, validate it, and save it.

We pick sixteen large US stocks across five sectors. The sector labels live in a dictionary because we will need them for colours later. We also use historical data for reproducibility purposes.

Two habits are worth having here. First, auto_adjust=True gives prices adjusted for splits and dividends. Without it, a stock split looks like a 50% crash.

Second, we save the data. Data providers revise history, and a post whose numbers change every week is hard to debug.

Now the boring but important part: validating the data.

That last line is the one that matters most. The tickers you ask for and the columns you get back do not have to come in the same order. If you later attach a list of metrics to a list of names by position, you may quietly label Microsoft's number as Apple's. Nothing crashes since they both have the same number of datapoints. The chart probably even looks great, but it's still wrong.

The rule for this whole post: match by label, never by position. If it is a pandas object, keep it a pandas object.


Returns, Not Prices

Here is the first trap, prices trend. Almost everything goes up over a few years, so almost every pair of price series looks correlated. That tells us about the shared trend, not about how stocks react to the same news.

So we correlate daily returns instead:

A move from 100 to 102 is a return of 0.02 (or 2%). We also do not have to worry about scale anymore. Let's measure how much the choice matters.

We are measuring the average pairwise correlation between the price series and compare it with the one for the returns. In general, the price-level number is typically far higher. The return-level number is the one that answers our actual question. It is also lower and less flattering, which is usually a sign you are measuring something real.


The Heatmap: Everything vs Everything

A correlation matrix is sixteen rows by sixteen columns of numbers. Let's be honest, we already do not want to read that and we are looking at a small example. A heatmap turns it into a picture and makes use of our natural eye for irregularities.

Three arguments do the real work in this example. First, we have vmin=-1, vmax=1which pin the colour scale to the full range of Pearson correlation. Correlation lives between -1 and +1, not between 0 and 1. If you let the library autoscale, a matrix that only spans 0.1 to 0.6 will look just as dramatic as one that spans -1 to 1.

Secondly, center=0 with a diverging palette makes zero visually neutral. Red and blue then mean positive and negative, not good and bad.

The choice cmap='vlag' was made, since it is a perceptually even diverging palette. Rainbow palettes invent boundaries that are not in the data. Then we end up with this

I this case we only have positive correlation, with some stronger correlation indicators in the blocks that correspond to one sector and the further out of blocks between sectors with a good overlap.


Sorting Reveals Structure

Since we choose our tickers ordered by sectors already, the heatmap comes in a nice form with the strongest correlation close to the diagonal already. But in a general example, the order of your tickers is arbitrary, so the heatmap might look like noise with a diagonal. Order it by something meaningful and blocks appear.

If you do not have sector labels, let the data order itself:

This needs the scipy package, but clustermap runs hierarchical clustering and reorders rows and columns so that similar assets sit together. It is a nice way to ask: do the groups I assumed exist in the data, or only in my head? In our example the clustering is pretty much the same as the division into sectors, but you can see inside a sector which tickers are more correlated to each other than others.


So, Is It Diversified?

A heatmap shows pairs. The diversification question is about the whole portfolio.

Here is a deliberately simple check. Compare the volatility of an equal-weight portfolio with the average volatility of its members.

If every stock moved perfectly together, the ratio would be 1.0. If they were uncorrelated, it would drop towards 1 divided by the square root of 16, which is 0.25.

Real portfolios land in between. The closer to 1, the more of your sixteen hats are one hat.

A caveat on the 252: it is the usual count of trading days in a year, so multiplying by its square root converts daily volatility into an annual figure. This is really a convention and not some fixed rule.


From Heatmap to Network

A heatmap shows every relationship at once. That is both its strength and its weakness. With sixteen assets it is fine. With three hundred, it is wallpaper where you will only spot some extreme outliers.

A network keeps only the relationships that matter and lets the layout do the grouping. The recipe:

  1. Each stock becomes a node.

  2. Two stocks are connected if their correlation is strong enough.

  3. The edge's thickness reflects the strength.

Step 2 is where all the judgement hides, so let's make it a parameter.

Note the abs(r). A filter like r > 0.35 silently throws away every negative relationship, and then any code that colours negative edges can never run. Keeping the sign as an edge attribute means we can draw both.

Now the drawing code. We define the layout explicitly, so the picture is reproducible.

The seed matters, spring layouts start from random positions, so without a seed you get a different picture on every run, and the same graph can look like two different stories.

The node size uses degree centrality: the fraction of other nodes a stock is connected to. A big node is a stock with many strong links. That is really that it has to it.

It is tempting to call big nodes "market drivers" or "systemic influencers". The calculation does not support that. Connectivity in a correlation graph is symmetric: if A and B are correlated, B is equally correlated with A. Nothing in it says who moves whom.

Similarly our choice of threshold is not fixed, to the left we have the 0.5 choice from the example above, while the right shows the same configuration with a threshold of 0.3. This will naturally result in bigger clusters.


Turning the Knob

This last observation with the threshold is really where the network earns its keep, or loses it.

The threshold is a free parameter. Let's see what it does to the structure.

Typically the picture goes from a hairball to a few clusters to scattered islands as the threshold rises. Somewhere in the middle it looks "right", and that is exactly the danger. You can usually find a threshold that gives you the story you were expecting.

The honest approach is to show two or three thresholds side by side and report what stays stable. If the Energy cluster survives from 0.4 to 0.7, that is a finding. If a link only exists at 0.48, it is an artefact. In our example above, we can see that already from 0.3 to 0.5 the Staples cluster and the Health cluster are falling apart, while the others stay together as sectors.


Does It Hold Over Time?

A single correlation matrix compresses the whole sample into one summary, but correlations move. A quick way to look at this: compute the average pairwise correlation over a rolling six-month window.

If the line wanders, then one heatmap is one snapshot, not a property of these stocks. In our example, it wanders quite a bit

In stressed markets, correlations tend to rise, which is precisely when you wanted diversification most. You can go one step further and compare two windows directly:

This one plots the difference. Red cells are pairs that moved closer together; blue cells are pairs that drifted apart. It is a much better question than "what does the matrix look like?"


When NOT to Use This

Correlation heatmaps and networks are exploratory tools. They are bad at several things.

They do not show causation. Two stocks can be correlated because of a shared driver, a shared investor base, or coincidence.

They only capture linear co-movement. Pearson correlation can be near zero for two series with a strong nonlinear relationship, and it can miss the fact that assets sometimes only fall together in the tails.

They depend on your choices. Sample period, return frequency, threshold, layout seed and chosen universe all change the picture.

They do not tell you what to buy. A low correlation in the past is not a guarantee about the future.

If you remember one thing: the chart displays the calculation you gave it. It cannot tell you whether the calculation was the right one.


Wrapping Up

We took one dataset and asked one question: do these stocks really move independently?

We saw that returns, not prices, are the right input. We saw a heatmap show all relationships at once, and that sorting it is what reveals structure. We saw a network show only the strong ones, at the price of a threshold you have to define and potentially vary to see real outcome. And we saw that both are snapshots until you check them across time.

The heatmap tells us how assets move together. It says nothing about how each one moves by itself: how large its typical day is, how fat its bad tail is, whether a "normal" assumption is reasonable.

Comments


bottom of page