Update intraday.py
Browse files- intraday.py +95 -124
intraday.py
CHANGED
|
@@ -1,131 +1,102 @@
|
|
| 1 |
# intraday.py
|
|
|
|
| 2 |
import yfinance as yf
|
| 3 |
import pandas as pd
|
| 4 |
-
import
|
| 5 |
-
import numpy as np
|
| 6 |
-
import plotly.graph_objs as go
|
| 7 |
-
|
| 8 |
-
STYLE_BLOCK = """
|
| 9 |
-
<style>
|
| 10 |
-
.styled-table { border-collapse: collapse; margin: 10px 0; font-size: 0.9em; font-family: sans-serif; width: 100%; box-shadow: 0 0 10px rgba(0,0,0,0.1);}
|
| 11 |
-
.styled-table th, .styled-table td { padding: 8px 10px; border: 1px solid #ddd;}
|
| 12 |
-
.styled-table tbody tr:nth-child(even) { background-color: #f9f9f9;}
|
| 13 |
-
.button { margin:5px; padding:5px 10px; border-radius:5px; border:1px solid #0077cc; background:#0077cc; color:#fff; cursor:pointer;}
|
| 14 |
-
.button:hover { background:#005fa3; }
|
| 15 |
-
</style>
|
| 16 |
-
"""
|
| 17 |
-
|
| 18 |
-
# --- Custom functions (same as daily.py) ---
|
| 19 |
-
def supertrend(df, period=10, multiplier=3):
|
| 20 |
-
hl2 = (df['High'] + df['Low']) / 2
|
| 21 |
-
tr = pd.concat([df['High'] - df['Low'],
|
| 22 |
-
abs(df['High'] - df['Close'].shift()),
|
| 23 |
-
abs(df['Low'] - df['Close'].shift())], axis=1).max(axis=1)
|
| 24 |
-
atr = tr.rolling(period).mean()
|
| 25 |
-
upperband = hl2 + multiplier * atr
|
| 26 |
-
lowerband = hl2 - multiplier * atr
|
| 27 |
-
st = pd.Series(index=df.index)
|
| 28 |
-
trend_up = True
|
| 29 |
-
for i in range(1, len(df)):
|
| 30 |
-
if df['Close'][i] > upperband[i-1]:
|
| 31 |
-
trend_up = True
|
| 32 |
-
elif df['Close'][i] < lowerband[i-1]:
|
| 33 |
-
trend_up = False
|
| 34 |
-
st[i] = lowerband[i] if trend_up else upperband[i]
|
| 35 |
-
return st
|
| 36 |
-
|
| 37 |
-
def zigzag(df, pct=0.5):
|
| 38 |
-
zz = pd.Series(index=df.index)
|
| 39 |
-
last_pivot = df['Close'][0]
|
| 40 |
-
trend = 0
|
| 41 |
-
for i in range(1, len(df)):
|
| 42 |
-
change = (df['Close'][i] - last_pivot) / last_pivot * 100
|
| 43 |
-
if trend >= 0 and change <= -pct:
|
| 44 |
-
zz[i] = df['Close'][i]
|
| 45 |
-
last_pivot = df['Close'][i]
|
| 46 |
-
trend = -1
|
| 47 |
-
elif trend <= 0 and change >= pct:
|
| 48 |
-
zz[i] = df['Close'][i]
|
| 49 |
-
last_pivot = df['Close'][i]
|
| 50 |
-
trend = 1
|
| 51 |
-
return zz
|
| 52 |
-
|
| 53 |
-
def swing_high_low(df, window=5):
|
| 54 |
-
df['SwingHigh'] = df['High'].rolling(window, center=True).max()
|
| 55 |
-
df['SwingLow'] = df['Low'].rolling(window, center=True).min()
|
| 56 |
-
return df
|
| 57 |
-
|
| 58 |
-
def keltner_channel(df, period=20, atr_mult=2):
|
| 59 |
-
ema = talib.EMA(df['Close'], period)
|
| 60 |
-
tr = pd.concat([df['High'] - df['Low'],
|
| 61 |
-
abs(df['High'] - df['Close'].shift()),
|
| 62 |
-
abs(df['Low'] - df['Close'].shift())], axis=1).max(axis=1)
|
| 63 |
-
atr = tr.rolling(period).mean()
|
| 64 |
-
df['KC_Upper'] = ema + atr_mult * atr
|
| 65 |
-
df['KC_Lower'] = ema - atr_mult * atr
|
| 66 |
-
return df
|
| 67 |
-
|
| 68 |
-
# --- Main function ---
|
| 69 |
-
def fetch_intraday(symbol):
|
| 70 |
-
yfsymbol = symbol + ".NS"
|
| 71 |
-
content_html = f"<h1>No intraday data for {symbol}</h1>"
|
| 72 |
|
| 73 |
-
try:
|
| 74 |
-
df = yf.download(yfsymbol, period="1d", interval="5m").round(2)
|
| 75 |
-
if not df.empty:
|
| 76 |
-
if isinstance(df.columns, pd.MultiIndex):
|
| 77 |
-
df.columns = df.columns.get_level_values(0)
|
| 78 |
-
|
| 79 |
-
# --- TA-Lib indicators ---
|
| 80 |
-
df["SMA20"] = talib.SMA(df["Close"], timeperiod=20)
|
| 81 |
-
df["SMA50"] = talib.SMA(df["Close"], timeperiod=50)
|
| 82 |
-
df["EMA20"] = talib.EMA(df["Close"], timeperiod=20)
|
| 83 |
-
df["RSI14"] = talib.RSI(df["Close"], timeperiod=14)
|
| 84 |
-
df["MACD"], df["MACD_Signal"], df["MACD_Hist"] = talib.MACD(df["Close"], fastperiod=12, slowperiod=26, signalperiod=9)
|
| 85 |
-
|
| 86 |
-
# --- Custom indicators ---
|
| 87 |
-
df["SuperTrend"] = supertrend(df)
|
| 88 |
-
df = keltner_channel(df)
|
| 89 |
-
df["ZigZag"] = zigzag(df)
|
| 90 |
-
df = swing_high_low(df)
|
| 91 |
-
|
| 92 |
-
# --- Plotly chart ---
|
| 93 |
-
fig = go.Figure()
|
| 94 |
-
fig.add_trace(go.Candlestick(
|
| 95 |
-
x=df.index, open=df["Open"], high=df["High"],
|
| 96 |
-
low=df["Low"], close=df["Close"], name="Price"
|
| 97 |
-
))
|
| 98 |
-
|
| 99 |
-
# Indicators toggle
|
| 100 |
-
indicators = ["SMA20","SMA50","EMA20","RSI14","MACD","MACD_Signal",
|
| 101 |
-
"SuperTrend","KC_Upper","KC_Lower","ZigZag","SwingHigh","SwingLow"]
|
| 102 |
-
|
| 103 |
-
for ind in indicators:
|
| 104 |
-
yaxis = 'y2' if ind in ["RSI14","MACD","MACD_Signal"] else 'y'
|
| 105 |
-
fig.add_trace(go.Scatter(x=df.index, y=df[ind], mode='lines+markers' if 'Swing' in ind or 'ZigZag' in ind else 'lines',
|
| 106 |
-
name=ind, visible=False, yaxis=yaxis))
|
| 107 |
-
|
| 108 |
-
buttons=[]
|
| 109 |
-
for i, ind in enumerate(indicators):
|
| 110 |
-
visible=[True]+[False]*len(indicators)
|
| 111 |
-
visible[i+1]=True
|
| 112 |
-
buttons.append(dict(label=ind, method="restyle", args=[{"visible":visible}]))
|
| 113 |
-
buttons.append(dict(label="All Off", method="restyle", args=[{"visible":[True]+[False]*len(indicators)}]))
|
| 114 |
-
|
| 115 |
-
fig.update_layout(
|
| 116 |
-
xaxis_title="Time",
|
| 117 |
-
yaxis_title="Price",
|
| 118 |
-
yaxis2=dict(title="Indicator", overlaying="y", side="right"),
|
| 119 |
-
xaxis_rangeslider_visible=False,
|
| 120 |
-
height=700,
|
| 121 |
-
updatemenus=[dict(type="buttons", x=1.05, y=0.8, buttons=buttons)]
|
| 122 |
-
)
|
| 123 |
-
|
| 124 |
-
chart_html = fig.to_html(full_html=False)
|
| 125 |
-
table_html = df.tail(50).to_html(classes="styled-table", border=0)
|
| 126 |
-
content_html = f"{chart_html}<h2>Recent Intraday Data (last 50 rows)</h2>{table_html}"
|
| 127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
except Exception as e:
|
| 129 |
-
|
| 130 |
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# intraday.py
|
| 2 |
+
|
| 3 |
import yfinance as yf
|
| 4 |
import pandas as pd
|
| 5 |
+
from chart_builder import build_chart
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
+
# -------------------------------
|
| 9 |
+
# Fetch + Clean intraday dataset
|
| 10 |
+
# -------------------------------
|
| 11 |
+
def _fetch_intraday(symbol, interval="5m", period="1d"):
|
| 12 |
+
yfs = f"{symbol}.NS"
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
df = yf.download(
|
| 16 |
+
yfs,
|
| 17 |
+
interval=interval,
|
| 18 |
+
period=period,
|
| 19 |
+
progress=False
|
| 20 |
+
)
|
| 21 |
except Exception as e:
|
| 22 |
+
return None, str(e)
|
| 23 |
|
| 24 |
+
if df is None or df.empty:
|
| 25 |
+
return None, "No intraday data returned"
|
| 26 |
+
|
| 27 |
+
# Clean index timestamps
|
| 28 |
+
df.index = pd.to_datetime(df.index)
|
| 29 |
+
|
| 30 |
+
# Remove timezone if present
|
| 31 |
+
try:
|
| 32 |
+
df.index = df.index.tz_localize(None)
|
| 33 |
+
except:
|
| 34 |
+
pass
|
| 35 |
+
|
| 36 |
+
# Round values
|
| 37 |
+
df = df.round(2)
|
| 38 |
+
|
| 39 |
+
return df, None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# -------------------------------
|
| 43 |
+
# Main intraday function (UI return)
|
| 44 |
+
# -------------------------------
|
| 45 |
+
def fetch_intraday(symbol, interval="5m", period="1d"):
|
| 46 |
+
"""
|
| 47 |
+
Supported:
|
| 48 |
+
interval = 1m,2m,5m,15m,30m,60m
|
| 49 |
+
period = 1d,5d,1mo
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
df, err = _fetch_intraday(symbol, interval, period)
|
| 53 |
+
|
| 54 |
+
if err:
|
| 55 |
+
return {
|
| 56 |
+
"html": f"<div class='group'><h2>Intraday Error</h2><p>{err}</p></div>",
|
| 57 |
+
"data": {}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
if df is None or df.empty:
|
| 61 |
+
return {
|
| 62 |
+
"html": f"<div class='group'><h2>No Intraday Data for {symbol}</h2></div>",
|
| 63 |
+
"data": {}
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
# Build chart using indicator engine
|
| 67 |
+
chart_html = build_chart(df)
|
| 68 |
+
|
| 69 |
+
# Convert last rows to table
|
| 70 |
+
table_html = df.tail(200).to_html(
|
| 71 |
+
classes="styled-table",
|
| 72 |
+
border=0
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
final = f"""
|
| 76 |
+
<div class="group">
|
| 77 |
+
<h2>Intraday Chart — {symbol} ({interval}, {period})</h2>
|
| 78 |
+
{chart_html}
|
| 79 |
+
|
| 80 |
+
<h3>Last 200 Rows</h3>
|
| 81 |
+
{table_html}
|
| 82 |
+
|
| 83 |
+
<style>
|
| 84 |
+
.styled-table {{
|
| 85 |
+
border-collapse: collapse;
|
| 86 |
+
width: 100%;
|
| 87 |
+
font-size: 13px;
|
| 88 |
+
}}
|
| 89 |
+
.styled-table td, .styled-table th {{
|
| 90 |
+
border: 1px solid #ddd;
|
| 91 |
+
padding: 6px;
|
| 92 |
+
text-align: right;
|
| 93 |
+
}}
|
| 94 |
+
.styled-table tr:nth-child(even) {{background: #f9f9f9;}}
|
| 95 |
+
</style>
|
| 96 |
+
</div>
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
return {
|
| 100 |
+
"html": final,
|
| 101 |
+
"data": df.tail(200).to_dict()
|
| 102 |
+
}
|