mobenta commited on
Commit
2f16ed3
·
verified ·
1 Parent(s): cbb1701

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -49
app.py CHANGED
@@ -1,28 +1,21 @@
1
  import torch
2
- import yfinance as yf
 
3
  import matplotlib.pyplot as plt
4
  import mplfinance as mpf
 
5
  from PIL import Image, ImageDraw, ImageFont
6
- import gradio as gr
7
  import datetime
8
- import logging
9
- from transformers import AutoProcessor, AutoModelForPreTraining
10
  import tempfile
11
- import os
12
- import spaces
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,7 +23,7 @@ def predict(image, input_text):
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,47 +130,23 @@ def create_stock_chart(data, ticker, filename='chart.png', timeframe='1d', indic
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,7 +155,6 @@ def gradio_interface(ticker1, ticker2, ticker3, ticker4, start_date, end_date, q
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,7 +166,23 @@ def gradio_interface(ticker1, ticker2, ticker3, ticker4, start_date, end_date, q
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")
 
1
  import torch
2
+ import gradio as gr
3
+ from transformers import AutoProcessor, AutoModelForPreTraining
4
  import matplotlib.pyplot as plt
5
  import mplfinance as mpf
6
+ import yfinance as yf
7
  from PIL import Image, ImageDraw, ImageFont
 
8
  import datetime
 
 
9
  import tempfile
10
+ import logging
 
 
 
 
 
11
 
12
  # Configure logging
13
  logging.basicConfig(filename='debug.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
14
 
15
+ # Load the model and processor
16
  processor = AutoProcessor.from_pretrained("mobenta/chart_analysis")
17
  model = AutoModelForPreTraining.from_pretrained("mobenta/chart_analysis")
18
 
 
19
  def predict(image, input_text):
20
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
21
  model.to(device)
 
23
  image = image.convert("RGB")
24
  inputs = processor(text=input_text, images=image, return_tensors="pt")
25
  inputs = {k: v.to(device) for k, v in inputs.items()}
26
+
27
  prompt_length = inputs['input_ids'].shape[1]
28
  generate_ids = model.generate(**inputs, max_new_tokens=512)
29
  output_text = processor.batch_decode(generate_ids[:, prompt_length:], skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
 
130
  resized_image = image.resize(new_size, Image.LANCZOS)
131
  resized_image.save(filename)
132
 
133
+ logging.debug(f"Resized image saved to {filename}")
134
+ return filename
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  except Exception as e:
136
+ logging.error(f"Error creating stock chart: {e}")
137
  raise
138
 
139
  def gradio_interface(ticker1, ticker2, ticker3, ticker4, start_date, end_date, query, analysis_type, interval, indicators):
140
  try:
 
 
 
141
  chart_paths = []
142
+ tickers = [ticker1, ticker2, ticker3, ticker4]
143
 
144
+ for ticker in tickers:
145
+ if ticker.strip():
146
+ data = fetch_stock_data(ticker, start_date, end_date, interval)
147
+ chart_path = f"{ticker}_chart.png"
148
+ create_stock_chart(data, ticker, filename=chart_path, timeframe=interval, indicators=indicators)
149
+ chart_paths.append(chart_path)
 
150
 
151
  if analysis_type == 'Comparative Analysis' and len(chart_paths) > 1:
152
  with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as temp_combined_chart:
 
155
  insights = predict(Image.open(combined_chart_path), query)
156
  return insights, combined_chart_path
157
 
 
158
  if chart_paths:
159
  insights = predict(Image.open(chart_paths[0]), query)
160
  return insights, chart_paths[0]
 
166
 
167
  def gradio_app():
168
  with gr.Blocks() as demo:
169
+ gr.Markdown("""
170
+ ## 📈Stock Analysis Dashboard
171
+
172
+ 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:
173
+
174
+ 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.
175
+
176
+ 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.
177
+
178
+ 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.
179
+
180
+ 4. **Logging and Debugging**: Detailed logging helps in debugging and tracking the application's processes.
181
+
182
+ 5. **Enhanced Image Processing**: The app adds financial metrics and annotations to the generated charts, ensuring clear presentation of data.
183
+
184
+ This tool leverages the Paligema model to provide detailed insights into stock market trends, offering an interactive and educational experience for users.
185
+ """)
186
 
187
  with gr.Row():
188
  ticker1 = gr.Textbox(label="Primary Ticker", value="GC=F")