import yfinance as yf
import pandas as pd
import plotly.graph_objs as go
import time
from scipy.signal import find_peaks
# Function to calculate the simple moving average (SMA)
def calculate_sma(data, window):
return data['Close'].rolling(window=window).mean()
# Function to detect support and resistance lines
def detect_support_resistance(data):
peaks, _ = find_peaks(data['High'], prominence=10)
troughs, _ = find_peaks(-data['Low'], prominence=10)
return peaks, troughs
# Function to calculate Fibonacci retracement levels
def calculate_fibonacci_levels(data):
high = data['Close'].max()
low = data['Close'].min()
diff = high - low
levels = {
'0%': high,
'23.6%': high - (0.236 * diff),
'38.2%': high - (0.382 * diff),
'50%': high - (0.5 * diff),
'61.8%': high - (0.618 * diff),
'100%': low
}
return levels
# Main loop
while True:
try:
# Fetch live stock prices
df = yf.download('^NSEI', period='1d', interval='1m', auto_adjust=True)
# Calculate the moving averages
df['SMA 9'] = calculate_sma(df, window=9)
df['SMA 21'] = calculate_sma(df, window=21)
# Detect support and resistance lines
peaks, troughs = detect_support_resistance(df)
# Calculate Fibonacci retracement levels
fibonacci_levels = calculate_fibonacci_levels(df)
# Create candlestick chart
candlestick = go.Candlestick(x=df.index,
open=df['Open'],
high=df['High'],
low=df['Low'],
close=df['Close'],
name='Candlestick')
# Create moving averages traces
sma_9_trace = go.Scatter(x=df.index, y=df['SMA 9'], mode='lines', name='SMA
9')
sma_21_trace = go.Scatter(x=df.index, y=df['SMA 21'], mode='lines',
name='SMA 21')
# Convert DatetimeIndex to a list
troughs_list = list(troughs)
peaks_list = list(peaks)
# Create Fibonacci retracement levels traces
fibonacci_traces = []
for level, price in fibonacci_levels.items():
trace = go.Scatter(
x=df.index,
y=[price] * len(df),
mode='lines',
name=level,
line=dict(color='green' if level == '0%' else 'blue' if level ==
'50%' else 'orange')
)
fibonacci_traces.append(trace)
# Create plot layout
layout = go.Layout(
title='Stock Data - 1-minute Time Frame',
xaxis=dict(title='Date'),
yaxis=dict(title='Price'),
hovermode='x',
annotations=[
# Annotation for support
dict(
x=df.index[troughs_list[-1]],
y=df['Low'][troughs_list[-1]],
xref='x',
yref='y',
text=f"S-{round(df['Low'][troughs_list[-1]])}",
showarrow=True,
arrowhead=4,
arrowsize=1.5,
arrowwidth=2,
arrowcolor='green',
ax=20,
ay=-40,
bordercolor='black',
borderwidth=2,
borderpad=4,
bgcolor='green',
opacity=0.8,
font=dict(family='Arial', size=12, color='white')
),
# Annotation for resistance
dict(
x=df.index[peaks_list[-1]],
y=df['High'][peaks_list[-1]],
xref='x',
yref='y',
text=f"R-{round(df['High'][peaks_list[-1]])}",
showarrow=True,
arrowhead=4,
arrowsize=1.5,
arrowwidth=2,
arrowcolor='red',
ax=20,
ay=-40,
bordercolor='black',
borderwidth=2,
borderpad=4,
bgcolor='red',
opacity=0.8,
font=dict(family='Arial', size=12, color='white')
)
]
)
# Plot the data
fig = go.Figure(data=[candlestick, sma_9_trace, sma_21_trace] +
fibonacci_traces, layout=layout)
fig.show()
except Exception as e:
print(f'An error occurred: {e}')
# Delay before fetching data again
time.sleep(60) # 60-second interval
==================================================================
# imports and installs
import os
import yfinance as yf
import mplfinance as mpf
import matplotlib.pyplot as plt
import datetime
import time
# variables to tune your plots
# valid periods: 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max
period = '1d'
# valid intervals: 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo
interval = '5m'
# the stocks you want to plot
stocks = ['^NSEI', '^NSEBANK', 'HDFCBANK.NS', 'RELIANCE.NS']
# method to grab data and plot the data
def plot_live_data(stocks, period='1d', interval='1m'):
while True:
for stock in stocks:
plt.figure()
hist = yf.download(tickers=stock, period=period, interval=interval)
mpf.plot(hist, type='candle',
volume=True, mav=(20,5), title=stock + " " +
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
tight_layout=True, figratio=(10,5))
plt.show()
# Delay for 30 seconds before fetching data again
time.sleep(30)
# call the method
plot_live_data(stocks, period, interval)
^NSEI India VIX ^NSEBANK HDFCBANK.NS) RELIANCE.NS
===================================================================================
========
import yfinance as yf
import pandas as pd
from dash import Dash, html, dcc, callback, Input, Output
import plotly.graph_objs as go
import time
# Fetch live stock prices
df_nsei = yf.download('^NSEI', period='1d', interval='1m', auto_adjust=True)
df_indiavix = yf.download('^INDIAVIX', period='1d', interval='1m',
auto_adjust=True)
df_hdfcbank = yf.download('HDFCBANK.NS', period='1d', interval='1m',
auto_adjust=True)
# Define Dash app
app = Dash(__name__)
# Define layout
app.layout = html.Div([
dcc.Graph(id='graph-nsei'),
dcc.Graph(id='graph-indiavix'),
dcc.Graph(id='graph-hdfcbank'),
dcc.Interval(id='interval', interval=30*1000) # Update every 30 seconds
])
# Define callback to update NSEI graph
@app.callback(
Output('graph-nsei', 'figure'),
Input('interval', 'n_intervals')
)
def update_nsei_graph(n_intervals):
return {
'data': [go.Scatter(x=df_nsei.index, y=df_nsei['Close'], mode='lines')],
'layout': {
'title': 'NSEI Stock Price'
}
}
# Define callback to update INDIAVIX graph
@app.callback(
Output('graph-indiavix', 'figure'),
Input('interval', 'n_intervals')
)
def update_indiavix_graph(n_intervals):
return {
'data': [go.Scatter(x=df_indiavix.index, y=df_indiavix['Close'],
mode='lines')],
'layout': {
'title': 'INDIAVIX Stock Price'
}
}
# Define callback to update HDFCBANK graph
@app.callback(
Output('graph-hdfcbank', 'figure'),
Input('interval', 'n_intervals')
)
def update_hdfcbank_graph(n_intervals):
return {
'data': [go.Scatter(x=df_hdfcbank.index, y=df_hdfcbank['Close'],
mode='lines')],
'layout': {
'title': 'HDFCBANK Stock Price'
}
}
# Run the app
if __name__ == '__main__':
app.run_server(debug=True)