Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import plotly.graph_objects as go
|
| 4 |
+
from ultralytics import YOLO
|
| 5 |
+
import cv2
|
| 6 |
+
import time
|
| 7 |
+
import gradio as gr
|
| 8 |
+
|
| 9 |
+
API_KEY = "ITWJ6NDTF45CBTDO"
|
| 10 |
+
|
| 11 |
+
def get_stock_candlestick_data(symbol, interval="5min", output_size="compact"):
|
| 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 |
+
Process Alpha Vantage stock candlestick data into a DataFrame.
|
| 35 |
+
"""
|
| 36 |
+
rows = []
|
| 37 |
+
for timestamp, values in data.items():
|
| 38 |
+
rows.append({
|
| 39 |
+
"timestamp": timestamp,
|
| 40 |
+
"open": float(values["1. open"]),
|
| 41 |
+
"high": float(values["2. high"]),
|
| 42 |
+
"low": float(values["3. low"]),
|
| 43 |
+
"close": float(values["4. close"]),
|
| 44 |
+
"volume": float(values["5. volume"])
|
| 45 |
+
})
|
| 46 |
+
return pd.DataFrame(rows)
|
| 47 |
+
|
| 48 |
+
def generate_candlestick_chart(df, n=50):
|
| 49 |
+
"""
|
| 50 |
+
Generate a candlestick chart using Plotly with the last n data points.
|
| 51 |
+
"""
|
| 52 |
+
df = df.tail(n) # Use only the last n rows
|
| 53 |
+
fig = go.Figure(data=[go.Candlestick(
|
| 54 |
+
x=df["timestamp"],
|
| 55 |
+
open=df["open"],
|
| 56 |
+
high=df["high"],
|
| 57 |
+
low=df["low"],
|
| 58 |
+
close=df["close"]
|
| 59 |
+
)])
|
| 60 |
+
fig.update_layout(
|
| 61 |
+
title="Candlestick Chart",
|
| 62 |
+
xaxis_title="Time",
|
| 63 |
+
yaxis_title="Price",
|
| 64 |
+
xaxis_rangeslider_visible=False
|
| 65 |
+
)
|
| 66 |
+
# Removed fig.show() since Gradio will display the image
|
| 67 |
+
fig.write_image("candlestick.png")
|
| 68 |
+
|
| 69 |
+
def yolo_model(img_path, model):
|
| 70 |
+
"""
|
| 71 |
+
Run YOLO model on the image and count GAP UP and GAP DOWN patterns.
|
| 72 |
+
"""
|
| 73 |
+
results = model(img_path)
|
| 74 |
+
gap_up_count = 0
|
| 75 |
+
gap_down_count = 0
|
| 76 |
+
for result in results:
|
| 77 |
+
classes = result.boxes.cls
|
| 78 |
+
for cls in classes:
|
| 79 |
+
if cls == 0:
|
| 80 |
+
gap_down_count += 1
|
| 81 |
+
elif cls == 1:
|
| 82 |
+
gap_up_count += 1
|
| 83 |
+
annotated_image = result.plot()
|
| 84 |
+
return annotated_image, gap_up_count, gap_down_count
|
| 85 |
+
|
| 86 |
+
def detect_gap_patterns(symbol):
|
| 87 |
+
"""
|
| 88 |
+
Main function to fetch data, generate charts, and detect GAP patterns in near-real-time.
|
| 89 |
+
"""
|
| 90 |
+
model = YOLO("/content/best.pt") # Load model once outside the loop
|
| 91 |
+
while True:
|
| 92 |
+
data = get_stock_candlestick_data(symbol)
|
| 93 |
+
if not data:
|
| 94 |
+
print("Failed to fetch data. Retrying in 15 seconds.")
|
| 95 |
+
time.sleep(15)
|
| 96 |
+
continue # Retry instead of exiting
|
| 97 |
+
|
| 98 |
+
df = process_stock_candlestick_data(data)
|
| 99 |
+
generate_candlestick_chart(df, n=50) # Generate chart with last 50 candles
|
| 100 |
+
annotated_image, gap_up_count, gap_down_count = yolo_model("candlestick.png", model)
|
| 101 |
+
cv2.imwrite("annotated_output.png", annotated_image)
|
| 102 |
+
yield "annotated_output.png", gap_up_count, gap_down_count
|
| 103 |
+
time.sleep(15) # Wait 15 seconds to respect API rate limits
|
| 104 |
+
|
| 105 |
+
# Gradio Interface
|
| 106 |
+
with gr.Blocks() as demo:
|
| 107 |
+
gr.Markdown("# GAP Pattern Detection in Real-Time Stock Charts")
|
| 108 |
+
gr.Markdown("Enter a stock symbol (e.g., AAPL) to detect GAP UP and GAP DOWN patterns in near-real-time candlestick charts.")
|
| 109 |
+
|
| 110 |
+
with gr.Row():
|
| 111 |
+
symbol_input = gr.Textbox(label="Stock Symbol", placeholder="Enter a stock symbol (e.g., AAPL)")
|
| 112 |
+
submit_button = gr.Button("Start Real-Time Detection")
|
| 113 |
+
|
| 114 |
+
with gr.Row():
|
| 115 |
+
output_image = gr.Image(label="Annotated Candlestick Chart")
|
| 116 |
+
gap_up_output = gr.Textbox(label="GAP UP Count")
|
| 117 |
+
gap_down_output = gr.Textbox(label="GAP DOWN Count")
|
| 118 |
+
|
| 119 |
+
# Start real-time detection when the button is clicked
|
| 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(share=True, debug=True)
|