File size: 4,355 Bytes
ee1214d 319d3dc 3374424 ee1214d 3374424 ee1214d 3374424 d833f1d 3374424 d833f1d 319d3dc d833f1d 319d3dc d833f1d 319d3dc d833f1d 319d3dc d833f1d 3374424 319d3dc 3374424 319d3dc 3374424 319d3dc 3374424 d833f1d 3374424 d833f1d ee1214d d833f1d ee1214d 3374424 d833f1d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
import yfinance as yf
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import streamlit as st
from datetime import datetime
# Step 1: Define a function to fetch real-time market data up to the current date
def fetch_data(ticker_symbol):
ticker = yf.Ticker(ticker_symbol)
end_date = datetime.now().strftime('%Y-%m-%d') # Get the current date
data = ticker.history(start="2023-01-01", end=end_date) # Fetches data from the start of this year to the current date
return data
# Step 2: Define a function to calculate indicators
def calculate_indicators(df, lengthEMA=3, lengthRSI=14, momentumLength=3, trendLength=50):
# Calculate Moving Averages
df['MA20'] = df['Close'].rolling(window=20).mean()
df['MA50'] = df['Close'].rolling(window=50).mean()
# Calculate EMA for Buy Signal
buy_signal = df['Close'] - df['Open']
df['SignalEMA'] = df['Close'].ewm(span=lengthEMA, adjust=False).mean()
# Calculate RSI
delta = df['Close'].diff(1)
gain = (delta.where(delta > 0, 0)).rolling(window=lengthRSI).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=lengthRSI).mean()
rs = gain / loss
df['RSI'] = 100 - (100 / (1 + rs))
# Calculate Momentum
df['Momentum'] = df['Close'].diff(momentumLength)
# Composite SIGNAL Calculation
df['SignalComposite'] = (0.5 * df['SignalEMA']) + (0.3 * (df['RSI'] - 50) / 100) + (0.2 * (df['Momentum'] / df['Close'].rolling(window=lengthRSI).mean()))
# Smooth the Composite SIGNAL with EMA
df['SmoothedSignal'] = df['SignalComposite'].ewm(span=lengthEMA, adjust=False).mean()
# Trend Filter (SMA)
df['TrendSMA'] = df['Close'].rolling(window=trendLength).mean()
# Buy and Sell Signals
buyThreshold = 0.75
sellThreshold = -0.75
df['BuySignal'] = (df['SmoothedSignal'] > buyThreshold) & (df['Close'] > df['TrendSMA'])
df['SellSignal'] = (df['SmoothedSignal'] < sellThreshold) & (df['Close'] < df['TrendSMA'])
return df
# Step 3: Streamlit UI Setup for Stock Selection
st.title("Indian Share Market Analysis")
# Add a stock selector input box
st.sidebar.header("Select Stock Ticker")
ticker_symbol = st.sidebar.text_input("Enter Stock Ticker (e.g., RELIANCE.NS, ^NSEI)", "^NSEI")
# Step 4: Fetch Data and Calculate Indicators
nifty_data = fetch_data(ticker_symbol)
nifty_data = calculate_indicators(nifty_data)
# Step 5: Display Stock Data
st.subheader(f"Data Overview for {ticker_symbol}")
st.write(nifty_data.head())
# Step 6: Visualizations using Plotly for Interactivity
st.subheader(f"Buy and Sell Signals for {ticker_symbol}")
# Create a Plotly figure
fig = go.Figure()
# Add Close Price line
fig.add_trace(go.Scatter(
x=nifty_data.index,
y=nifty_data['Close'],
mode='lines',
name='Close Price',
line=dict(color='blue')
))
# Add Trend SMA line
fig.add_trace(go.Scatter(
x=nifty_data.index,
y=nifty_data['TrendSMA'],
mode='lines',
name='Trend SMA',
line=dict(color='gray')
))
# Plot Buy Signals
buy_signals = nifty_data[nifty_data['BuySignal']]
fig.add_trace(go.Scatter(
x=buy_signals.index,
y=buy_signals['Close'],
mode='markers',
name='Buy Signal',
marker=dict(symbol='triangle-up', color='green', size=10)
))
# Plot Sell Signals
sell_signals = nifty_data[nifty_data['SellSignal']]
fig.add_trace(go.Scatter(
x=sell_signals.index,
y=sell_signals['Close'],
mode='markers',
name='Sell Signal',
marker=dict(symbol='triangle-down', color='red', size=10)
))
# Update layout for better readability
fig.update_layout(
title=f"Buy and Sell Signals with Trend Filter for {ticker_symbol}",
xaxis_title="Date",
yaxis_title="Close Price",
legend_title="Legend",
template="plotly_dark"
)
# Show Plotly figure in Streamlit
st.plotly_chart(fig)
# Step 7: Interactive Timeframe Selection and Alerts
st.sidebar.subheader("Select Timeframe:")
timeframes = ['1d', '5d', '1mo', '3mo', '6mo', '1y', '2y', '5y', '10y', 'ytd', 'max']
selected_timeframe = st.sidebar.selectbox('Timeframe', timeframes)
st.sidebar.subheader("Set Alerts:")
alert_type = st.sidebar.selectbox('Alert Type', ['Price', 'RSI'])
alert_value = st.sidebar.number_input('Enter Alert Value')
# Step 8: Run the Streamlit App (Note: Do not use st.run())
# Save as `app.py` and run it using `streamlit run app.py`
|