Created
February 19, 2024 04:46
-
-
Save fsndzomga/dfb8e6d518f92dc52abfcdd21918e953 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
import yfinance as yf | |
import matplotlib.pyplot as plt | |
import pandas as pd | |
# Fetch historical data for AAPL | |
data = yf.download('AAPL', start='2023-01-01', end='2024-01-01') | |
# Calculate RSI | |
def RSI(data, window=14): | |
delta = data['Adj Close'].diff(1) | |
gain = (delta.where(delta > 0, 0)).rolling(window=window).mean() | |
loss = (-delta.where(delta < 0, 0)).rolling(window=window).mean() | |
RS = gain / loss | |
return 100 - (100 / (1 + RS)) | |
data['RSI'] = RSI(data) | |
# Calculate MACD | |
exp1 = data['Adj Close'].ewm(span=12, adjust=False).mean() | |
exp2 = data['Adj Close'].ewm(span=26, adjust=False).mean() | |
data['MACD'] = exp1 - exp2 | |
data['Signal Line'] = data['MACD'].ewm(span=9, adjust=False).mean() | |
# Calculate Bollinger Bands | |
data['Middle Band'] = data['Adj Close'].rolling(window=20).mean() | |
data['Upper Band'] = data['Middle Band'] + 2*data['Adj Close'].rolling(window=20).std() | |
data['Lower Band'] = data['Middle Band'] - 2*data['Adj Close'].rolling(window=20).std() | |
# Plotting | |
plt.figure(figsize=(14, 7)) | |
# Plot closing price and Bollinger Bands | |
plt.subplot(311) | |
plt.plot(data['Adj Close'], label='Adjusted Close Price', color='blue') | |
plt.plot(data['Upper Band'], label='Upper Band', color='red') | |
plt.plot(data['Middle Band'], label='Middle Band', color='black') | |
plt.plot(data['Lower Band'], label='Lower Band', color='green') | |
plt.title('AAPL Bollinger Bands') | |
plt.legend() | |
# Plot MACD and Signal Line | |
plt.subplot(312) | |
plt.plot(data['MACD'], label='MACD', color='blue') | |
plt.plot(data['Signal Line'], label='Signal Line', color='red') | |
plt.title('AAPL MACD') | |
plt.legend() | |
# Plot RSI | |
plt.subplot(313) | |
plt.plot(data['RSI'], label='RSI', color='purple') | |
plt.title('AAPL RSI') | |
plt.axhline(70, linestyle='--', alpha=0.5, color='red') | |
plt.axhline(30, linestyle='--', alpha=0.5, color='green') | |
plt.legend() | |
plt.tight_layout() | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment