Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
"""
|
| 2 |
-
|
| 3 |
-
-
|
| 4 |
-
-
|
| 5 |
-
-
|
| 6 |
"""
|
| 7 |
|
| 8 |
import yfinance as yf
|
|
@@ -13,29 +13,25 @@ import talib
|
|
| 13 |
import gradio as gr
|
| 14 |
from datetime import date
|
| 15 |
import os
|
| 16 |
-
from typing import Optional,
|
| 17 |
|
| 18 |
-
#
|
| 19 |
-
# TALib pattern
|
| 20 |
-
#
|
| 21 |
|
| 22 |
TALIB_PATTERNS = sorted([n for n in dir(talib) if n.startswith("CDL")])
|
| 23 |
-
|
| 24 |
-
# UI name → TALib name mapping
|
| 25 |
PATTERN_DISPLAY_MAP = {n.replace("CDL", ""): n for n in TALIB_PATTERNS}
|
| 26 |
DISPLAY_PATTERNS = list(PATTERN_DISPLAY_MAP.keys())
|
| 27 |
|
| 28 |
-
|
| 29 |
-
#
|
| 30 |
-
#
|
| 31 |
-
# ===============================
|
| 32 |
|
| 33 |
def _normalize_col_name(col) -> str:
|
| 34 |
if isinstance(col, (tuple, list)):
|
| 35 |
return "_".join(str(c) for c in col if c).lower()
|
| 36 |
return str(col).strip().lower()
|
| 37 |
|
| 38 |
-
|
| 39 |
def _find_best_col(key: str, columns: List[str]) -> Optional[str]:
|
| 40 |
if key in columns:
|
| 41 |
return key
|
|
@@ -47,10 +43,9 @@ def _find_best_col(key: str, columns: List[str]) -> Optional[str]:
|
|
| 47 |
return c
|
| 48 |
return None
|
| 49 |
|
| 50 |
-
|
| 51 |
def clean_ohlc(df: pd.DataFrame) -> pd.DataFrame:
|
| 52 |
if df is None or not isinstance(df, pd.DataFrame):
|
| 53 |
-
raise ValueError("Invalid
|
| 54 |
|
| 55 |
df = df.copy()
|
| 56 |
df.columns = [_normalize_col_name(c) for c in df.columns]
|
|
@@ -86,16 +81,12 @@ def clean_ohlc(df: pd.DataFrame) -> pd.DataFrame:
|
|
| 86 |
|
| 87 |
return df
|
| 88 |
|
| 89 |
-
|
| 90 |
-
# ===============================
|
| 91 |
# Pattern detection
|
| 92 |
-
#
|
| 93 |
|
| 94 |
def find_candlestick_patterns(df, talib_pattern):
|
| 95 |
-
|
| 96 |
-
func = getattr(talib, talib_pattern)
|
| 97 |
-
except AttributeError:
|
| 98 |
-
return [], f"TALib pattern not found: {talib_pattern}"
|
| 99 |
|
| 100 |
df = clean_ohlc(df)
|
| 101 |
|
|
@@ -115,28 +106,31 @@ def find_candlestick_patterns(df, talib_pattern):
|
|
| 115 |
bull = pd.Series(np.nan, index=df.index)
|
| 116 |
bull[s > 0] = df.loc[s > 0, "Low"] * 0.98
|
| 117 |
apds.append(
|
| 118 |
-
mpf.make_addplot(
|
| 119 |
-
|
|
|
|
|
|
|
| 120 |
)
|
| 121 |
|
| 122 |
if (s < 0).any():
|
| 123 |
bear = pd.Series(np.nan, index=df.index)
|
| 124 |
bear[s < 0] = df.loc[s < 0, "High"] * 1.02
|
| 125 |
apds.append(
|
| 126 |
-
mpf.make_addplot(
|
| 127 |
-
|
|
|
|
|
|
|
| 128 |
)
|
| 129 |
|
| 130 |
return apds, None
|
| 131 |
|
| 132 |
-
|
| 133 |
-
# ===============================
|
| 134 |
# Main plot function
|
| 135 |
-
#
|
| 136 |
|
| 137 |
def plot_stock_with_patterns(symbol, start, end, selected):
|
| 138 |
if not symbol:
|
| 139 |
-
return None, "
|
| 140 |
|
| 141 |
try:
|
| 142 |
df = yf.download(symbol, start=start, end=end, progress=False)
|
|
@@ -144,7 +138,7 @@ def plot_stock_with_patterns(symbol, start, end, selected):
|
|
| 144 |
return None, str(e)
|
| 145 |
|
| 146 |
if df.empty:
|
| 147 |
-
return None, "No data"
|
| 148 |
|
| 149 |
try:
|
| 150 |
df_clean = clean_ohlc(df)
|
|
@@ -169,36 +163,67 @@ def plot_stock_with_patterns(symbol, start, end, selected):
|
|
| 169 |
volume="Volume" in df_clean.columns,
|
| 170 |
addplot=addplots if addplots else None,
|
| 171 |
style="yahoo",
|
| 172 |
-
title=f"{symbol} Candlestick Chart",
|
| 173 |
-
|
| 174 |
-
|
| 175 |
)
|
| 176 |
|
| 177 |
fig.savefig(path, dpi=150, bbox_inches="tight")
|
| 178 |
-
return path, "
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
#
|
| 182 |
-
#
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
end = gr.Textbox(label="End Date", value=date.today().strftime("%Y-%m-%d"))
|
| 191 |
-
|
| 192 |
-
patterns = gr.CheckboxGroup(
|
| 193 |
-
label="Candlestick Pattern",
|
| 194 |
-
choices=DISPLAY_PATTERNS,
|
| 195 |
-
value=["HAMMER", "SHOOTINGSTAR"]
|
| 196 |
)
|
| 197 |
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
run.click(
|
| 204 |
plot_stock_with_patterns,
|
|
|
|
| 1 |
"""
|
| 2 |
+
TALib + mplfinance + Gradio
|
| 3 |
+
- Clean dashboard layout
|
| 4 |
+
- Pattern names without CDL
|
| 5 |
+
- Max chart space
|
| 6 |
"""
|
| 7 |
|
| 8 |
import yfinance as yf
|
|
|
|
| 13 |
import gradio as gr
|
| 14 |
from datetime import date
|
| 15 |
import os
|
| 16 |
+
from typing import Optional, List
|
| 17 |
|
| 18 |
+
# =====================================================
|
| 19 |
+
# TALib pattern mapping (UI clean, backend intact)
|
| 20 |
+
# =====================================================
|
| 21 |
|
| 22 |
TALIB_PATTERNS = sorted([n for n in dir(talib) if n.startswith("CDL")])
|
|
|
|
|
|
|
| 23 |
PATTERN_DISPLAY_MAP = {n.replace("CDL", ""): n for n in TALIB_PATTERNS}
|
| 24 |
DISPLAY_PATTERNS = list(PATTERN_DISPLAY_MAP.keys())
|
| 25 |
|
| 26 |
+
# =====================================================
|
| 27 |
+
# Data utilities
|
| 28 |
+
# =====================================================
|
|
|
|
| 29 |
|
| 30 |
def _normalize_col_name(col) -> str:
|
| 31 |
if isinstance(col, (tuple, list)):
|
| 32 |
return "_".join(str(c) for c in col if c).lower()
|
| 33 |
return str(col).strip().lower()
|
| 34 |
|
|
|
|
| 35 |
def _find_best_col(key: str, columns: List[str]) -> Optional[str]:
|
| 36 |
if key in columns:
|
| 37 |
return key
|
|
|
|
| 43 |
return c
|
| 44 |
return None
|
| 45 |
|
|
|
|
| 46 |
def clean_ohlc(df: pd.DataFrame) -> pd.DataFrame:
|
| 47 |
if df is None or not isinstance(df, pd.DataFrame):
|
| 48 |
+
raise ValueError("Invalid dataframe")
|
| 49 |
|
| 50 |
df = df.copy()
|
| 51 |
df.columns = [_normalize_col_name(c) for c in df.columns]
|
|
|
|
| 81 |
|
| 82 |
return df
|
| 83 |
|
| 84 |
+
# =====================================================
|
|
|
|
| 85 |
# Pattern detection
|
| 86 |
+
# =====================================================
|
| 87 |
|
| 88 |
def find_candlestick_patterns(df, talib_pattern):
|
| 89 |
+
func = getattr(talib, talib_pattern)
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
df = clean_ohlc(df)
|
| 92 |
|
|
|
|
| 106 |
bull = pd.Series(np.nan, index=df.index)
|
| 107 |
bull[s > 0] = df.loc[s > 0, "Low"] * 0.98
|
| 108 |
apds.append(
|
| 109 |
+
mpf.make_addplot(
|
| 110 |
+
bull, type="scatter", marker="^",
|
| 111 |
+
markersize=90, color="green", alpha=0.85
|
| 112 |
+
)
|
| 113 |
)
|
| 114 |
|
| 115 |
if (s < 0).any():
|
| 116 |
bear = pd.Series(np.nan, index=df.index)
|
| 117 |
bear[s < 0] = df.loc[s < 0, "High"] * 1.02
|
| 118 |
apds.append(
|
| 119 |
+
mpf.make_addplot(
|
| 120 |
+
bear, type="scatter", marker="v",
|
| 121 |
+
markersize=90, color="red", alpha=0.85
|
| 122 |
+
)
|
| 123 |
)
|
| 124 |
|
| 125 |
return apds, None
|
| 126 |
|
| 127 |
+
# =====================================================
|
|
|
|
| 128 |
# Main plot function
|
| 129 |
+
# =====================================================
|
| 130 |
|
| 131 |
def plot_stock_with_patterns(symbol, start, end, selected):
|
| 132 |
if not symbol:
|
| 133 |
+
return None, "Stock symbol required"
|
| 134 |
|
| 135 |
try:
|
| 136 |
df = yf.download(symbol, start=start, end=end, progress=False)
|
|
|
|
| 138 |
return None, str(e)
|
| 139 |
|
| 140 |
if df.empty:
|
| 141 |
+
return None, "No data found"
|
| 142 |
|
| 143 |
try:
|
| 144 |
df_clean = clean_ohlc(df)
|
|
|
|
| 163 |
volume="Volume" in df_clean.columns,
|
| 164 |
addplot=addplots if addplots else None,
|
| 165 |
style="yahoo",
|
| 166 |
+
title=f"{symbol} • Candlestick Chart",
|
| 167 |
+
figscale=1.7,
|
| 168 |
+
returnfig=True
|
| 169 |
)
|
| 170 |
|
| 171 |
fig.savefig(path, dpi=150, bbox_inches="tight")
|
| 172 |
+
return path, "Chart generated successfully"
|
| 173 |
+
|
| 174 |
+
# =====================================================
|
| 175 |
+
# Gradio UI – Clean Dashboard Layout
|
| 176 |
+
# =====================================================
|
| 177 |
+
|
| 178 |
+
with gr.Blocks(fill_height=True, theme=gr.themes.Soft()) as iface:
|
| 179 |
+
gr.Markdown(
|
| 180 |
+
"""
|
| 181 |
+
# 📊 TALib Candlestick Pattern Dashboard
|
| 182 |
+
**Bullish = Green ▲ | Bearish = Red ▼**
|
| 183 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
)
|
| 185 |
|
| 186 |
+
with gr.Row():
|
| 187 |
+
with gr.Column(scale=1, min_width=320):
|
| 188 |
+
gr.Markdown("### ⚙️ Controls")
|
| 189 |
+
|
| 190 |
+
symbol = gr.Textbox(
|
| 191 |
+
label="Stock / Index Symbol",
|
| 192 |
+
value="MSFT",
|
| 193 |
+
placeholder="AAPL, MSFT, ^NSEI, ^GSPC"
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
start = gr.Textbox(
|
| 197 |
+
label="Start Date",
|
| 198 |
+
value="2024-01-01"
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
end = gr.Textbox(
|
| 202 |
+
label="End Date",
|
| 203 |
+
value=date.today().strftime("%Y-%m-%d")
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
patterns = gr.CheckboxGroup(
|
| 207 |
+
label="Candlestick Patterns",
|
| 208 |
+
choices=DISPLAY_PATTERNS,
|
| 209 |
+
value=["HAMMER", "SHOOTINGSTAR"],
|
| 210 |
+
interactive=True
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
run = gr.Button("📈 Generate Chart", variant="primary")
|
| 214 |
+
|
| 215 |
+
status = gr.Textbox(
|
| 216 |
+
label="Status",
|
| 217 |
+
interactive=False
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
with gr.Column(scale=3):
|
| 221 |
+
gr.Markdown("### 📉 Price Chart")
|
| 222 |
+
chart = gr.Image(
|
| 223 |
+
type="filepath",
|
| 224 |
+
height=700,
|
| 225 |
+
show_label=False
|
| 226 |
+
)
|
| 227 |
|
| 228 |
run.click(
|
| 229 |
plot_stock_with_patterns,
|