Keywords

1 Introduction

The inflation index (or consumer price index) is an indicator that characterizes changes in the general level of prices for goods and services that the population buys for personal consumption. In Ukraine, the inflation index was 5% and 10% in 2020 and 2021, respectively. At the end of 2022, the inflation rate exceeded 20%, and the Ukrainian government included an expected inflation index of 28% in the planning of the state budget for 2023 [1]. Traditional methods of protecting savings from inflation, such as bank deposits, bonds are unable to compensate for the devaluation of monetary savings of the population at such a high level of consumer price index growth.

Individuals who aim to at least preserve their existing savings are seeking alternative means to do so. One such solution is investing in securities, stocks, ETFs and other financial instruments (FIs). However, if a person lacks experience in the financial sector, there is a high risk of incorrectly composing an investment portfolio, such as failing to adhere to asset diversification rules. To assist in the composition of an investment plan for individuals without specialized skills and competences, special software tools called Robo-Advisors (RA) have been developed.

RA is a type of financial software that gives investment advice based on information (such as investment goals, risk preferences, budget, and desired investment assets) provided by a user. Unlike the classical financial consulting companies offering to compose a personalized investment portfolio for a quite high price, RA services charge a relatively small transaction fee and some of them only have fixed annual fees [2].

Technical analysis is a trading strategy that involves analyzing past market data, such as price changes and volume, to identify patterns and make predictions about future price movements. Technical analysis is widely used by traders and investors in various financial markets, including stocks, currencies, and other FIs. Technical analysis traders use various technical indicators, such as moving averages and oscillators, to identify potential buying and selling opportunities. Such indicators that calculate some numerical value based on past market data are also called computer analysis. Technical analysis as a rule is applied after fundamental analysis.

The purpose of this research is to develop an algorithm that allows using trading strategies based on computer analysis for an initial investment portfolio, to implement this algorithm in a software tool using Python programming language, and to analyze the effectiveness of this approach on real historical datasets.

Research tasks include examination on which indicators based trading strategies shows better performance versus simple buy-and-hold strategy (benchmarks strategy), providing the step-by-step algorithm for applying trading strategy not only for a single FI but also for a whole investment portfolio, and analysis of the obtained results during the experimental part of the research.

The paper is structured as follows: Sect. 2 contains a brief overview of an existed approaches of using technical analysis indicators, Sect. 3 describes the idea of using computer analysis trading strategies to enhance the profitability of an investment portfolio, Sect. 4 presents obtained practical results, the last part concludes.

2 Related Works

Algorithmic trading is a computer-based trading method that utilizes algorithms to execute trades in financial markets. Algorithmic trading uses predefined set of instructions to perform a trade [3]. This approach based on mathematical models and statistical analysis to identify trading opportunities, manage risk, and optimize trading strategies. It also allows reducing trading costs and increasing trading speed. With the rapid development of computer technology and the increasing availability of market data, algorithmic trading has become a very popular way of professional trading in recent years. The study by S. Baek et al. [4] describes the way of applying machine-learning techniques in algorithmic trading application for futures markets. Thus, algorithmic trading is a topic of interest and research in the academic and financial communities.

Technical analysis is a methodology that identifies certain patterns and trends by analyzing market data, such as price and volume, and suggests investment decisions. It based on the assumption that historical data can be used to predict future price values. Instruments for technical analysis can be divided into graphic tools (so-called charting) and indicators of technical analysis [5]. Traders which use technical analysis use charts and technical indicators to interpret market data and make trading decisions. In our research, we focused on three main indicators of technical analysis: Moving Average Convergence/Divergence (MACD), Support and Resistance (S&R), and Relative Strength Index (RSI) [6].

Ha et al. [7] proposed an optimal intraday trading algorithm to reduce overall transaction costs by absorbing price shocks when an online portfolio selection method rebalances its portfolio. The proposed trading algorithm optimizes the number of intraday trades and finds an optimal intraday trading path. Backtesting results from the historical data of NASDAQ-traded stocks show that the proposed trading algorithm significantly reduces the overall transaction costs when market liquidity is limited [7]. Intraday trading algorithm is applicable to portfolio rebalancing strategy.

Algorithmic trading is the computerized execution of FIs following pre-specified rules and guidelines. The proposed algorithm is much effective for large capital investment, it generates more benefit for more frequent rebalance, the lower transaction fees rate is, the more benefit [7].

Dai et al. [8] addresses the problem of the instability of forecasting stock price investment and the difficulty in determining investment proportion by proposing the trend peak price tracing which sets adjustable historical window width. It uses slope value to judge prediction direction to track price change, which uses Markowitz’s mean-variance theory and Kelly’s capital growth theory by the means of exponential MA and peak equal weight slope value. Online portfolio strategy using learning algorithm demonstrate advantages in balancing risk and return [8]. Asset allocation in a portfolio is the core issue that people are concerned about.

Bisht et al. [9] presents an integrated approach of portfolio construction based on sector analysis for investment in National Stock Exchange of India combining different evidences, such as Average directional index (ADX), Relative strength indicator (RSI), Simple moving average (SMA), Sector’s relative strength (SRS) with different moving window. For optimizing of the constructed portfolio, an optimization function is constructed for minimum volatility, maximum Sharpe ratio, or maximum return under tolerable risk and simulated using a deep recurrent neural network, which is based on industry’s performance [9]. Behavioral portfolio can demonstrate better results than Markowitz’s model, when prevailing assumptions of overconfidence, gambler’s fallacy, illusion of validity etc. [10].

Advancements in machine learning have revealed a wide range of new opportunities for using advanced computer algorithms, such as reinforcement learning in portfolio risk management. Ngo et al. [11] show superior performance of reinforcement learning models over traditional optimization models following the mean-variance framework in different financial market (e.g., ETFs) settings while optimizing the Sharpe ratio even for similar degree of investment portfolio diversification.

In our previous research [12] we have described the algorithm of generating next month’s Close price prediction using Long Short-Term Memory neural network and proved that investment portfolio built using not only historical data but also a one-month prediction shows better results even during global stock market recession. We evaluated portfolio performance using simple buy-and-hold strategy. The aim of our current research is to expand that study and to propose an algorithm which applies trading strategy based on indicators of technical analysis for investment portfolio that includes more than one FI in contrast of existing researches.

3 Research Methodology

3.1 Model

The main objective of our research is to compare the profitability of investment portfolios that will change the distribution shares of FIs in accordance with buy or sell signals of some technical analysis indicator comparing to a simple buy-and-hold strategy. We used three technical analysis indicators: Moving Average Convergence/Divergence (MACD), Support and Resistance (S&R), and Relative Strength Index (RSI). All three indicators are based on price values for a certain time period in the past, but use different algorithms to calculate their numerical values.

Simple Moving Average (SMA) is a set of numeric values calculated by the arithmetic mean of a certain amount of previous price values (periods). We can use different numbers of periods that used to calculate current SMA value. When SMA values based on different periods diverge, it is called MA convergence or divergence. The periods for calculating SMA are divided into short-term and long-term. We used two SMA values to calculate MACD buy or sell signal. MACD strategy gives buy signal if 5-day SMA value is greater than 12-day SMA value and sell signal otherwise. The 5-day SMA reflects the short-term trend of price movement. Comparing the 5-day SMA to the 12-day SMA allows getting an early signal of a price trend change.

The Relative Strength Index (RSI) is used in financial analysis to measure the momentum of an asset’s price movement developed by Wilder [13]. The RSI value is calculated by comparing the magnitude of an asset’s recent price gains to its recent price losses for some previous timesteps number and oscillates between 0 and 100. The formal notation for calculating RSI signal is:

$$ RSI\left( t \right) = 100 - \frac{100}{{1 + RS\left( t \right)}} $$
(1)

where t is previous timesteps number, and Relative Strength (RS(t)) is determined by dividing the average gain by the average loss for a given period. When the RSI of some FI reaches the value 70 and above there are a high probability that the price will come down soon. When the RSI value is 30 or less it is considered as a buy signal (Fig. 1).

Another technical analysis approach is Support and Resistance strategy (S&R), which consists of identifying key price levels where price action is likely to reverse in the opposite direction. These levels are referred to as support (when the price does not drop below some key level) and resistance (when the price does not rise above the key level) ones. The support and resistance levels can be identified through the use of various technical analysis tools such as trend lines, extremum values, moving averages, and Fibonacci retracements. In the research, we used S&R signals based on the determination of impulse price changes after a long-term consolidation.

Fig. 1.
figure 1

RSI overbought and oversold signals on EUR/USD chart.

The initial condition of the developed algorithm, which is described below, is a previously formed investment portfolio. In our previous work [12], we described a method of building an initial investment portfolio that takes into account the investor’s desire to minimize acceptable risk or maximize expected return using the Markowitz portfolio model. The basic investment portfolio was built for a risk-neutral investor, when the ratio of risk to expected return is minimized (2), and includes twelve stocks. Here N is a number of assets, Rp is an expected return of the portfolio, σp is a level of risk (standard deviation), and wi is a percentage of asset i in portfolio p [12].

$$ \left\{ {\begin{array}{*{20}c} {\frac{{\sigma_{p} }}{{R_{p} }} \to min} \\ {w_{1} + w_{2} + \ldots + w_{N} = 1} \\ {w_{i} \ge 0} \\ \end{array} } \right. $$
(2)

The algorithm for using technical analysis indicators for an investment portfolio consisting of several FIs is presented in Fig. 2.

Let us consider the algorithm presented above in more detail. The first step is to form an initial investment portfolio based on data on past price movements of FIs. To do this, we use the Markowitz method of investment portfolio formation. If the starting point of our experiment is, for example, January 2021, we will use data from the previous five years, i.e. from January 2016 to December 2020. After the initial portfolio is formed, we buy FIs according to their share in the portfolio at the opening price of 2021.

The experiment compares 4 portfolios. The first corresponds to the Buy-and-hold strategy. This means that the proportion of FIs in its allocation does not change. The other three portfolios can be rebalanced if buy or sell signals are received from the MACD, RSI, or S&R indicators. The task of the experiment is to study the dynamics of changes in the value of each portfolio over a period of one year.

Fig. 2.
figure 2

The algorithm workflow.

The algorithm used to rebalance the portfolios is universal for all three indicators. The check and rebalancing is performed at the end of each week and consists of the following steps (Table 1):

Table 1. Rebalane portfolios algorithm.

Since we know the entire history of changes in the proportions of FIs in the portfolio and the history of price changes of each instrument, we can calculate the estimated value of the portfolio at each point in time, for example, at the end of each month. We can also calculate the maximum and minimum values of the portfolio over time to further compare portfolios that have used different rebalancing strategies or that have used a buy-and-hold strategy.

3.2 Experimental Part

Listings 1–3 demonstrate some parts of the implementation of the algorithm described in Sect. 3.1. The full code of the experimental part can be found at https://github.com/serhii1savchenko/portfolio-strategies. To develop the experimental part, we used the Python, the Anaconda development platform, and the open-source libraries numpy, pandas, matplotlib, pypfopt, and yfinance.

For the practical experiments in this research, a selection of 12 stocks was made. This set includes stocks of companies from various sectors of the economy, such as high technology companies (Apple Inc., Alphabet Inc., Microsoft Corporation, Amazon.com, Inc.), microelectronics firms (Intel Corporation, Advanced Micro Devices, Inc., NVIDIA Corporation), engineering companies (Ford Motor Company, Tesla, Inc.), and financial institutions (JPMorgan Chase & Co, Morgan Stanley, Vanguard 500 Index Fund), which contributes to a well-diversified investment portfolio. The five-year dataset range allows us to take into account medium- and long-term trends in the price of FIs. Historical price data for all the listed companies can be sourced from the publicly available Yahoo Finance service [14]. The first step involves calculating the initial investment portfolio using historical daily closing price data. Once the initial portfolio is formed according to the classical Markowitz model [15] using the pypfopt library, we need to purchase shares according to the weights calculated in the portfolio. The initial balance in the experiment is $100,000.

Next, we calculate the values of the MACD, RSI, and S&R indicators for each FI. A value of −1 corresponds to a sell signal, 1 corresponds to a buy signal, and 0 means no signal. For the RSI oscillator, a value of 70 or higher is perceived as a sell signal, while a value of 30 or lower is perceived as a buy signal.

figure a

It is also necessary to define auxiliary functions that are used to select one FI for sale and one FI for purchase in case a sell or buy signal is received for several FIs at the same time. The check_tickers_for_sell function is used to filter the stocks for which a sell signal has been received. To do this, the investment portfolio is calculated based on the data for the last 5 years (the same period as used to build the initial portfolio). A FI is checked if the share of this FI in the new portfolio is less than its share in the current portfolio. The share to be sold is calculated as the percentage by which the share in the new portfolio is less than the share in the current portfolio (Listing 1). Among the instruments that have passed the check, the one that will give the highest profit from the sale of the corresponding share is selected (Listing 2).

Among the FIs for which a buy signal has been received, the one with the highest percentage of price increase or the lowest percentage of price decrease over the past 5 years is selected (Listing 3).

figure b
figure c

After completing all portfolio rebalancing, the final version of the investment portfolio will be obtained, which takes into account all changes in the distribution of shares of FIs. A comparison of the results obtained by using the MACD, RSI, and S&R strategies relative to the basic buy-and-hold strategy is presented in Sect. 4.

4 Results

Table 2 shows a comparison of the dynamics of changes in the value of the four portfolios in 2021. In the first portfolio, the shares of FIs did not change throughout the entire period. The other portfolios used a weekly rebalancing strategy in accordance with the signals of the certain indicator (MACD, RSI or S&R).

Table 2. Portfolios value changes (2021).

Table 3 shows the minimum and maximum value of each portfolio and compares the maximum and final difference in the portfolio value relative to the portfolio in which the distribution of FIs did not change (buy-and-hold portfolio without rebalancing).

Table 3. Comparison of rebalancing strategies (2021).

According to the results of the experiment, the strategy based on the S&R indicator signals showed the best performance (winner strategy). The final value of the portfolio that was rebalanced based on S&R signals was $10059.51 more than the value of the buy-and-hold portfolio. The final value of the portfolio that used RSI signals for rebalancing is almost the same as the value of the buy-and-hold portfolio. The worst result was obtained by the portfolio that used MACD signals for rebalancing, its final value is $9057.77 less than the buy-and-hold portfolio. A comparison of the dynamics of changes in the value of buy-and-hold, S&R, and other portfolios is shown in Fig. 3.

Fig. 3.
figure 3

Comparison of portfolios value throughout 2021.

An experiment was also conducted using data for 2022. Results demonstrate a comparison of the dynamics of changes in the value of the four portfolios during 2022 (the first portfolio was not rebalanced, the other three used a certain indicator to initiate rebalancing). Table 4 shows the minimum and maximum portfolio values and a comparison of the maximum and final difference in portfolio value relative to the portfolio in which the distribution of shares of FIs did not change.

Table 4. Comparison of rebalancing strategies (2022).

According to the results of the experiment on the data on changes in the prices of FIs for 2022, the best final result was also shown by the portfolio that used the S&R indicator signals for weekly rebalancing. Its final value is $3226.44 higher than the buy-and-hold portfolio.

Unforeseen events, such as wars or natural disasters, have notable impact on macroeconomic indicators, often resulting in a collapse of prices across various FIs. However, it is crucial to recognize that investments in FIs typically target long-term growth, necessitating a broader examination of the overall dynamics of changes in their values over extended periods. For instance, the S&P 500 index graph over the past 15 years illustrates a consistent upward trend, outpacing the average inflation rate. Even during the challenging times of the COVID-19 pandemic in 2020, it took 27 weeks (from 10th February to 17th August) for the index’s price to recover. Subsequently, the index demonstrated steady growth and reached an all-time high in late 2021. Presently, the following recession, which endured throughout 2022, displays signs of concluding, marking the beginning of a new period of growth.

The proposed algorithm for rebalancing the investment portfolio reduces the risk of a significant drawdown in the portfolio value when the value of certain FIs decreases. Experiments based on the price data for selected FIs for 2021 and 2022 show that the rebalancing algorithm performs better with the S&R and RSI indicators.

5 Conclusions

Thus, the paper provides a brief overview of technical analysis tools used by traders to maximize profits from buying and selling FIs. The advantage of such approaches lies in their high interpretability and adaptability to different types of FIs. The paper also presents a new algorithm that allows using technical analysis indicator signals to rebalance investment portfolios using different strategies. We also proposed enhanced criteria for selecting FIs for making buy and sell decisions. During the experimental part of the research, we developed a software application to test hypotheses on real historical data. The experimental part of the study confirmed the feasibility of using buy and sell signals from RSI and S&R indicators for periodic rebalancing of the investment portfolio.

In our further research, we are going to consider more technical analysis indicators, such as Commodity Channel Index, Weighted Moving Average, volume-based indicators and others and to investigate the dependence of the effectiveness of using a certain indicator depending on the type of FI (shares, precious metals and raw materials, cryptocurrency, etc.).