Update app.py
Browse files
app.py
CHANGED
@@ -3,36 +3,29 @@ import pandas as pd
|
|
3 |
import plotly.graph_objects as go
|
4 |
from ultralytics import YOLO
|
5 |
import cv2
|
6 |
-
import
|
7 |
import gradio as gr
|
8 |
|
9 |
-
API_KEY = "ITWJ6NDTF45CBTDO"
|
10 |
|
11 |
-
def get_stock_candlestick_data(symbol, interval="
|
12 |
-
"""
|
13 |
-
Fetch stock candlestick data from Alpha Vantage.
|
14 |
-
"""
|
15 |
url = f"https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={symbol}&interval={interval}&apikey={API_KEY}&outputsize={output_size}"
|
16 |
-
print(f"Fetching data from: {url}") # Debugging
|
17 |
response = requests.get(url)
|
18 |
if response.status_code == 200:
|
19 |
data = response.json()
|
20 |
-
print("API Response:", data) # Debugging
|
21 |
if f"Time Series ({interval})" in data:
|
22 |
return data[f"Time Series ({interval})"]
|
23 |
else:
|
24 |
-
print("Error: No candlestick data found in response.")
|
25 |
-
print(data)
|
26 |
return None
|
27 |
else:
|
28 |
-
print(f"Error fetching data: {response.status_code}")
|
29 |
-
print(response.text)
|
30 |
return None
|
31 |
|
32 |
def process_stock_candlestick_data(data):
|
33 |
-
"""
|
34 |
-
|
35 |
-
|
|
|
36 |
rows = []
|
37 |
for timestamp, values in data.items():
|
38 |
rows.append({
|
@@ -43,12 +36,15 @@ def process_stock_candlestick_data(data):
|
|
43 |
"close": float(values["4. close"]),
|
44 |
"volume": float(values["5. volume"])
|
45 |
})
|
46 |
-
|
|
|
|
|
47 |
|
48 |
-
def generate_candlestick_chart(df, n=50):
|
49 |
-
"""
|
50 |
-
|
51 |
-
|
|
|
52 |
df = df.tail(n) # Use only the last n rows
|
53 |
fig = go.Figure(data=[go.Candlestick(
|
54 |
x=df["timestamp"],
|
@@ -63,65 +59,89 @@ def generate_candlestick_chart(df, n=50):
|
|
63 |
yaxis_title="Price",
|
64 |
xaxis_rangeslider_visible=False
|
65 |
)
|
66 |
-
|
67 |
-
|
68 |
|
69 |
-
def yolo_model(img_path,
|
70 |
-
"""
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
|
86 |
-
def detect_gap_patterns(symbol):
|
87 |
-
"""
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
|
105 |
# Gradio Interface
|
106 |
with gr.Blocks() as demo:
|
107 |
-
gr.Markdown("# GAP Pattern Detection in
|
108 |
-
gr.Markdown("Enter a stock symbol (e.g., AAPL) to detect GAP UP and GAP DOWN patterns in
|
109 |
-
|
110 |
with gr.Row():
|
111 |
symbol_input = gr.Textbox(label="Stock Symbol", placeholder="Enter a stock symbol (e.g., AAPL)")
|
112 |
-
|
113 |
-
|
|
|
114 |
with gr.Row():
|
115 |
output_image = gr.Image(label="Annotated Candlestick Chart")
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
|
|
|
|
120 |
submit_button.click(
|
121 |
fn=detect_gap_patterns,
|
122 |
-
inputs=symbol_input,
|
123 |
outputs=[output_image, gap_up_output, gap_down_output]
|
124 |
)
|
125 |
|
126 |
# Launch the Gradio app
|
127 |
-
demo.launch(
|
|
|
3 |
import plotly.graph_objects as go
|
4 |
from ultralytics import YOLO
|
5 |
import cv2
|
6 |
+
import os
|
7 |
import gradio as gr
|
8 |
|
9 |
+
API_KEY = "ITWJ6NDTF45CBTDO" # Consider using environment variables for API keys
|
10 |
|
11 |
+
def get_stock_candlestick_data(symbol, interval="1min", output_size="compact"):
|
12 |
+
"""Fetch stock candlestick data from Alpha Vantage."""
|
|
|
|
|
13 |
url = f"https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={symbol}&interval={interval}&apikey={API_KEY}&outputsize={output_size}"
|
|
|
14 |
response = requests.get(url)
|
15 |
if response.status_code == 200:
|
16 |
data = response.json()
|
|
|
17 |
if f"Time Series ({interval})" in data:
|
18 |
return data[f"Time Series ({interval})"]
|
19 |
else:
|
|
|
|
|
20 |
return None
|
21 |
else:
|
|
|
|
|
22 |
return None
|
23 |
|
24 |
def process_stock_candlestick_data(data):
|
25 |
+
"""Process Alpha Vantage stock candlestick data into a DataFrame."""
|
26 |
+
if not data:
|
27 |
+
return None
|
28 |
+
|
29 |
rows = []
|
30 |
for timestamp, values in data.items():
|
31 |
rows.append({
|
|
|
36 |
"close": float(values["4. close"]),
|
37 |
"volume": float(values["5. volume"])
|
38 |
})
|
39 |
+
df = pd.DataFrame(rows)
|
40 |
+
df = df.sort_values("timestamp") # Ensure chronological order
|
41 |
+
return df
|
42 |
|
43 |
+
def generate_candlestick_chart(df, n=50, output_path="candlestick.png"):
|
44 |
+
"""Generate a candlestick chart using Plotly with the last n data points."""
|
45 |
+
if df is None or len(df) == 0:
|
46 |
+
return None
|
47 |
+
|
48 |
df = df.tail(n) # Use only the last n rows
|
49 |
fig = go.Figure(data=[go.Candlestick(
|
50 |
x=df["timestamp"],
|
|
|
59 |
yaxis_title="Price",
|
60 |
xaxis_rangeslider_visible=False
|
61 |
)
|
62 |
+
fig.write_image(output_path)
|
63 |
+
return output_path
|
64 |
|
65 |
+
def yolo_model(img_path, model_path):
|
66 |
+
"""Run YOLO model on the image and count GAP UP and GAP DOWN patterns."""
|
67 |
+
if not os.path.exists(img_path):
|
68 |
+
return None, 0, 0
|
69 |
+
|
70 |
+
# Load model each time to avoid persistence issues in Spaces
|
71 |
+
try:
|
72 |
+
model = YOLO(model_path)
|
73 |
+
results = model(img_path)
|
74 |
+
gap_up_count = 0
|
75 |
+
gap_down_count = 0
|
76 |
+
|
77 |
+
for result in results:
|
78 |
+
boxes = result.boxes
|
79 |
+
if hasattr(boxes, 'cls') and len(boxes.cls) > 0:
|
80 |
+
classes = boxes.cls.cpu().numpy() if hasattr(boxes.cls, 'cpu') else boxes.cls
|
81 |
+
for cls in classes:
|
82 |
+
if int(cls) == 0:
|
83 |
+
gap_down_count += 1
|
84 |
+
elif int(cls) == 1:
|
85 |
+
gap_up_count += 1
|
86 |
+
|
87 |
+
annotated_image = results[0].plot()
|
88 |
+
output_path = "annotated_output.png"
|
89 |
+
cv2.imwrite(output_path, annotated_image)
|
90 |
+
return output_path, gap_up_count, gap_down_count
|
91 |
+
except Exception as e:
|
92 |
+
print(f"Error running YOLO model: {e}")
|
93 |
+
return None, 0, 0
|
94 |
|
95 |
+
def detect_gap_patterns(symbol, model_path="best.pt"):
|
96 |
+
"""Non-streaming function to fetch data, generate charts, and detect GAP patterns."""
|
97 |
+
# Check if the model file exists
|
98 |
+
if not os.path.exists(model_path):
|
99 |
+
return None, f"Model not found at {model_path}", f"Model not found at {model_path}"
|
100 |
+
|
101 |
+
# Get stock data
|
102 |
+
data = get_stock_candlestick_data(symbol)
|
103 |
+
if not data:
|
104 |
+
return None, "Failed to fetch stock data", "Failed to fetch stock data"
|
105 |
+
|
106 |
+
# Process data and generate chart
|
107 |
+
df = process_stock_candlestick_data(data)
|
108 |
+
if df is None or len(df) == 0:
|
109 |
+
return None, "No valid stock data available", "No valid stock data available"
|
110 |
+
|
111 |
+
chart_path = generate_candlestick_chart(df, n=50)
|
112 |
+
if not chart_path or not os.path.exists(chart_path):
|
113 |
+
return None, "Failed to generate chart", "Failed to generate chart"
|
114 |
+
|
115 |
+
# Run YOLO detection
|
116 |
+
annotated_path, gap_up_count, gap_down_count = yolo_model(chart_path, model_path)
|
117 |
+
if not annotated_path:
|
118 |
+
return None, "Failed to run detection model", "Failed to run detection model"
|
119 |
+
|
120 |
+
return annotated_path, f"GAP UP Count: {gap_up_count}", f"GAP DOWN Count: {gap_down_count}"
|
121 |
|
122 |
# Gradio Interface
|
123 |
with gr.Blocks() as demo:
|
124 |
+
gr.Markdown("# GAP Pattern Detection in Stock Charts")
|
125 |
+
gr.Markdown("Enter a stock symbol (e.g., AAPL) to detect GAP UP and GAP DOWN patterns in candlestick charts.")
|
126 |
+
|
127 |
with gr.Row():
|
128 |
symbol_input = gr.Textbox(label="Stock Symbol", placeholder="Enter a stock symbol (e.g., AAPL)")
|
129 |
+
model_path_input = gr.Textbox(label="Model Path", value="best.pt", placeholder="Path to YOLO model file")
|
130 |
+
submit_button = gr.Button("Detect Patterns")
|
131 |
+
|
132 |
with gr.Row():
|
133 |
output_image = gr.Image(label="Annotated Candlestick Chart")
|
134 |
+
|
135 |
+
with gr.Row():
|
136 |
+
gap_up_output = gr.Textbox(label="GAP UP Results")
|
137 |
+
gap_down_output = gr.Textbox(label="GAP DOWN Results")
|
138 |
+
|
139 |
+
# Run detection when the button is clicked
|
140 |
submit_button.click(
|
141 |
fn=detect_gap_patterns,
|
142 |
+
inputs=[symbol_input, model_path_input],
|
143 |
outputs=[output_image, gap_up_output, gap_down_output]
|
144 |
)
|
145 |
|
146 |
# Launch the Gradio app
|
147 |
+
demo.launch()
|