Lesson Overview

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:

  1. Loading and Preparing Tesla Stock Data
  2. Calculating Simple Moving Averages (SMAs)
  3. Identifying Golden Cross and Death Cross
  4. Visualizing the Results
Loading and Preparing Tesla Stock Data

As a reminder, we will use historical prices of Tesla stock for our analysis. Let's load the dataset and prepare it:

import pandas as pd
import matplotlib.pyplot as plt
from datasets import load_dataset

# Load the Tesla dataset
dataset = load_dataset('codesignal/tsla-historic-prices')
tesla_df = pd.DataFrame(dataset['train'])

# Convert 'Date' column to datetime format and set it as the index
tesla_df['Date'] = pd.to_datetime(tesla_df['Date'])
tesla_df.set_index('Date', inplace=True)

Explanation:

  • Import Libraries: We import pandas for data manipulation, matplotlib.pyplot for plotting, and load_dataset to fetch our Tesla stock data.
  • Load Dataset: We use load_dataset to fetch the dataset and convert it to a DataFrame.
  • Convert Date Column: The Date column is converted to datetime format for easier manipulation.
  • Set Index: We set the Date column as the index to efficiently perform time series operations.
Calculating Simple Moving Averages (SMAs)

A Simple Moving Average (SMA) smooths out price data over a pre-defined time period to identify trends. Now, let's calculate the SMAs:

Python
# Calculate 50-day and 200-day SMAs
tesla_df['SMA_50'] = tesla_df['Close'].rolling(window=50).mean()
tesla_df['SMA_200'] = tesla_df['Close'].rolling(window=200).mean()

Explanation:

  • SMA_50: We calculate the 50-day SMA by using the rolling method with a window of 50 days on the 'Close' price and then applying the mean function.
  • SMA_200: Similarly, we calculate the 200-day SMA by using a rolling window of 200 days.
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal