Why Move from Data Retrieval to Data Analysis?
Embarking on this journey into the realms of financial data analysis, I’ve come to appreciate the beauty of starting simple. Like learning to cook, I began with the basics — fetching stock data, much like fetching ingredients from a market. I’ve managed to get ahold of daily highs, lows, open, and close prices, essentially my stock market groceries. But here’s the kicker: having ingredients doesn’t make you a chef, just like having data doesn’t make you an investor. It’s all about how you use them. So, armed with my “ingredients,” I’m stepping into the financial “kitchen” to whip up something a bit more sophisticated. And let me tell you, the first recipe in our cookbook? Moving averages.
Why move from merely collecting data to analyzing it, you ask? Well, while my initial steps of gathering daily stock metrics provided a clear snapshot of market activity, it felt like watching a sports game through snapshots. You see the action but miss the flow. Moving averages, on the other hand, are like the highlight reels of the stock market, smoothing out the day-to-day volatility to show us the underlying trends. By applying these fundamental analysis tools, we start to see the forest for the trees, gaining insights into potential future movements of stock prices.
It dawned on me that this is more than a mere academic exercise; it’s a crucial step towards making informed investment decisions. After all, understanding the direction and strength of market trends could be the difference between a savvy investment and a costly gamble. So, with a dash of curiosity and a pinch of humor to keep things light, let’s dive deeper into the art of financial analysis. Who knows? This initial foray into moving averages might just be the secret sauce to our investment success.
Understanding Moving Averages
Before diving into the code, explain what moving averages are and why they’re useful. Moving averages smooth out price data over a specified period, making it easier to identify the direction of the trend. The SMA50 and SMA200 are widely used in the industry:
- SMA50 (50-Day Moving Average): Often used to gauge the medium-term trend. Rising SMA50 can indicate a positive trend, while a declining SMA50 may suggest a downtrend.
- SMA200 (200-Day Moving Average): Helps identify the long-term trend. It’s considered a significant indicator where the price in relation to SMA200 can signal bullish or bearish trends.
Explain that you chose SMA50 and SMA200 because they are standard benchmarks used by traders and analysts to assess market sentiment. A stock price above its SMA200 is typically seen as in a long-term uptrend, and vice versa. The SMA50 offers more immediate trend information, providing a bridge between short-term price fluctuations and the longer-term perspective of the SMA200.
We will pause here for a second with information on what is exactly the bullish or bearish trend?
- A bullish trend is when the market’s feeling optimistic — imagine a bull charging ahead, horns first, unstoppable in its momentum. It’s like when you’re on a winning streak in a video game, and nothing can touch you. Prices are going up, investors are smiling, and the world is a happy place. If the stock market were a party, bullish trends would be when the music’s pumping, and everyone’s dancing.
- On the flip side, we have the bearish trend. Picture a bear, hibernating or swiping down with its massive paws. This trend is the mood killer, the rain on your parade when prices are dropping, and pessimism is in the air. It’s like that moment you step on a Lego piece barefoot — sudden, painful, and decidedly unwelcome. In our stock market party, this is when someone unplugs the music, and you realize it’s time to go home.
Why SMA50 and SMA200?
We chose SMA50 and SMA200 because they are standard benchmarks used by traders and analysts to assess market sentiment. A stock price above its SMA200 is typically seen as in a long-term uptrend, and vice versa. The SMA50 offers more immediate trend information, providing a bridge between short-term price fluctuations and the longer-term perspective of the SMA200.
And let’s cooking begin - we are about to write a code to do the magic: create a new python file in your PyCharm IDE, name it and let’s roll in
Code
import yfinance as yf # Import yfinance library to fetch stock data
import matplotlib.pyplot as plt # Import matplotlib library for plotting and drawing
# Let's get a look for 1stock perspective
stock = yf.Ticker("AAPL") # Here we are about to create a Ticker object for Apple stock
hist = stock.history(period="3y") # Fetch 3 years of historical data for the picked stock
# Calculate moving averages
hist['SMA_50'] = hist['Close'].rolling(window=50).mean() # Calculate the 50-day SMA of the closing prices
hist['SMA_200'] = hist['Close'].rolling(window=200).mean() # Calculate the 200-day SMA of the closing prices
# Plotting
plt.figure(figsize=(14, 7)) # Set the figure size for the plot
plt.plot(hist['Close'], label='AAPL Close', alpha=0.5) # Plot the closing prices
plt.plot(hist['SMA_50'], label='50-Day Moving Average', alpha=0.75) # Plot the SMA50
plt.plot(hist['SMA_200'], label='200-Day Moving Average', alpha=0.75) # Plot the SMA200
plt.xlabel("Date") # Label for the x-axis
plt.ylabel("Close Price USD ($)") # Label for the y-axis
plt.title("AAPL Close Price and Moving Averages") # Title of the plot
plt.legend() # Display the legend
plt.show() # Show the plot
The code above can be divided into 3 logical sections: get stock information, calculate moving averages and plot the data into the graph.
If we did everything correctly, we would see as a result some nice graph:
What we got: By the end of the code execution, you will have a plot that visually represents the stock’s daily closing prices alongside its 50-day and 200-day Simple Moving Averages (SMA50 and SMA200). This plot doesn’t just depict numbers and trends; it narrates a story of the stock’s performance over time and provides actionable insights. Specifically, the plot aims to help you: on the graph above with red rectangle are areas, where the bearish trend is on, while green ones represent our bullish trend timeline. For clarification, those rectangles are added manually by me, for better visibility. What our script is providing — is a plot with 3 lines of information.
Understand Market Trends
Identify Market Trends: The plot visually demonstrates whether the stock is in a bullish trend (indicating potential buying opportunities) or a bearish trend (which might suggest selling or waiting).
A bullish trend is typically identified when the stock’s price is consistently above its moving averages, especially if the SMA50 is also above the SMA200 — that’s the “Welcome” point (And green rectangle area in graph).
Conversely, a bearish trend might be inferred when the stock’s price and the SMA50 are below the SMA200 — and, as we know about these animals — this is the time when market is very unfriendly — thus, it’s dangerous red color.
Make Informed Decisions
Decide When to Enter or Exit the Market: While the plot with SMA50 and SMA200 primarily aids in understanding longer-term trends, it can also hint at when to enter or exit the market based on the crossover points:
Entry Signal: A common bullish entry signal occurs when the SMA50 crosses above the SMA200, suggesting that the stock’s price might start an upward trend. On our graph that will be the point of the beginning for the green rectangle area
Exit Signal: Conversely, a bearish exit signal is often indicated when the SMA50 crosses below the SMA200, hinting that the stock might begin a downward trend. All the red rectangle beginning areas can be considered as an exit point
Support Investment Strategies
Support for Diverse Investment Strategies: Depending on your investment strategy, you can use these trends and signals differently. If you’re a long-term investor, you might look for a bullish crossover as a sign to buy and hold. If you’re more of a short-term trader, you might use these signals to time your trades more precisely, looking for shorter-term gains.
Visualize Data for Clarity
Visual Clarity: The visual representation makes it easier to see the stock’s performance at a glance, as opposed to trying to discern patterns from raw data or tables. It highlights the importance of visualization in data analysis, making complex data more accessible and understandable.
Hope this helps you to start making your move from just getting the data to analyzing it and considering decision-making points. Next article will be for another concept, which considers SMA_5, SMA_8, SMA_13 indicators. And later, we will compare these two approaches in terms of accuracy. And finally, our traditional disclaimer:
Financial Disclaimer: The views in this article are the author’s personal views. This commentary is provided for general informational purposes only. It does not constitute financial, investment, tax, legal, or accounting advice, nor does it constitute an offer or solicitation to buy or sell any securities referred to. Individual circumstances and current events are critical to sound investment planning; anyone wishing to act on this article should consult with their advisor. The information provided in this article has been obtained from sources believed to be reliable and is believed to be accurate at the time of publishing, but we do not represent that it is accurate or complete, and it should not be relied upon as such. Investing in stocks, bonds, exchange-traded funds, mutual funds, and money market funds involves the risk of loss. Their values change frequently, and past performance may not be repeated.