Beginner’s Python Financial Analysis Walk-through — Part 5

Keith Chan
Analytics Vidhya
Published in
6 min readAug 23, 2020
Image adapted from https://www.dnaindia.com/personal-finance/report-india-s-personal-wealth-to-grow-13-by-2022-2673182

“Predicting” Future Stock Movements

Boy am I glad you made it here! This section covers what I find to be the most exciting part of the entire project! At this point, if you’ve read through parts 1–4 of the project, you understand my steps to evaluate the historical performance of stocks, but the question we are all asking is “How do I predict if a stock will go up and make me rich?” This is probably why you’re here in the first place; You want to know how to choose a stock that has a higher likelihood of yielding greater returns. Let’s see how we can do this using simple moving averages and Bollinger band plots. Let’s make money!

Simple Moving Average

We begin by understanding a simple moving average (SMA). An SMA is a constantly updated average price for a certain period of time. For example, a 10 day moving average would average the first 10 closing prices for the first data point. The next data point would add the 11th closing price and drop the first day’s price, and take the new average. This process continues on a rolling basis. In effect, a moving average smooths out the day-to-day volatility and better displays the underlying trends in a stock price. A shorter time frame is less smooth, but better represents the source data.

There are many ways to plot moving averages, but for simplicity, here I use the cufflinks package to do it for me.

# The cufflinks package has useful technical analysis functionality, and we can use .ta_plot(study=’sma’) to create a Simple Moving Averages plot# User input ticker of interest
ticker = “NFLX”
each_df[ticker][‘Adj Close’].ta_plot(study=’sma’,periods=[10])
Figure 1: A 10-day simple moving average overlaid on NFLX’s closing prices

Figure 1 above illustrates a 10-day moving average for Netflix’s (NFLX) closing prices. As evident, the SMA reduces the jagged peaks and valleys of the closing prices and gives better visibility to the underlying trends. In the past 2 years, we can clearly see the stock price trending upwards.

Death Cross and Golden Cross

Building on this concept, you can compare multiple SMA’s with different time frames. When a shorter-term SMA consistently lies above a longer-term SMA, we can expect the stock price to trend upwards. There are two popular trading patterns that utilize this concept: the death cross and the golden cross. I’ll turn to Investopedia for a definition: “A death cross occurs when the 50-day SMA crosses below the 200-day SMA. This is considered a bearish signal, that further losses are in store. The golden cross occurs when a short-term SMA breaks above a long-term SMA. This can signal further gains are in store.” Source

Let’s take a look at overlaying two SMA’s onto Netflix.

# User input ticker of interest
ticker = “NFLX”
start_date = ‘2018–06–01’
end_date = ‘2020–08–01’
each_df[ticker][‘Adj Close’].loc[start_date:end_date].ta_plot(study=’sma’,periods=[50,200])
Figure 2: Example of a death cross followed by a golden cross

As we can see from Figure 2, Netflix is an interesting case study. Around August 2019 we see a death cross. I was not following Netflix’s stock price at that time, but it seems the stock had been trending downwards. I’ll leave it as an exercise for you to explain the dip. Soon after, the death cross is followed by a golden cross near February 2020. Ever since the golden cross in February, Netflix’s stock has been on the rise.

Now we know Coronavirus explains a lot of price movements around that time. As more people stayed at home, more and more people turned to Netflix as the sole source of entertainment in the house. Netflix’s paid user subscription base grew significantly in the months following. That is no surprise.

However, what’s interesting to me is that during the major economic earthquake in Feb-Mar. 2020, when the rest of the stock market was plummeting, we don’t see a death cross. Quite opposite, we actually see a golden cross! If we focus on the orange line, we see that Netflix’s stock prices also took a big hit in March 2020, so it’s not that Netflix didn’t feel the impacts of COVID. The takeaway is that the stock dip was due to a one-off event and NOT a trend, as shown by the SMA’s. If in March we had traded solely based on a comparison of 50-day and 200-day SMA’s, we would have reaped all the future gains.

Next, I’ll talk about another tool used to make predictions on stock movements.

Bollinger Band Plots

Bollinger band plots are a technical analysis tool composed of three lines, a simple moving average (SMA) and two bounding lines above and below the average. Most commonly, the bounding bands are +/- 2 standard deviations from a 20-day SMA.

One major use case for Bollinger band plots is to help understand undersold vs. oversold stocks. As a stock’s market price moves closer to the upper band, the stock is perceived to be overbought, and as the price moves closer to the lower band, the stock is more oversold. Although not recommended as the sole basis for buy/sell, price movements near the upper and lower bands can signal uncharacteristically high/low prices for stocks. The latter is what I generally look for, as I hope to buy oversold stocks for cheap and let their values rise back towards the moving average.

Bollinger bands also allow traders to monitor and take advantage of volatility shifts. As we learned previously in part 4 of this project, the standard deviation of stock prices is a measure of volatility. Therefore, the upper and lower bands expand as the stock price becomes volatile. Conversely, the bands contract as the market calms down; This is called a squeeze. Traders may take squeezes as a potential sign of trading opportunities since squeezes are often followed by increased volatility, although the direction of price movement is unknown.

Let’s plot the Bollinger bands before we go deeper so we can take a look at what I’m talking about. The cufflinks package again makes it very simple to plot Bollinger Bands as shown in Figure 3.

# User input ticker of interest
ticker = "SPY"

each_df[ticker]['Close'].ta_plot(study='boll', periods=20,boll_std=2)
Figure 3. Bollinger Band Plot for SPY from 2018–2020

During an uptrend, the prices will bounce between the upper band and the moving average. While in this uptrend, the price crossing below the moving average can be a sign of slowing growth or trend reversal. You can see this crossing in Figure 4 below. Here I plotted the Bollinger bands for the SPY for the first 4 months of 2020. See how the orange closing price line dips below the 20-day SMA around February 18. Before this, there was a steady uptrend for the SPY. Afterwards, there was a hefty downtrend.

Figure 4. Unusual SPY market prices Feb-Mar 2020

As you can see above, the period of Feb-March 2020 showed a major downtrend in the SPY. It’s unusual to see the SMA breakout below the lower band 4 times within a month. With standard deviations, 95% of the values should lie within the +/- 2 standard deviations, so we’re seeing very unusual activity. Of course, this is understandable as peak Coronavirus fears struck America in this time frame. This is a good example of what a strong downtrend looks like. In the following months, we see a strong uptrend.

Conclusion

In this section, we’ve learned how to use moving averages and Bollinger band plots to take a step back from all the noise in the erratic trading data and focus on the trends. It’s hard to profit day-trading the daily ups and downs, but it’s much simpler to profit if you can identify strong growth trends . Using these techniques, you can also identify trend reversals and buy stocks early in a trend. On a shorter time horizon, you can use Bollinger bands to find undervalued or overvalued stocks. With this analysis, you can hopefully be more informed and make data driven decisions to buy stocks. In the next and last section, we’ll wrap up everything we’ve learned.

--

--

Keith Chan
Analytics Vidhya

A curious adventure-seeker aspiring to write good code and live a full life