Modelling Financial Assets through Embeddings
Lately, I had been looking for offbeat machine learning papers that were not in the typical NLP, audio, or vision domain. AlphaXiv has this great feature of being able to search their repository of papers through semantic search or through an agent. That is how I came across Contrastive Learning of Asset Embeddings from Financial Time Series.
Now, the paper assumes the Efficient Market Hypothesis. It states that the asset price soaks in all of the available market information and that most events surrounding the asset, directly or indirectly, get imbued in the market price of the asset. Of course, this is an ideal that does not play out perfectly in practice, but certain markets around the world are speculated to be very efficient. Following this assumption, we focus only on market prices and hope for them to give us a semantically relevant story and capture supply-chain and sectoral relationships. We have to create a representation space for these assets using their prices as the only signal. How do we do this?
Let’s say we have assets in our pool. For a given asset , we take a window of time—a month worth of daily returns:
where is the price of asset at time . We compare this window of daily close prices with the rest of the assets using the Pearson correlation coefficient, which captures linear correlation between two data sequences. We take the top assets from these assets that have the highest Pearson coefficient and count their occurrences with respect to asset . We then shift the window across by 5 days, corresponding to a trading week, and do the same process again.
We count the total occurrences of the assets in the top with respect to asset . Suppose asset occurs in the top for 50+ windows. That would mean the paired windows of asset and had Pearson correlation high enough for it to appear in the top for 50+ windows. We will call this number the co-occurrence count. We do the same thing we did with asset across the rest of the assets.
where is the similarity vector for asset at window .
This gives us an co-occurrence matrix, where each row represents the co-occurrence counts of some asset with the rest of the assets. We ignore the diagonal, as that would be the co-occurrence count of the asset with itself. Now even though the Pearson correlation coefficient is symmetric for two given assets, the co-occurrence counts of any given two assets are not symmetric. Often for any asset , its top slots will be dominated by its sectoral peers, even when asset might have a high Pearson coefficient. This high correlation can instead be caught by , which will have in its top consistently as it is not as crowded by other assets with higher correlational strength. Or worse, both of them are dominated by other assets with higher correlational strength in their top and will hence have low occurrence counts, which might disregard a true causal relationship. This might turn out to be a problem, as we will see later.
Now with this co-occurrence matrix, the authors assume a null hypothesis, which assumes that the probability of asset co-occurring with is in expectation equal to random chance, i.e. . What this means is that for assets that co-occur more than the expected count by a significant amount, we assume a direct dependency between them. We then use a formula to define a distribution centered around the expected co-occurrence count. This gives us a z-score for each value in the co-occurrence matrix, which basically tells us how unusual a given co-occurrence count is. The closer it is to 0, the more usual it is, and we regard that number of co-occurrences as random and conclude that the occurrence count is not significant enough to suggest a one-way dependency between two assets.
Then we pass this number to the normal cumulative distribution, which tells us the probability mass towards the right of . This tells us, in probabilistic terms, how surprising a pair’s co-occurrence strength would be if co-occurrence were just random chance. We use this -value and positive and negative thresholds to weed out from the assets those that are significant enough to be considered for any asset . There are two thresholds: one for positive samples and the other for negative samples. Negative samples are the co-occurrence counts that are less than the expected count and imply dissimilarity with any given asset . We do this across all the stocks and get filtered positive and negative samples for each asset.
Now based on the co-occurrence counts, we assign probabilities to both the negative and positive samples, where assets with higher counts get assigned more probability for positive samples and the opposite is done for negative samples. This entire process has been the cookbook on how to generate the proper samples to train our embeddings using contrastive loss.
Contrastive loss, popularized by CLIP, is a clever self-supervised training objective that makes use of negative and positive samples to train an embedding space that makes semantic sense. The primary protagonist of this paper is the contrastive loss. If the cookbook was the recipe to make our asset representation space, the contrastive loss would be the heat that cooks it up.
Understanding this intuitively is absurdly simple: for a given asset , similar assets are incentivized to be together, hence they are pulled together; dissimilar assets are incentivized to stay apart, and hence are pulled apart. In the paper, they make use of three possible loss functions to implement this. Using the assigned probabilities for the positive and negative samples from the cookbook, we sample some positive samples and some negative samples. The embeddings of all assets are randomly initialized and then, using the sampled positives and negatives, we try to tweak the embeddings of the anchor asset, the positives, and the negatives such that the cosine similarity between the positives increases close to 1 and the negatives decrease close to -1. This would mean that negative samples that are closer to the anchor assets are positioned in a direction such that they would yield a similarity closer to -1, and the opposite goes for the positive samples. The positives with higher assigned probabilities for a given anchor asset are sampled more often and hence are positioned closer together with the anchor asset, while the opposite goes for the negatives. The authors also mention a loss to encourage the embeddings to be on the unit hypersphere such that the embeddings are normalized and bounded to a given volume in the embedding space. Equipped with these two loss functions, we can effectively train the embeddings to form a meaningful representation space.
The authors in the paper used US stock data, which is considered more efficient. I was curious to see how this would work with Indian stocks. I pulled in one day close data for around 500 symbols over 10 years, converted them into daily returns, and wrote the cookbook pre-processing script. You can find the repository here; instructions are given in the README to set it up. I used my own set of hyperparameters by doing a hyperparameter sweep over many training runs. The training runs are very fast and take around 5–6 seconds on an M2 CPU.
The paper uses an SVM classifier to train and predict the sector labels using the embedding vectors, and uses the SVM as a proxy to measure how well the asset embeddings are doing. Now there is a caveat to using sector classification as a proxy measure: many companies do not have proper sectors that they semantically really belong to, and their official labels are often very broadly classified. This makes a sector like capital goods have a lot of assets that do not generally move together and are spread across many sectors. This then really makes it a makeshift proxy measure to judge the embedding vectors, as there are not many tractable ways to judge the quality of the vectors trained. Another way we can check the quality, as shown in the paper, is by having a pool of stocks to hedge from using the embeddings we trained and then checking the performance of our asset-embedding-chosen hedge portfolio.
After using optimal hyperparameters, the loss plateaued and the F1 score, calculated using an SVM, touched 55%, compared to the paper’s 67%. I projected these embeddings onto a 2D t-SNE graph by visualizing them through an interactive HTML file. You can see very interesting sector clusters and cross-sector grouping. I played around with the graph and made some interesting observations that made semantic sense. Asset clusters from the power, oil and gas, and construction sectors are relatively closer together than other sectors. Siemens has positioned itself across two sectors: automobile and chemicals. You can interact with the graph here and note your own observations.
I had a back and forth with the main author, asking about some implementation choices he made and about the implementation differences I noted from my end when using Indian stocks to train. These were some points I noted when I implemented it myself:
-
I needed considerably longer training epochs than mentioned in the paper while using their learning rates for the loss to really plateau.
-
Anchor assets with higher entropy in their co-occurrence distributions were getting clustered in general regions together, and in the t-SNE they are seen to be clustered in the center. This makes a lot of sense, as there is not a strong enough pull from a particular asset or bunch of assets for these assets to be pulled to a certain region.
-
Sectors that are semantically ambiguous like capital goods are scattered across the graph, as individual assets share relationships with other sectors, like food manufacturing companies being seen with a cluster of fast-moving consumer goods industry assets.
Apart from these differences, through the references of the t-SNE graph and the sectoral classification metric, the contrastive objective worked fairly well on the cookbook we generated from the Indian asset data. There are a few scopes that still remain interesting to be explored:
-
Cross-window correlations seem to be an interesting idea that can be experimented with, with a few caveats in mind as mentioned by the author of the paper in a response to my email. One concern is that cross-window correlations with a lag would capture the general market momentum, with its higher linear correlation across many assets, and hence would add noise to the cookbook. But it is still worth trying out.
-
As we had gone through before, while top- serves as a great way to use the null hypothesis and figure out the strong correlations, it could also hide significant correlations with other assets that were just shy of getting into the top by a small margin on many windows. One way this may manifest is that the anchor asset is flooded by its sectoral peers in its top and they get higher co-occurrence counts. This may lead to another asset that in general has higher correlation in many windows having lower co-occurrence count and hence being disregarded by our model. One way to remedy this is to use the distribution of the Pearson correlation in every window, have some non-linear function such as a square function to eliminate consistent noisy correlations from any asset that is weakly significant, and aggregate across all windows to have a final distribution which we will then use for the cookbook.
Overall, what really prompted me to read and implement this paper is just the sheer simplicity of its approach. The pre-processing and the training are nothing fancy and very intuitive to go through, and it brings in quite insightful results. This would in many ways be a naive approach to serious financial modelling, but it serves as a great foundation to build interest and may give the impetus to go deeper into such contrastive modelling approaches.