Skip to content

Instantly share code, notes, and snippets.

@quantra-go-algo
Created May 5, 2025 10:52
Show Gist options
  • Select an option

  • Save quantra-go-algo/88e0bb5836eac8034d788e7c6e2dfaa1 to your computer and use it in GitHub Desktop.

Select an option

Save quantra-go-algo/88e0bb5836eac8034d788e7c6e2dfaa1 to your computer and use it in GitHub Desktop.
# 1) IMPORT LIBRARIES
import yfinance as yf # yfinance to fetch historical market data
import pandas as pd # pandas for data manipulation (DataFrame)
import matplotlib.pyplot as plt # matplotlib for plotting
# 2) DOWNLOAD TESLA (TSLA) DATA
# - 'start' is the first date (inclusive)
# - 'end' is the last date (exclusive)
tesla = yf.download(
tickers='TSLA',
start='2023-01-01',
end='2025-04-24',
progress=False # disable download progress bar
)
# 3) EXTRACT CLOSE PRICE
# We only need the 'Close' column for moving averages
close = tesla['Close']
# 4) CALCULATE MOVING AVERAGES
# rolling(window=N).mean() computes the N-day simple moving average
ma10 = close.rolling(window=10).mean() # 10-day MA
ma20 = close.rolling(window=20).mean() # 20-day MA
ma50 = close.rolling(window=50).mean() # 50-day MA
# 5) PLOT CLOSE PRICE AND MOVING AVERAGES
plt.figure(figsize=(12, 6)) # set figure size
# Plot the raw close price
plt.plot(close.index, close, label='Close Price', linewidth=1)
# Plot each moving average
plt.plot(ma10.index, ma10, label='10-Day MA', linewidth=1)
plt.plot(ma20.index, ma20, label='20-Day MA', linewidth=1)
plt.plot(ma50.index, ma50, label='50-Day MA', linewidth=1)
# 6) FORMAT THE PLOT
plt.title('Tesla Close Price & 10/20/50-Day Moving Averages\n2023–2025') # title
plt.xlabel('Date') # x-axis label
plt.ylabel('Price (USD) and Moving Averages') # y-axis label
plt.legend() # show legend
plt.grid(True) # add grid for readability
# 7) DISPLAY THE PLOT
plt.tight_layout() # adjust padding
plt.show() # render the plot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment