Last active
February 22, 2024 15:26
-
-
Save financial-python/0902fee09a358767c377db12d1e39164 to your computer and use it in GitHub Desktop.
Coding and Visualizing a Stock Price crossing a Simple Moving Average in Python
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 pandas as pd | |
import plotly.graph_objs as go | |
from plotly.subplots import make_subplots | |
#Get Historical Stock Data from AAPL | |
stock_data = yf.download(tickers='AAPL', interval='1d', period='3y') | |
#Calculate an SMA | |
stock_data['SMA50'] = stock_data['Close'].rolling(window=50).mean() | |
#Determine when the stock price crosses above / below the SMA | |
stock_data['Crossings'] = 0 #cross below = -1, cross above = 1 | |
cross_below_indexes = (stock_data['Close'].shift(1) > stock_data['SMA50'].shift(1)) & (stock_data['Close'] < stock_data['SMA50']) | |
cross_above_indexes = (stock_data['Close'].shift(1) < stock_data['SMA50'].shift(1)) & (stock_data['Close'] > stock_data['SMA50']) | |
stock_data.loc[cross_below_indexes, 'Crossings'] = -1 | |
stock_data.loc[cross_above_indexes, 'Crossings'] = 1 | |
#use plotly to create graph | |
fig = make_subplots(rows=1, cols=1, shared_xaxes=True) | |
# Add the stock price and SMA50 lines | |
stock_price_line = go.Scatter(x=stock_data.index, y=stock_data['Close'], mode='lines', name='Stock Price', line=dict(color='blue')) | |
sma50_line = go.Scatter(x=stock_data.index, y=stock_data['SMA50'], mode='lines', name='SMA50', line=dict(color='orange')) | |
fig.add_trace(stock_price_line) | |
fig.add_trace(sma50_line) | |
# Add markers for crossings | |
cross_below = go.Scatter(x=stock_data[stock_data['Crossings'] == -1].index, y=stock_data[stock_data['Crossings'] == -1]['SMA50'], | |
mode='markers', name='Price Crosses Below SMA50', marker=dict(color='red', size=10)) | |
fig.add_trace(cross_below) | |
# Add markers for crossings above SMA50 | |
cross_above = go.Scatter(x=stock_data[stock_data['Crossings'] == 1].index, y=stock_data[stock_data['Crossings'] == 1]['SMA50'], | |
mode='markers', name='Price Crosses Above SMA50', marker=dict(color='green', size=10)) | |
fig.add_trace(cross_above) | |
# Customize the layout | |
fig.update_layout(title='AAPL Stock Price and SMA50 Crossings', | |
xaxis_rangeslider_visible=False, xaxis_title='Date', | |
yaxis_title='Price', showlegend=True) | |
# Show the chart | |
fig.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment