-
-
Save quantra-go-algo/29b622ab5f15b69e40c5a12017694648 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 1) IMPORT LIBRARIES | |
| import yfinance as yf # yfinance to fetch historical market data | |
| import pandas as pd # pandas for data manipulation (DataFrame) | |
| import numpy as np # numpy for numerical operations (weights) | |
| import matplotlib.pyplot as plt # matplotlib for static plotting | |
| # 2) DOWNLOAD TESLA (TSLA) DATA | |
| # - 'start' is inclusive, 'end' is exclusive | |
| tesla = yf.download( | |
| tickers='TSLA', | |
| start='2023-01-01', | |
| end='2025-04-25', | |
| progress=False # disable the progress bar | |
| ) | |
| # 3) EXTRACT CLOSE PRICE SERIES | |
| close = tesla['Close'] # get only the 'Close' column | |
| # 4) CALCULATE 30-DAY SIMPLE MOVING AVERAGE (SMA) | |
| sma15 = close.rolling(window=30).mean() | |
| # 5) CALCULATE 30-DAY EXPONENTIAL MOVING AVERAGE (EMA) | |
| # - span=30 sets the decay so that the effective window ≈30 days | |
| ema30 = close.ewm(span=30, adjust=False).mean() | |
| # 6) CALCULATE 30-DAY LINEARLY WEIGHTED MOVING AVERAGE (LWMA) | |
| # - weights 1,2,…,30 so the most recent day gets weight 30 | |
| weights = np.arange(1, 31) | |
| lwma30 = close.rolling(window=30).apply( | |
| lambda prices: np.dot(prices, weights) / weights.sum(), raw=True | |
| ) | |
| # 7) PLOT CLOSE PRICE AND ALL THREE MOVING AVERAGES | |
| plt.figure(figsize=(12, 6)) # set figure size | |
| plt.plot(close.index, close, label='Close Price', linewidth=1) | |
| plt.plot(sma15.index, sma15, label='30-Day SMA', linewidth=1) | |
| plt.plot(ema30.index, ema30, label='30-Day EMA', linewidth=1) | |
| plt.plot(lwma30.index, lwma30, label='30-Day LWMA', linewidth=1) | |
| # 8) FORMAT THE PLOT | |
| plt.title('Tesla Close Price with 30-Day SMA, EMA & LWMA\n2023–2025') | |
| plt.xlabel('Date') # x-axis label | |
| plt.ylabel('Price (USD) and Moving Average') # y-axis label | |
| plt.legend() # show legend | |
| plt.grid(True) # add grid lines for readability | |
| plt.tight_layout() # adjust layout margins | |
| # 9) DISPLAY THE PLOT | |
| plt.show() # render the plot window (or inline in notebook) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment