Hello and welcome! Today, we will explore Applying Technical Indicators to Identify Trends using Tesla's ($TSLA) stock data. You will revisit how to calculate Simple Moving Averages (SMAs), and learn how to identify trend signals like Golden Cross and Death Cross, and visualize these trends using pandas
and matplotlib
.
Lesson Goal: To understand and implement technical indicators (SMA) and identify trend signals (Golden Cross and Death Cross) in financial data using Python and Pandas.
Lesson Plan:
As a reminder, we will use historical prices of Tesla stock for our analysis. Let's load the dataset and prepare it:
Python1import pandas as pd 2import matplotlib.pyplot as plt 3from datasets import load_dataset 4 5# Load the Tesla dataset 6dataset = load_dataset('codesignal/tsla-historic-prices') 7tesla_df = pd.DataFrame(dataset['train']) 8 9# Convert 'Date' column to datetime format and set it as the index 10tesla_df['Date'] = pd.to_datetime(tesla_df['Date']) 11tesla_df.set_index('Date', inplace=True)
Explanation:
pandas
for data manipulation, matplotlib.pyplot
for plotting, and load_dataset
to fetch our Tesla stock data.load_dataset
to fetch the dataset and convert it to a DataFrame.Date
column is converted to datetime format for easier manipulation.Date
column as the index to efficiently perform time series operations.A Simple Moving Average (SMA) smooths out price data over a pre-defined time period to identify trends. Now, let's calculate the SMAs:
Python1# Calculate 50-day and 200-day SMAs 2tesla_df['SMA_50'] = tesla_df['Close'].rolling(window=50).mean() 3tesla_df['SMA_200'] = tesla_df['Close'].rolling(window=200).mean()
Explanation:
rolling
method with a window of 50 days on the 'Close' price and then applying the mean
function.In trading, golden and death crosses are defined as follows:
Now, let's create signals for these crossover points:
Python1# Identifying the "Golden Cross" and "Death Cross" 2tesla_df['Signal'] = 0 # Default value 3tesla_df.loc[tesla_df['SMA_50'] > tesla_df['SMA_200'], 'Signal'] = 1 4tesla_df.loc[tesla_df['SMA_50'] < tesla_df['SMA_200'], 'Signal'] = -1 5 6# Creating a column to mark crossover points 7tesla_df['Crossover'] = tesla_df['Signal'].diff()
Explanation:
We will use a smaller date range for better visualization. In this example, let's visualize the $TSLA
data for the year 2018.
Python1# Using a smaller date range for better visualization 2tesla_df_small = tesla_df.loc['2018']
Next, we will plot the Close price, 50-day SMA, and 200-day SMA.
Python1# Plot with Golden Cross and Death Cross 2fig, ax = plt.subplots(figsize=(12, 6)) 3tesla_df_small[['Close', 'SMA_50', 'SMA_200']].plot(ax=ax, title="TSLA with Golden Cross and Death Cross (2018)")
Now, to highlight the crossover points, we loop through the 'Crossover' column in the DataFrame. We use green dots for the Golden Cross and red dots for the Death Cross.
Python1# Highlighting Golden Cross and Death Cross points 2crosses = tesla_df_small[tesla_df_small['Crossover'] != 0] 3for idx, row in crosses.iterrows(): 4 if row['Crossover'] == 2: 5 plt.plot(idx, row['SMA_50'], 'go', markersize=10, label='Golden Cross' if 'Golden Cross' not in [text.get_text() for text in ax.get_legend().get_texts()] else "") 6 elif row['Crossover'] == -2: 7 plt.plot(idx, row['SMA_50'], 'ro', markersize=10, label='Death Cross' if 'Death Cross' not in [text.get_text() for text in ax.get_legend().get_texts()] else "") 8 9plt.legend() 10plt.show()
tesla_df_small
to get rows where the 'Crossover' column is not zero.idx
) and row in the crosses
DataFrame:
You have now learned how to apply and visualize technical indicators such as SMAs to identify trends in Tesla stock data. This lesson covered importing and preparing financial data, calculating SMAs, identifying trend signals, and visualizing the results. Practice exercises will reinforce these essential skills, allowing you to analyze and make informed trading decisions. Understanding stock movements and improving your trading strategies by leveraging Python and Pandas is crucial for success in the financial market.
Ready to take your skills to the next level? Let's dive into the practice exercises!