<figure><img src="image_1.png" /></figure>

HAL
open science

# Stock Trade Recommendations Using Knowledge Graph

Rahul Sonar, Sumitra Menaria, Shaleen Shukla

► To cite this version:

Rahul Sonar, Sumitra Menaria, Shaleen Shukla. Stock Trade Recommendations Using Knowledge Graph. 6th International Conference on Computational Intelligence in Data Science (ICCIDS), Feb 2023, Chennai, India. pp.168-177, 10.1007/978-3-031-38296-3_13. hal-05466048

HAL Id: hal-05466048

https://inria.hal.science/hal-05466048v1

Submitted on 19 Jan 2026

HAL is a multi-disciplinary open access
archive for the deposit and dissemination of sci-
entific research documents, whether they are pub-
lished or not. The documents may come from
teaching and research institutions in France or
abroad, or from public or private research centers.

L'archive ouverte pluridisciplinaire HAL, est
destinée au dépôt et à la diffusion de documents
scientifiques de niveau recherche, publiés ou non,
émanant des établissements d'enseignement et de
recherche français ou étrangers, des laboratoires
publics ou privés.

<figure><img src="image_2.png" /></figure>

Distributed under a Creative Commons CC BY 4.0 - Attribution - International License
<figure><img src="image_3.png" /></figure>

ifip

International Federation for Information Processing

This document is the original author manuscript of a paper submitted to an IFIP
conference proceedings or other IFIP publication by Springer Nature. As such, there
may be some differences in the official published version of the paper. Such
differences, if any, are usually due to reformatting during preparation for publication or
minor corrections made by the author(s) during final proofreading of the publication
manuscript.
<figure><img src="image_4.png" /></figure>

# Stock Trade Recommendations Using Knowledge Graph

Rahul Sonar✉️, Sumitra Menaria, and Shaleen Shukla

Parul Institute of Engineering and Technology, Vadodara, India
rahulsonar1318@gmail.com

**Abstract.** The ability to generate wealth from stocks requires two key decisions: buying and selling at the right time. When it comes to investing, deciding when to buy and sell a stock is often challenging. Executing both of these decisions correctly, investors consider various factors. Much of the current research focuses on the historical stock price that influences future stock prices. Although individual historical characteristic is important, other factors also affect stock prices. To capture such internal relations and influence, we used multiple parameters as input. This research paper proposes a knowledge graph (KG) approach for generating stock trade recommendations. We use a combination of historical data, technical data, fundamental data, and market sentiments to build a KG that captures the relationships between stocks for recommendations. To evaluate the effectiveness of our KG approach, we conduct experiments on a real-time stock market dataset. We compare the performance of our approach to a baseline system that uses only traditional machine learning techniques. Our results show that our KG approach outperforms the baseline system in terms of accuracy, and profitability. We found that our approach generates more profitable trades than the baseline system, indicating its potential for practical use in stock trading applications. Overall, our research demonstrates the potential of KG techniques for generating accurate and profitable stock trade recommendations. We believe that our approach can contribute to the development of more effective and reliable stock trading systems that can help investors make informed decisions.

**Keywords:** Knowledge Graph · Relational Recommendation · Stock Exchange

## 1 Introduction

Stock trading is a complex and dynamic process that involves making informed decisions based on various factors such as stock prices, market trends, financial statements, and news articles. With the advent of big data and artificial intelligence, many researchers have explored the use of machine learning techniques to generate stock trade recommendations. However, these approaches have limitations in capturing the complex relationships and patterns among different stocks, which can result in suboptimal recommendations.
Knowledge graphs are a potent tool that has recently gained popularity for represent-
ing complex knowledge and relationships between entities. KGs enable the integration
of multiple data, including organized and unorganized data, and provide a powerful
framework for reasoning and generating new insights [1].

A knowledge graph is a type of graph database that represents information as a network of interconnected nodes, where each node represents an entity (h, t), and each edge represents a relationship (r₁, r₂, r₃) between entities shown in Fig. 1. The graph provides a structured and interconnected way to store and retrieve information and enables the capture of both explicit and implicit relationships between entities.

<figure><img src="image_5.png" /><figcaption>Fig. 1. Knowledge Graph Representation</figcaption></figure>

In this research, we suggest a KG approach for generating stock trade recommen-
dations. Our approach leverages a combination of historical data, technical data, fun-
damental data, market sentiments, and graph structures to build a KG that captures the
complex relationships between stocks. We use the KG to generate recommendations
based on the stock's fundamental patterns, market indicators, and sentiment analysis.

Our research aims to evaluate the effectiveness of KG techniques for generating stock trade recommendations. We conduct experiments on a real-time stock market dataset and compare the performance of our approach to a baseline system that uses only traditional machine learning techniques. We evaluate our approach in terms of accuracy, and profitability.

## 2 Related Work

Over the years, researchers have explored various machine learning and data mining techniques for generating stock trade recommendations. These approaches range from simple rule-based systems to more complex deep learning models.

The approaches that have gained popularity using methods for supervised learning include support vector machines (SVM), decision trees, and neural networks to learn patterns from historical data and generate stock trade recommendations. For example, Fan et al. (2017) used SVMs to predict stock prices and generate trading signals [2]. Hu et al. (2018) proposed a decision tree-based approach to generate stock trade recommendations [3]. Other studies have explored the use of unsupervised learning techniques such as clustering and association rule mining for stock trade recommendations. For instance,
Wu and Wu (2019) proposed a clustering-based approach to generate stock trade recommendations based on stock similarity [4]. Ye et al. (2017) used association rule mining to identify patterns in historical data and generate recommendations [5]. More recently, algorithms for deep learning including convolutional neural network (CNN) and recurrent neural network (RNN) have been utilized to stock trade recommendations. For example, Liu et al. (2020) proposed a CNN-based approach to predict stock prices and generate trading signals [6].

While these studies demonstrate the potential of machine learning techniques in generating stock trade recommendations, they have limitations in capturing the complex relationships between different stocks, sectors, and industries. The interest in knowledge graphs has increased recently for stock trade recommendations, as KGs can capture and integrate multiple information sources, including both organized and unstructured data.

In recent years, several studies have focused on developing KG-based approaches for generating stock trade recommendations. For example, Zhang et al. (2020) proposed a financial knowledge graph for stock selection and demonstrated its effectiveness in generating profitable trades [7]. Huang et al. (2020) used a KG to model the relationships between stocks, sectors, and industries and used this model to generate recommendations [8]. Li et al. (2018) developed a KG-based framework for news-based stock price prediction [9]. While these studies demonstrate the potential of KGs in stock trading, there is still a need for further research to evaluate the effectiveness of KGs in generating stock trade recommendations. In particular, there is a need for studies that compare KG-based approaches to traditional machine learning techniques and assess how accurate they are at performing precision, recall, and profitability.

In this research, we aimed to address this gap by proposing a KG-based approach for generating stock trade recommendations and evaluating its effectiveness using a real-time stock market dataset with multiple quality parameters. We believe that our study can contribute to the development of more effective and reliable stock trading systems.

# 3 Methodology

In this, we proposed a knowledge graph approach for generating stock trade recommendations and compare it with various models as below:

## 3.1 Model Selection

The selection of the Knowledge Graph model for Stock Trade Recommendations has several benefits.

First, the stock market is a complex and dynamic environment with multiple inter-dependent factors and entities. The Knowledge Graph model can capture and represent this complexity by modeling the relationships between historical, technical, fundamental, sentiment, and other relevant entities. This helps to identify patterns and trends in the data that may not be apparent using traditional numerical data analysis. Second, the Knowledge Graph model can integrate multiple sources of data, including financial statements, news articles, and social media, into a unified and structured format [10]. This enables the use of a wide range of information sources in generating trade recommendations.
recommendations, leading to more informed and accurate recommendations. Third, the Knowledge Graph model is a flexible and adaptable approach that can be easily updated and refined with new data sources and changing market conditions [11]. This enables the system to continuously learn and improve over time, leading to more accurate and relevant trade recommendations. Fourth, the Knowledge Graph model is easily interpretable [12], allowing traders to understand the underlying reasons for a particular trade recommendation. This can increase their confidence in the system and allow them to decide more intelligently.

In summary, the Knowledge Graph model provides a powerful and flexible approach to Stock Trade Recommendations, allowing for the integration of multiple sources of data and the modeling of complex relationships between different entities. This can lead to more informed and accurate trade recommendations, ultimately resulting in improved trading performance.

## 3.2 Data Collection

The four types of data have been used such as stocks' historical price, news, financial, and technical data.

**Real-Time Data Acquisition.** To collect real-time stock data for this research, the Application Programming Interface (API) of Yahoo Finance was used in Python 3.10. The dataset includes trade volume, highest and lowest prices, and starting and closing prices for each day. Figure 2 shows the plotting of stock price to time.

<figure><img src="image_6.png" /><figcaption>Fig. 2. Plotting of stock's historical data</figcaption></figure>

**News Data Acquisition.** To assess the public sentiment trends towards specific company stocks, this research paper collected real-world financial news headlines of the current day. To collect current-day news data, NewsAPI was used to obtain financial headlines. This approach can provide more up-to-date information on public sentiment towards specific companies and their stocks, which can be useful for making timely and informed trading decisions. The resulting dataset was used to perform sentiment
analysis, which was then used to inform the stock trade recommendations generated by the Knowledge Graph model.

**Fundamental Data Acquisition.** In addition to historical stock price data and news headlines, another important source of data for stock trade recommendations is a company's fundamental data. This includes financial metrics such as revenue, earnings, and assets, as well as non-financial metrics such as employee count and industry sector.

To obtain this data, this research paper utilizes the Yahoo Finance API. The API provides access to a wide range of financial information, such as cash flow statements, income statements, and balance sheets. By querying the API for data on specific companies, we were able to collect a comprehensive set of fundamental data for use in their knowledge graph.

**Technical Data Acquisition.** Technical analysis is another important parameter to stock trade recommendations. Technical analysis involves studying past market data, primarily price and volume, to identify patterns and make predictions about future price movements. To acquire this data, we calculated the technical indicator. Such as moving average convergence divergence (MACD), and William %R. The MACD is a widely used technical indicator that calculates the average stock's cost beyond a specific threshold time. For this study, we calculated each moving average of a stock's 20-day and 50-day periods using Eq. (1). The William %R is an indication of momentum that measures the oversold or overbought conditions of a stock. It ranges from -100 to 0 and is calculated based on the highest high and lowest low of a stock over a certain period. We calculated the 14-day William %R for each stock by using Eq. (2).

For MACD:

$$ 
\begin{aligned}
\text{MACD Line} &= \text{20-day Exponential Moving Average} - \text{50-day Exponential Moving Average} \\
\text{Signal Line} &= \text{9-day Exponential Moving Average of MACD Line}
\end{aligned}
\qquad (1) $$

For Williams %R:

$$ \frac{\text{Highest High} - \text{Close}}{\text{Highest High} - \text{Lowest Low}} \times (-100) \qquad (2) $$

## 3.3 Data Preparation

**Sentiment Analysis.** After acquiring the data, sentiment analysis was performed on each news headline to ascertain the text's emotional tone. This sentiment was used as a feature for the knowledge graph, which can help in identifying correlations between sentiment and other factors related to the stock market.

To perform sentiment analysis, the news headlines were preprocessed. Which involved tasks such as tokenization, stop-word removal, and special characters. After preprocessing, sentiment analysis was performed using a pre-trained transformer model of natural language processing. Figure 3 indicates result of sentiment analysis of news headlines.
<table><caption>**Fig. 3.** Sentiment analysis and labeling of news headlines.</caption><thead><tr><th></th><th>news</th><th>label</th><th>score</th></tr></thead><tbody><tr><td>Adani halts $847mn acquisition of coal-fired p...</td><td></td><td>0</td><td>0.999018</td></tr><tr><td>Adani Power Said to Scrap $850 Million Coal Pl...</td><td></td><td>0</td><td>0.999165</td></tr><tr><td>Tesla beats BMW as top luxury brand in the U.S...</td><td></td><td>1</td><td>0.999121</td></tr></tbody></table>

**Technical Feature.** After calculating the technical data, the next step was to prepare the data for incorporation into the knowledge graph. This involved several tasks, including data cleaning, normalization, and feature engineering. Technical attributes which are used for the research are shown in Fig. 4.

To begin, the technical data was cleaned to remove any missing or erroneous values.

Once the data was cleaned and normalized, we performed feature engineering to create new variables that was used in the knowledge graph by concatenating features of MACD and William %R.

<table><caption>**Fig. 4.** Stock's technical features</caption><thead><tr><th>wr_14</th><th>macd</th><th>macd_signal</th><th>wr_macd_signal</th></tr></thead><tbody><tr><td>607.169983</td><td>-1.973328</td><td>2.727408</td><td>0.545482</td></tr><tr><td>588.219971</td><td>-20.244698</td><td>3.321502</td><td>1.100686</td></tr><tr><td>602.549988</td><td>-9.683849</td><td>4.892244</td><td>1.858997</td></tr><tr><td>597.909973</td><td>-14.518458</td><td>5.696986</td><td>2.626595</td></tr></tbody></table>

**Fundamental Feature.** Once the fundamental data was collected, it was also subjected to cleaning and normalization to remove any missing or erroneous values and ensure that all values were on a comparable scale. We then performed feature engineering to create new variables that were used in the knowledge graph, such as revenue, and earnings shown in Fig. 5.

<table><caption>**Fig. 5.** Stock's fundamental features</caption><thead><tr><th></th><th>Revenue</th><th>Earnings</th></tr></thead><tbody><tr><td><strong>Year</strong></td><td></td><td></td></tr><tr><td><strong>2019</strong></td><td>425089000000</td><td>32190400000</td></tr><tr><td><strong>2020</strong></td><td>540701200000</td><td>33691300000</td></tr><tr><td><strong>2021</strong></td><td>602494400000</td><td>44704600000</td></tr><tr><td><strong>2022</strong></td><td>671366700000</td><td>45567700000</td></tr></tbody></table>
## 3.4 Model Construction

The proposed model for stock trade recommendations using a knowledge graph involves a series of steps shown in Fig. 6, starting with the collection and preparation of technical and fundamental data, as well as live news headlines for sentiment analysis. The prepared data is then fed into the model, which involves several stages, including featurization, embedding, knowledge graph construction, and recommendation.

Featurization involves converting raw data into numerical features that can be used as input for the model. For technical data, this involves calculating various indicators such as moving averages, and William %R. For fundamental data, this involves extracting financial metrics such as EPS, P/E ratio, and revenue. For live news headlines, sentiment analysis is performed to classify the news as positive, negative, or neutral.

In the embedding step, we transform the feature data into high-dimensional vector representations using techniques such as GloVe. These embeddings capture the underlying semantic relationships between the features and allow us to construct a knowledge graph that represents the relationships between different stocks and their features.

The knowledge graph construction step involves building a graph where nodes represent stocks and edges represent the relationships between them. These relationships include correlations between stock prices, similarities in technical and fundamental features, and sentiment factors. We use graph databases such as Neo4j to store and query the knowledge graph.

Finally, the recommendation engine generates a list of recommended trades based on the user's input and the knowledge graph. The model is evaluated using metrics such as profit and loss (P&L) to determine its accuracy and effectiveness in making profitable trades. The P&L metric measures the profitability of the trades made based on the model's recommendations. By using a knowledge graph-based approach, we can leverage the rich relationships and context between different stocks to make more accurate and informed trade recommendations.

<figure><img src="image_7.png" /><figcaption>Fig. 6. Flowchart Diagram of the Proposed Method</figcaption></figure>
## 4 Experiment and Result Analysis

The proposed model was evaluated using a real-time stock market dataset consisting of the daily price and volume data of 7 companies from January 2018 to January 2023. The data was collected from Yahoo Finance API and preprocessed to generate technical and fundamental features for each company. Also, sentiment analysis was performed on each news headline.

To assess the effectiveness of the model, several experiments were conducted using different combinations of technical, fundamental, and news features as input to the knowledge graph. As part of the experimentation, the proposed model was evaluated using the profit and loss metric. The Eq. (3) for calculating the average profit of a stock trade is:

$$ \text{Average Profit } \% = (\text{Total Profit or Loss}/\text{Total Cost}) \times 100/\text{Number of Trades} \quad (3) $$

To calculate the average profit % of a stock trade, the total profit or loss generated by the model over a testing period was gathered. Then we determined the total cost of the trades executed during the same period. Finally, we divided the product of the first two calculations by the number of trades executed during the same period and multiply by 100. The results of these experiments are shown in Fig. 7.

<table><caption>**Fig. 7.** Experiment results from stocks using a combination of parameters.</caption><thead><tr><th rowspan="2">Stocks</th><th colspan="2">Three parameters</th><th colspan="2">News</th><th colspan="2">Fundamental</th><th colspan="2">Technical</th></tr><tr><th>Short Term</th><th>Long Term</th><th>Short Term</th><th>Long Term</th><th>Short Term</th><th>Long Term</th><th>Short Term</th><th>Long Term</th></tr></thead><tbody><tr><td>BAJAJFINSV</td><td>2.324</td><td>4.823</td><td>-0.268</td><td>0.754</td><td>1.832</td><td>3.033</td><td>3.161</td><td>3.848</td></tr><tr><td>BERGEPAINT</td><td>1.783</td><td>2.473</td><td>0.785</td><td>-0.168</td><td>1.721</td><td>2.291</td><td>2.171</td><td>2.631</td></tr><tr><td>SBIN</td><td>3.678</td><td>4.327</td><td>1.204</td><td>1.435</td><td>0.245</td><td>1.738</td><td>2.267</td><td>2.314</td></tr><tr><td>INFY</td><td>3.056</td><td>3.473</td><td>-1.159</td><td>-0.893</td><td>0.806</td><td>1.602</td><td>2.495</td><td>3.098</td></tr><tr><td>ADANIENT</td><td>2.424</td><td>1.161</td><td>0.452</td><td>-2.603</td><td>-0.271</td><td>1.202</td><td>1.122</td><td>3.152</td></tr><tr><td>ASIANPAINT</td><td>1.985</td><td>2.673</td><td>-0.935</td><td>0.481</td><td>1.446</td><td>2.257</td><td>1.768</td><td>2.789</td></tr><tr><td>TCS</td><td>3.315</td><td>4.541</td><td>-1.301</td><td>1.038</td><td>-0.753</td><td>1.138</td><td>2.739</td><td>3.426</td></tr></tbody></table>

The model was trained and tested on a dataset of historical daily stock data, technical indicators, fundamental data, and sentiment analysis derived from news headlines. The model was evaluated on the ability to predict profitable trades, and the results showed that the proposed model achieved an average return of 4.8% in the testing period. Which outperformed the benchmark return of 2.8%. The model-generated trade signals respected to time and price change, are shown in Fig. 8.

Additionally, the model was compared with other models to determine its superiority in making profitable trades. The comparison is shown in Table 1. The results showed that the proposed knowledge graph model surpassed the other models regarding the profit and loss metric. Specifically, the model achieved a higher profit and lower loss compared to the baseline models. When compared with similar models, the CNN and RNN-based models achieved competitive performance. While the model outperformed the SVM-based model in terms of profit, the model achieved a lower loss. The RNN-based model achieved similar performance to the CNN-based model.

Overall, the experiment results prove the viability of the suggested knowledge graph model in making profitable trades, and its potential to be used in real-world stock trade recommendations.
<figure><img src="image_8.png" /><figcaption>Fig. 8. Plotting of trade signals</figcaption></figure>

<table><caption>**Table 1.** Average returns of various models on parameters</caption><thead><tr><td>Models</td><td>Parameters</td><td>Average Return</td></tr></thead><tbody><tr><td>Proposed</td><td>Real-time market data, fundamental, technical, and news headlines</td><td>4.8</td></tr><tr><td>SVM [1]</td><td>Market data, technical indicators, Wikipedia traffic, Google news counts, and generated features</td><td>1.5</td></tr><tr><td>CNN [5]</td><td>Historical stock data</td><td>2.5</td></tr><tr><td>RNN [7]</td><td>Time series data</td><td>2.8</td></tr></tbody></table>

# 5 Conclusion

In this study, we presented a new strategy for making stock trade recommendations by leveraging multiple quality factors and knowledge graphs. We collected historical daily stock data, fundamental and technical data, as well as news headlines related to the companies of interest. We then preprocessed and featured the data before embedding it into a knowledge graph. The resulting knowledge graph was used to make stock trade recommendations, which were evaluated using metrics such as average returns. Our experimental results demonstrated that the proposed approach achieved higher accuracy and outperformed several baseline methods. In particular, the average returns of the recommended trades using our approach were significantly higher than those of the other methods. These results suggest that the chosen factors and knowledge graphs have great potential for improving the accuracy and effectiveness of stock trade recommendations. It could be further extended to incorporate more sources of data and to improve the model's ability to adapt to changing market conditions.

# References

1. Chen, H., Zhang, H., Ding, Y., Zhou, X., Chen, L., Yang, J.: A survey on knowledge graph-based recommender systems. IEEE Trans. Knowl. Data Eng. 32(12), 2258–2279 (2020)

2. Fan, S., Chen, Y., Jiang, J.: A stock price prediction and trading strategy using SVM regression. In: 2017 2nd International Conference on Cloud Computing and Big Data Analysis (ICCCBDA), pp. 279–283. IEEE (2017)

3. Hu, Y., Zhang, Y., Li, X., Chen, X.: A decision tree-based approach to generating stock trading recommendations. J. Intell. Fuzzy Syst. 34(6), 3761–3768 (2018)
4. Wu, Q., Wu, W.: A clustering-based approach to generating stock trade recommendations. In: 2019 IEEE 5th International Conference on Computer and Communications (ICCC), pp. 2242–2247. IEEE (2019)

5. Ye, Y., Liu, C., Huang, H., Su, J.: Association rule mining-based stock trade recommendations. In: 2017 International Conference on Industrial Informatics and Computer Engineering (CIIC), pp. 81–85. IEEE (2017)

6. Liu, Y., Liu, Q., Zhang, X., Xu, Y., Wang, J.: Deep convolutional neural networks for stock price prediction using technical indicators. IEEE Access 8, 133918–133931 (2020)

7. Zhang, Y., Cao, L., Qian, Z.: Financial knowledge graph-based stock selection. J. Intell. Fuzzy Syst. 38(4), 4373–4381 (2020)

8. Huang, L., Li, J., Yang, Y., Gao, H.: Stock recommendation system based on sector and industry correlation. In: Complexity, vol. 2020 (2020)

9. Li, H., Yu, X., Wu, C.: News-based stock price prediction using knowledge graph embedding. In: Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing, pp. 3474–3479 (2018)

10. Li, K., Li, W., Li, W., Li, X.: A hybrid model for stock price prediction using financial news and graph convolutional networks. Neural Comput. Appl. 32(15), 11255–11265 (2020)

11. Chen, H., Zhang, X., Liu, Y., Wang, T.: A review of knowledge graph-based recommender systems: research problems and future directions. Front. Comput. Sci. 14(5), 753–768 (2020)

12. Li, H., Li, B., Li, C., Cui, L., Yang, W.: Interpretable learning for knowledge graph completion based on neural networks. In: Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP), pp. 6854–6864 (2020)

13. Long, J., Chen, Z., He, W., Wu, T., Ren, J.: An integrated framework of deep learning and knowledge graph for prediction of stock price trend: an application in Chinese stock exchange market. Appl. Soft Comput. 91, 106205 (2020)

14. Liu, J., Lu, Z., Du, W.: Combining enterprise knowledge graph and news sentiment analysis for stock price prediction (2019)

15. Liu, Y., Zeng, Q., Ordieres Meré, J., Yang, H.: Anticipating stock market of the renowned companies: a knowledge graph approach. In: Complexity, vol. 2019 (2019)

16. Zhu, P., Cheng, D., Luo, S., Xu, R., Liang, Y., Luo, Y.: Leveraging enterprise knowledge graph to infer web events' influences via self-supervised learning. J. Web Semant. 74, 100722 (2022)