eshan6704 commited on
Commit
c1fcb74
·
verified ·
1 Parent(s): 1327196

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -41
app.py CHANGED
@@ -1,8 +1,8 @@
1
  # =========================================================
2
  # TALib + mplfinance + Gradio
3
  # 1️⃣ Load Data (Internet only)
4
- # 2️⃣ Chart Type
5
- # 3️⃣ Pattern Marking
6
  # =========================================================
7
 
8
  import yfinance as yf
@@ -22,7 +22,7 @@ PATTERN_MAP = {p.replace("CDL", ""): p for p in TALIB_PATTERNS}
22
  PATTERN_CHOICES = ["None"] + list(PATTERN_MAP.keys())
23
 
24
  # ---------------------------------------------------------
25
- # DATA CLEANING (WITH YOUR REQUESTED ADDITION)
26
  # ---------------------------------------------------------
27
  def clean_ohlc(df):
28
  if df is None or df.empty:
@@ -30,14 +30,14 @@ def clean_ohlc(df):
30
 
31
  df = df.copy()
32
 
33
- # YOUR REQUESTED FORMAT FIX
34
  if isinstance(df.columns, pd.MultiIndex):
35
  df.columns = df.columns.get_level_values(0)
36
 
37
  df.columns = list(df.columns)
38
  df.index.name = None
39
 
40
- # normalize names
41
  df.columns = [str(c).lower().strip() for c in df.columns]
42
 
43
  # rename to mplfinance standard
@@ -69,7 +69,7 @@ def clean_ohlc(df):
69
  return df
70
 
71
  # ---------------------------------------------------------
72
- # 1️⃣ LOAD DATA (INTERNET ONLY)
73
  # ---------------------------------------------------------
74
  def load_data(symbol, start_date, end_date):
75
  if not symbol:
@@ -87,18 +87,7 @@ def load_data(symbol, start_date, end_date):
87
  return None, f"❌ Load error: {e}"
88
 
89
  # ---------------------------------------------------------
90
- # 2️⃣ CHART TYPE CONFIG
91
- # ---------------------------------------------------------
92
- def chart_type_config(chart_type):
93
- mapping = {
94
- "Candlestick": ("candle", True),
95
- "OHLC": ("ohlc", True),
96
- "Line": ("line", False)
97
- }
98
- return mapping[chart_type]
99
-
100
- # ---------------------------------------------------------
101
- # 3️⃣ PATTERN MARKER BUILDER
102
  # ---------------------------------------------------------
103
  def build_pattern_addplots(df, pattern):
104
  if pattern == "None":
@@ -115,12 +104,13 @@ def build_pattern_addplots(df, pattern):
115
  )
116
 
117
  s = pd.Series(result, index=df.index)
118
- aps = []
119
 
 
120
  if (s > 0).any():
121
  bull = pd.Series(np.nan, index=df.index)
122
  bull[s > 0] = df["Low"][s > 0] * 0.98
123
- aps.append(
124
  mpf.make_addplot(
125
  bull,
126
  type="scatter",
@@ -130,10 +120,11 @@ def build_pattern_addplots(df, pattern):
130
  )
131
  )
132
 
 
133
  if (s < 0).any():
134
  bear = pd.Series(np.nan, index=df.index)
135
  bear[s < 0] = df["High"][s < 0] * 1.02
136
- aps.append(
137
  mpf.make_addplot(
138
  bear,
139
  type="scatter",
@@ -143,40 +134,40 @@ def build_pattern_addplots(df, pattern):
143
  )
144
  )
145
 
146
- return aps
147
 
148
  # ---------------------------------------------------------
149
- # BUILD CHART (NO INTERNET CALL)
150
  # ---------------------------------------------------------
151
- def build_chart(df, symbol, chart_type, pattern):
152
  if df is None:
153
  return None, "❌ Load data first"
154
 
155
- mpf_type, volume = chart_type_config(chart_type)
156
  addplots = build_pattern_addplots(df, pattern)
 
157
 
158
  os.makedirs("/tmp", exist_ok=True)
159
- path = f"/tmp/{symbol}_{chart_type}_{pattern}.png"
160
 
161
  fig, _ = mpf.plot(
162
  df,
163
- type=mpf_type,
164
- volume=volume,
165
- addplot=addplots if mpf_type != "line" else None,
166
  style="yahoo",
167
- title=f"{symbol} | {chart_type} | {pattern}",
168
  figscale=1.8,
169
  returnfig=True
170
  )
171
 
172
  fig.savefig(path, dpi=150, bbox_inches="tight")
173
- return path, "✅ Chart built successfully"
174
 
175
  # ---------------------------------------------------------
176
  # =================== GRADIO UI ===========================
177
  # ---------------------------------------------------------
178
  with gr.Blocks(fill_height=True) as app:
179
- gr.Markdown("## 📊 Stock Chart Builder (3-Step Clean App)")
180
 
181
  state_df = gr.State(None)
182
 
@@ -196,13 +187,7 @@ with gr.Blocks(fill_height=True) as app:
196
  # ---------------- BUILD SECTION ----------------
197
  with gr.Row():
198
  with gr.Column(scale=1):
199
- gr.Markdown("### 2️⃣ Chart Type")
200
- chart_type = gr.Dropdown(
201
- ["Candlestick", "OHLC", "Line"],
202
- value="Candlestick"
203
- )
204
-
205
- gr.Markdown("### 3️⃣ Pattern")
206
  pattern = gr.Dropdown(
207
  PATTERN_CHOICES,
208
  value="None"
@@ -211,7 +196,7 @@ with gr.Blocks(fill_height=True) as app:
211
  build_btn = gr.Button("Build Chart", variant="primary")
212
 
213
  with gr.Column(scale=3):
214
- chart = gr.Image(label="Chart Output", height=600)
215
  build_status = gr.Textbox(label="Build Status")
216
 
217
  # ---------------- EVENTS ----------------
@@ -223,7 +208,7 @@ with gr.Blocks(fill_height=True) as app:
223
 
224
  build_btn.click(
225
  build_chart,
226
- inputs=[state_df, symbol, chart_type, pattern],
227
  outputs=[chart, build_status]
228
  )
229
 
 
1
  # =========================================================
2
  # TALib + mplfinance + Gradio
3
  # 1️⃣ Load Data (Internet only)
4
+ # 2️⃣ Pattern Selection
5
+ # 3️⃣ Build Candlestick Chart + Pattern Marking
6
  # =========================================================
7
 
8
  import yfinance as yf
 
22
  PATTERN_CHOICES = ["None"] + list(PATTERN_MAP.keys())
23
 
24
  # ---------------------------------------------------------
25
+ # DATA CLEANING (MultiIndex SAFE)
26
  # ---------------------------------------------------------
27
  def clean_ohlc(df):
28
  if df is None or df.empty:
 
30
 
31
  df = df.copy()
32
 
33
+ # ---- MultiIndex handling ----
34
  if isinstance(df.columns, pd.MultiIndex):
35
  df.columns = df.columns.get_level_values(0)
36
 
37
  df.columns = list(df.columns)
38
  df.index.name = None
39
 
40
+ # normalize column names
41
  df.columns = [str(c).lower().strip() for c in df.columns]
42
 
43
  # rename to mplfinance standard
 
69
  return df
70
 
71
  # ---------------------------------------------------------
72
+ # 1️⃣ LOAD DATA (Internet only)
73
  # ---------------------------------------------------------
74
  def load_data(symbol, start_date, end_date):
75
  if not symbol:
 
87
  return None, f"❌ Load error: {e}"
88
 
89
  # ---------------------------------------------------------
90
+ # 2️⃣ PATTERN MARKER BUILDER
 
 
 
 
 
 
 
 
 
 
 
91
  # ---------------------------------------------------------
92
  def build_pattern_addplots(df, pattern):
93
  if pattern == "None":
 
104
  )
105
 
106
  s = pd.Series(result, index=df.index)
107
+ addplots = []
108
 
109
+ # bullish
110
  if (s > 0).any():
111
  bull = pd.Series(np.nan, index=df.index)
112
  bull[s > 0] = df["Low"][s > 0] * 0.98
113
+ addplots.append(
114
  mpf.make_addplot(
115
  bull,
116
  type="scatter",
 
120
  )
121
  )
122
 
123
+ # bearish
124
  if (s < 0).any():
125
  bear = pd.Series(np.nan, index=df.index)
126
  bear[s < 0] = df["High"][s < 0] * 1.02
127
+ addplots.append(
128
  mpf.make_addplot(
129
  bear,
130
  type="scatter",
 
134
  )
135
  )
136
 
137
+ return addplots
138
 
139
  # ---------------------------------------------------------
140
+ # 3️⃣ BUILD CANDLESTICK CHART (NO INTERNET)
141
  # ---------------------------------------------------------
142
+ def build_chart(df, symbol, pattern):
143
  if df is None:
144
  return None, "❌ Load data first"
145
 
 
146
  addplots = build_pattern_addplots(df, pattern)
147
+ has_volume = "Volume" in df.columns
148
 
149
  os.makedirs("/tmp", exist_ok=True)
150
+ path = f"/tmp/{symbol}_candlestick_{pattern}.png"
151
 
152
  fig, _ = mpf.plot(
153
  df,
154
+ type="candle",
155
+ volume=has_volume,
156
+ addplot=addplots if addplots else None,
157
  style="yahoo",
158
+ title=f"{symbol} | Candlestick | {pattern}",
159
  figscale=1.8,
160
  returnfig=True
161
  )
162
 
163
  fig.savefig(path, dpi=150, bbox_inches="tight")
164
+ return path, "✅ Candlestick chart built successfully"
165
 
166
  # ---------------------------------------------------------
167
  # =================== GRADIO UI ===========================
168
  # ---------------------------------------------------------
169
  with gr.Blocks(fill_height=True) as app:
170
+ gr.Markdown("## 📊 Candlestick Pattern Analyzer (Clean 3-Step App)")
171
 
172
  state_df = gr.State(None)
173
 
 
187
  # ---------------- BUILD SECTION ----------------
188
  with gr.Row():
189
  with gr.Column(scale=1):
190
+ gr.Markdown("### 2️⃣ Pattern")
 
 
 
 
 
 
191
  pattern = gr.Dropdown(
192
  PATTERN_CHOICES,
193
  value="None"
 
196
  build_btn = gr.Button("Build Chart", variant="primary")
197
 
198
  with gr.Column(scale=3):
199
+ chart = gr.Image(label="Candlestick Chart", height=600)
200
  build_status = gr.Textbox(label="Build Status")
201
 
202
  # ---------------- EVENTS ----------------
 
208
 
209
  build_btn.click(
210
  build_chart,
211
+ inputs=[state_df, symbol, pattern],
212
  outputs=[chart, build_status]
213
  )
214