Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,5 +1,3 @@
|
|
1 |
-
|
2 |
-
|
3 |
import torch
|
4 |
import yfinance as yf
|
5 |
import matplotlib.pyplot as plt
|
@@ -15,13 +13,16 @@ import spaces
|
|
15 |
import pandas as pd
|
16 |
|
17 |
|
|
|
|
|
18 |
# Configure logging
|
19 |
logging.basicConfig(filename='debug.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
|
20 |
|
21 |
-
# Load the model and processor
|
22 |
processor = AutoProcessor.from_pretrained("mobenta/chart_analysis")
|
23 |
model = AutoModelForPreTraining.from_pretrained("mobenta/chart_analysis")
|
24 |
|
|
|
25 |
def predict(image, input_text):
|
26 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
27 |
model.to(device)
|
@@ -29,7 +30,7 @@ def predict(image, input_text):
|
|
29 |
image = image.convert("RGB")
|
30 |
inputs = processor(text=input_text, images=image, return_tensors="pt")
|
31 |
inputs = {k: v.to(device) for k, v in inputs.items()}
|
32 |
-
|
33 |
prompt_length = inputs['input_ids'].shape[1]
|
34 |
generate_ids = model.generate(**inputs, max_new_tokens=512)
|
35 |
output_text = processor.batch_decode(generate_ids[:, prompt_length:], skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
@@ -136,23 +137,47 @@ def create_stock_chart(data, ticker, filename='chart.png', timeframe='1d', indic
|
|
136 |
resized_image = image.resize(new_size, Image.LANCZOS)
|
137 |
resized_image.save(filename)
|
138 |
|
139 |
-
logging.debug(f"Resized image saved to {filename}")
|
140 |
-
return filename
|
141 |
except Exception as e:
|
142 |
-
logging.error(f"Error creating
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
143 |
raise
|
144 |
|
145 |
def gradio_interface(ticker1, ticker2, ticker3, ticker4, start_date, end_date, query, analysis_type, interval, indicators):
|
146 |
try:
|
147 |
-
|
|
|
148 |
tickers = [ticker1, ticker2, ticker3, ticker4]
|
|
|
149 |
|
150 |
-
for ticker in tickers:
|
151 |
-
if ticker
|
152 |
-
data = fetch_stock_data(ticker, start_date, end_date, interval)
|
153 |
-
|
154 |
-
|
155 |
-
|
|
|
156 |
|
157 |
if analysis_type == 'Comparative Analysis' and len(chart_paths) > 1:
|
158 |
with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as temp_combined_chart:
|
@@ -161,6 +186,7 @@ def gradio_interface(ticker1, ticker2, ticker3, ticker4, start_date, end_date, q
|
|
161 |
insights = predict(Image.open(combined_chart_path), query)
|
162 |
return insights, combined_chart_path
|
163 |
|
|
|
164 |
if chart_paths:
|
165 |
insights = predict(Image.open(chart_paths[0]), query)
|
166 |
return insights, chart_paths[0]
|
@@ -172,23 +198,7 @@ def gradio_interface(ticker1, ticker2, ticker3, ticker4, start_date, end_date, q
|
|
172 |
|
173 |
def gradio_app():
|
174 |
with gr.Blocks() as demo:
|
175 |
-
gr.Markdown(""
|
176 |
-
## 📈Stock Analysis Dashboard
|
177 |
-
|
178 |
-
This application provides a comprehensive stock analysis tool that allows users to input up to four stock tickers, specify date ranges, and select various financial indicators. The core functionalities include:
|
179 |
-
|
180 |
-
1. **Data Fetching and Chart Creation**: Historical stock data is fetched from Yahoo Finance, and candlestick charts are generated with optional financial indicators like RSI, SMA, VWAP, and Bollinger Bands.
|
181 |
-
|
182 |
-
2. **Text Analysis and Insights Generation**: The application uses a pre-trained model based on the **Paligema** architecture to analyze the input chart and text query, generating insightful analysis based on the provided financial data and context.
|
183 |
-
|
184 |
-
3. **User Interface**: Users can interactively select stocks, date ranges, intervals, and indicators. The app also supports the analysis of single tickers or comparative analysis across multiple tickers.
|
185 |
-
|
186 |
-
4. **Logging and Debugging**: Detailed logging helps in debugging and tracking the application's processes.
|
187 |
-
|
188 |
-
5. **Enhanced Image Processing**: The app adds financial metrics and annotations to the generated charts, ensuring clear presentation of data.
|
189 |
-
|
190 |
-
This tool leverages the Paligema model to provide detailed insights into stock market trends, offering an interactive and educational experience for users.
|
191 |
-
""")
|
192 |
|
193 |
with gr.Row():
|
194 |
ticker1 = gr.Textbox(label="Primary Ticker", value="GC=F")
|
@@ -220,4 +230,3 @@ def gradio_app():
|
|
220 |
|
221 |
if __name__ == "__main__":
|
222 |
gradio_app()
|
223 |
-
|
|
|
|
|
|
|
1 |
import torch
|
2 |
import yfinance as yf
|
3 |
import matplotlib.pyplot as plt
|
|
|
13 |
import pandas as pd
|
14 |
|
15 |
|
16 |
+
|
17 |
+
|
18 |
# Configure logging
|
19 |
logging.basicConfig(filename='debug.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
|
20 |
|
21 |
+
# Load the chart_analysis model and processor
|
22 |
processor = AutoProcessor.from_pretrained("mobenta/chart_analysis")
|
23 |
model = AutoModelForPreTraining.from_pretrained("mobenta/chart_analysis")
|
24 |
|
25 |
+
@spaces.GPU
|
26 |
def predict(image, input_text):
|
27 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
28 |
model.to(device)
|
|
|
30 |
image = image.convert("RGB")
|
31 |
inputs = processor(text=input_text, images=image, return_tensors="pt")
|
32 |
inputs = {k: v.to(device) for k, v in inputs.items()}
|
33 |
+
|
34 |
prompt_length = inputs['input_ids'].shape[1]
|
35 |
generate_ids = model.generate(**inputs, max_new_tokens=512)
|
36 |
output_text = processor.batch_decode(generate_ids[:, prompt_length:], skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
|
|
137 |
resized_image = image.resize(new_size, Image.LANCZOS)
|
138 |
resized_image.save(filename)
|
139 |
|
140 |
+
logging.debug(f"Resized image with timeframe {timeframe} and ticker {ticker} saved to {filename}")
|
|
|
141 |
except Exception as e:
|
142 |
+
logging.error(f"Error creating or resizing chart: {e}")
|
143 |
+
raise
|
144 |
+
|
145 |
+
def combine_images(image_paths, output_path='combined_chart.png'):
|
146 |
+
try:
|
147 |
+
logging.debug(f"Combining images {image_paths} into {output_path}")
|
148 |
+
images = [Image.open(path) for path in image_paths]
|
149 |
+
|
150 |
+
# Calculate total width and max height for combined image
|
151 |
+
total_width = sum(img.width for img in images)
|
152 |
+
max_height = max(img.height for img in images)
|
153 |
+
|
154 |
+
combined_image = Image.new('RGB', (total_width, max_height))
|
155 |
+
x_offset = 0
|
156 |
+
for img in images:
|
157 |
+
combined_image.paste(img, (x_offset, 0))
|
158 |
+
x_offset += img.width
|
159 |
+
|
160 |
+
combined_image.save(output_path)
|
161 |
+
logging.debug(f"Combined image saved to {output_path}")
|
162 |
+
return output_path
|
163 |
+
except Exception as e:
|
164 |
+
logging.error(f"Error combining images: {e}")
|
165 |
raise
|
166 |
|
167 |
def gradio_interface(ticker1, ticker2, ticker3, ticker4, start_date, end_date, query, analysis_type, interval, indicators):
|
168 |
try:
|
169 |
+
logging.debug(f"Starting gradio_interface with tickers: {ticker1}, {ticker2}, {ticker3}, {ticker4}, start_date: {start_date}, end_date: {end_date}, query: {query}, analysis_type: {analysis_type}, interval: {interval}")
|
170 |
+
|
171 |
tickers = [ticker1, ticker2, ticker3, ticker4]
|
172 |
+
chart_paths = []
|
173 |
|
174 |
+
for i, ticker in enumerate(tickers):
|
175 |
+
if ticker:
|
176 |
+
data = fetch_stock_data(ticker, start=start_date, end=end_date, interval=interval)
|
177 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as temp_chart:
|
178 |
+
chart_path = temp_chart.name
|
179 |
+
create_stock_chart(data, ticker, chart_path, timeframe=interval, indicators=indicators)
|
180 |
+
chart_paths.append(chart_path)
|
181 |
|
182 |
if analysis_type == 'Comparative Analysis' and len(chart_paths) > 1:
|
183 |
with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as temp_combined_chart:
|
|
|
186 |
insights = predict(Image.open(combined_chart_path), query)
|
187 |
return insights, combined_chart_path
|
188 |
|
189 |
+
# No comparative analysis, just return the single chart
|
190 |
if chart_paths:
|
191 |
insights = predict(Image.open(chart_paths[0]), query)
|
192 |
return insights, chart_paths[0]
|
|
|
198 |
|
199 |
def gradio_app():
|
200 |
with gr.Blocks() as demo:
|
201 |
+
gr.Markdown("## Stock Analysis Dashboard")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
202 |
|
203 |
with gr.Row():
|
204 |
ticker1 = gr.Textbox(label="Primary Ticker", value="GC=F")
|
|
|
230 |
|
231 |
if __name__ == "__main__":
|
232 |
gradio_app()
|
|