We can generate passive income by investing in stock markets. However, it is important to buy a stock at the right time. The right time is usually when the price of a stock is low and sell the stock when its price is high.
Having said that, it’s important to note that no one can absolutely time the market. This is because the market is dynamic in nature that is dependent on an infinite number of factors. Therefore the technical indicators are merely calculated signals with a degree of risk and should not be taken as signals with absolute certainty.
This article will demonstrate how we can perform a technical analysis of stock prices using Python code. We usually need the Open, High, Low, Close, and Volume (OHLCV) stock data but I will present three indicators that can be computed from the Close prices. I will use the Yahoo finance library to gather the required close prices of a company.
- I will first explain what technical indicators are.
2. Then I will present a handful of technical indicators and how they can be used.
3. Finally I will show how the technical indicators can be computed using the Python programming language. I will also demonstrate how we can plot them.
I will aim to keep the article simple and will only outline the three common technical indicators.
Disclaimer: This article is for learning purposes only and it should never be taken as investment advice. I highly recommend seeking an independent professional financial adviser before carrying out any investments. The author(s) do not take any responsibility for any loss. Therefore please use this article for educational purposes only. It is based on a view of the market environment, keeping in mind that the market is continuously changing. The article will be updated at any time without any notice as more information is gathered. If you spot an issue with the article then please do let me know.
If you are new to the world of trading and the stock market then I highly recommend reading this article to familiarise yourself with the basics of the trading fundamentals.
Understanding Must-Know Front Office Trading Lingo, Stock Market, Trades, Bonds, Shares, Bid-Ask Spread
To determine which companies to invest in, you can perform fundamental analysis. I have explained the concept of fundamental analysis here:
Automating Stock Investing Fundamental Analysis With Python
Explaining Stock Trading Fundamental Analysis Ratios And Retrieving Them Using Python
Fundamental analysis uses the information of a company such as its balance sheet, income statements, etc. to compute its value.
Investors usually perform due diligence on a handful of companies to select their target companies. There is no guarantee that an investor will make money and some investors lose some, if not all, of their investments hence it is wise not to invest in a company that is going to go bust or that is overvalued and its share price is already too high.
Investors usually perform fundamental analysis on a company to understand whether it is worth buying its stock. Once they have selected the chosen companies to invest their money in, they then need to evaluate when to buy the stock. Time is important in stock investing too. This is where the technical indicators can come in handy.
An investor performs technical analysis to compute technical indicators. These indicators can help an investor determine when to buy or sell a stock.
There are a large number of technical indicators available that are used by the investors. The key is to use a handful of them that meets the trading strategies of the investors and make sense for the current market situation. Too many indicators can clutter the charts and add unnecessary noise.
Usually, the technical indicators use the OHLCV data.
When we hear the term OHLCV in trading, it means the open, high, low, close, and volume of trades. These measures of a stock can be used to compute technical indicators.
The technical indicators can help us with our investment choices.
Investors use the technical indicators to time their investments. Having said that, it’s important to consider the trend of the stock prices into account of your analysis.
There is a large number of technical indicators available. The technical indicators can be grouped into Momentum Indicators, Volume Indicators, Volatility Indicators, Trend Indicators, and Others Indicators.
We will start by understanding the Moving Average Convergence Divergence (MACD) indicator. The MACD indicator is one of the most popular technical oscillator indicators.
MACD helps us understand the relationship between the moving averages. Convergent is when the lines move closer to each other and divergence is when the lines move away from each other. The lines here are the moving averages.
MACD is a trend-following momentum indicator. It can help us assess the relationship between two moving averages of prices. Subsequently, the MACD indicator can be used to compute a trading strategy that signals us when to buy or sell a stock. I will demonstrate it in this article.
Before I begin, it’s worth mentioning that a moving average is a rolling average value of a predefined historic period. As an instance, the simple 10-day moving average is computed by calculating the average of the past 10 days period. The exponential moving average, on the other hand, assigns higher importance to the recent values. It can help us capture the movements of a stock price better.
There are 3 main steps required to compute MACD:
Step 1: Calculate the MACD line:
- Calculate the 26-day exponentially weighted moving average of the price. This is the long term line.
- Calculate the 12-day exponentially weighted moving average of the price. This is the short term line.
- Calculate the difference between the 26-day EMA and 12-day EMA lines. This is the MACD line.
Step 2: Calculate the Signal line from the MACD line:
- Calculate the 9 days exponentially weighted moving average of the MACD line. This is known as the signal line.
Step 3: Compute the histogram: Distance between MACD and the Signal
- We can then calculate the difference between the MACD and the Signal line and then plot it as a histogram. The histogram can help us find when the cross-over is about to happen.
The histogram is the difference between MACD and the Signal line
The histogram’s length can be used to understand the trend better. When the histogram bars are not increasing then it can imply that the prices are not volatile and a big move might happen in the opposite direction soon.
Although the usual approach is to use the parameters as described above but it really depends on the stock, the market, and the investor. We can choose different parameters and optimize the parameters that meet our trading style and the stock we are interested in.
We can use the cross-over between MACD and the Signal line to create a simple trading strategy. This is where the MACD line and the signal line cross over each other.
- Sell Signal: The cross over: When the MACD line is below the signal line.
- Buy Signal: The cross over: When the MACD line is above the signal line
Bullish vs Bearish:
- Bearish: When the MACD and Signal lines are below 0 then the market is bearish.
- Bullish: When the MACD and Signal lines are above 0 then the market is bullish.
MACD is based on moving averages which imply that the past can impact the future. This is not always true. Additionally, there is a lag present due to the moving averages hence the generated signals are after the move has started.
The standard setting for MACD is the difference between the 12- and 26-period EMAs. We could use MACD(5,35,5) for more sensitive stocks and MACD(12,26,9) might be better suited for weekly charts. It all depends on the investor.
One keynote to remember is to always analyze the short and long-term price trend along with other factors. And rememeber sometimes a stock that might appear overbought might still move upwards due to other market factors.
We are going to analyze RSI now. RSI stands for Relative Strength Index. It’s a widely used technical indicator and this is mainly due to its simplicity. It relies on the market and we can use the indicator to determine when to buy or sell a stock.
RSI requires us to compute the recent gains and losses. The recent specified time period is subjective in nature. We use the RSI indicator to measure the speed and change of price movements.
RSI is an oscillating indicator. It can help us understand the momentum better. Note, momentum is the change of price and size. Therefore, the RSI indicator can help us understand when the stock price will change its trend.
The key to using this indicator is to understand whether a stock is overbought or oversold.
The calculation is extremely simple.
- Firstly, we have to determine the time period. Usually, a 14 day time period is chosen but it could depend on the investor’s own view of the market and the stock.
- Secondly, we have to compute the relative strength which is known as RS. RS is the average gain over the average loss. To explain it further, RS is the average gain when the price was moving up over the average loss when the price change was negative.
- Calculate RSI as 100 — (100/(1+RS))
The RSI value is between 0–100
Overbought: When the RSI is above 70%. Essentially, overbought is when the price of a stock has increased quickly over a small period of time, implying that it is overbought.
The price of an overbought stock usually decreases in price.
Oversold: When the RSI is below 30%. Essentially, oversold is when the price of a stock has decreased quickly over a small period of time, implying that it is oversold. The price of an oversold stock usually increases in price.
There are way too many strategies that are dependent on the RSI indicator.
A simple strategy is to use the RSI such that:
Sell: When RSI increases above 70%
Buy: When RSI decreases below 30%.
We might decide to use different parameters. The point is that we can optimize the parameters that meet our trading style, the market and the stock we are interested in.
The signals are not always accurate. The RSI signals are dependent on the price of the stock only and this is not the only factor that can change the price of a stock. Plus it’s highly subjective.
As an instance, a company can launch a product when a stock is oversold and that could further increase the price of the stock.
Therefore, always consider the market factors and also use the short and long term price trend when buying or selling a stock.
Lastly, I wanted to outline the Bollinger bands indicator. Again, it is one of the most popular technical indicators. And this is mainly due to its simplicity.
There are two main components of a Bollinder band indicator:
- Volatility Bolinger Bands
- Moving averages
Essentially, the steps are:
- Middle band: Calculate the moving average of the price, usually 20 days moving average.
- Upper band: Calculate two standard deviations above the moving average.
- Lower band: Calculate two standard deviations below the moving average.
The more volatile the stock prices, the wider the bands from the moving average. It’s important to look at the shape/trend of the bands along with the gap between them to understand the trend and stock better.
The standard deviations capture the volatile movements and hence we compute standard deviations above and below the upper and lower bands to capture the outliers. Consequently, 95% of the price movements will fall between the two standard deviations.
A simple trading strategy could be to:
Sell: As soon as the market price touches the upper Bollinger band
Buy: As soon as the market price touches the lower Bollinger band
This is based on the assumption that the stock must fall back (from the uptrend) and eventually touch the bottom band.
At times, the Bollinger Band Indicator signals us to buy a stock but an external market event such as negative news can change the price of the stock. Therefore it’s important to use the indicator as just an indicator that can sometimes be wrong.
I recently came across a Technical Analysis library named ta
It uses the financial time series datasets (open, close, high, low, volume) and is built on the Python Pandas library.
It provides a large number of technical indicators that are grouped into Momentum Indicators, Volume Indicators, Volatility Indicators, Trend Indicators, and Others Indicators categories.
Originally Appeared Here