S6six commited on
Commit
1753e95
·
1 Parent(s): 7c513b0

Force update README python_version to 3.10 and include other changes

Browse files
Files changed (3) hide show
  1. app.py +11 -24
  2. requirements.txt +0 -1
  3. src/data_fetcher.py +4 -7
app.py CHANGED
@@ -10,7 +10,7 @@ import base64
10
 
11
  # Add src directory to path to import modules
12
  module_path = os.path.abspath(os.path.join('.'))
13
- if module_path not in sys.path:
14
  sys.path.append(module_path)
15
 
16
  # Import functions from your src directory
@@ -29,7 +29,7 @@ except ImportError as e:
29
 
30
  # --- Data Fetching and Processing Logic ---
31
  # (Similar to the Streamlit version, but adapted for Gradio outputs)
32
- def perform_analysis(ticker_symbol, start_date_str, end_date_str): # Renamed date inputs
33
  """Fetches data, analyzes sentiment, merges, and prepares outputs for Gradio."""
34
  if not ticker_symbol:
35
  return None, "Please enter a stock ticker.", None, None, None
@@ -39,15 +39,11 @@ def perform_analysis(ticker_symbol, start_date_str, end_date_str): # Renamed dat
39
  if not news_key:
40
  return None, "Error: NEWS_API_KEY not found in .env file. Cannot fetch news.", None, None, None
41
 
42
- # Validate and parse date strings
43
- try:
44
- start_date_obj = datetime.strptime(start_date_str, '%Y-%m-%d').date()
45
- end_date_obj = datetime.strptime(end_date_str, '%Y-%m-%d').date()
46
- except ValueError:
47
- return None, "Error: Invalid date format. Please use YYYY-MM-DD.", None, None, None
48
 
49
-
50
- if start_date_obj >= end_date_obj:
51
  return None, "Error: Start date must be before end date.", None, None, None
52
 
53
  status_updates = f"Fetching data for {ticker_symbol} from {start_date_str} to {end_date_str}...\n"
@@ -211,9 +207,8 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
211
  with gr.Row():
212
  with gr.Column(scale=1):
213
  ticker_input = gr.Textbox(label="Stock Ticker", value="AAPL", placeholder="e.g., AAPL, GOOGL")
214
- # Use Textbox for dates, value should be string
215
- start_date_input = gr.Textbox(label="Start Date (YYYY-MM-DD)", value=(datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d'))
216
- end_date_input = gr.Textbox(label="End Date (YYYY-MM-DD)", value=datetime.now().strftime('%Y-%m-%d'))
217
  analyze_button = gr.Button("Analyze", variant="primary")
218
  status_output = gr.Textbox(label="Analysis Status", lines=5, interactive=False)
219
  # Optional: Add download button for the merged data
@@ -228,17 +223,9 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
228
  # Hidden state to store the merged dataframe for download
229
  merged_df_state = gr.State(None)
230
 
231
- def run_analysis_and_prepare_download(ticker, start_date_str, end_date_str): # Use string names
232
  """Wrapper function to run analysis and prepare CSV for download."""
233
- # Parse dates inside the wrapper or ensure perform_analysis handles strings robustly
234
- try:
235
- start_date_obj = datetime.strptime(start_date_str, '%Y-%m-%d').date()
236
- end_date_obj = datetime.strptime(end_date_str, '%Y-%m-%d').date()
237
- except ValueError:
238
- # Handle invalid date format input from textbox
239
- return None, "Error: Invalid date format. Please use YYYY-MM-DD.", None, "Error processing dates.", None, None
240
-
241
- plot, insights, news, status, merged_df = perform_analysis(ticker, start_date_str, end_date_str) # Pass strings
242
 
243
  csv_path = None
244
  if merged_df is not None and not merged_df.empty:
@@ -251,7 +238,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
251
 
252
  analyze_button.click(
253
  fn=run_analysis_and_prepare_download,
254
- inputs=[ticker_input, start_date_input, end_date_input], # Inputs are now textboxes
255
  outputs=[plot_output, insights_output, news_output, status_output, merged_df_state, download_data] # Update state and file output
256
  )
257
 
 
10
 
11
  # Add src directory to path to import modules
12
  module_path = os.path.abspath(os.path.join('.'))
13
+ if (module_path not in sys.path):
14
  sys.path.append(module_path)
15
 
16
  # Import functions from your src directory
 
29
 
30
  # --- Data Fetching and Processing Logic ---
31
  # (Similar to the Streamlit version, but adapted for Gradio outputs)
32
+ def perform_analysis(ticker_symbol, start_date, end_date):
33
  """Fetches data, analyzes sentiment, merges, and prepares outputs for Gradio."""
34
  if not ticker_symbol:
35
  return None, "Please enter a stock ticker.", None, None, None
 
39
  if not news_key:
40
  return None, "Error: NEWS_API_KEY not found in .env file. Cannot fetch news.", None, None, None
41
 
42
+ # Convert Gradio date objects to strings
43
+ start_date_str = start_date.strftime('%Y-%m-%d')
44
+ end_date_str = end_date.strftime('%Y-%m-%d')
 
 
 
45
 
46
+ if start_date >= end_date:
 
47
  return None, "Error: Start date must be before end date.", None, None, None
48
 
49
  status_updates = f"Fetching data for {ticker_symbol} from {start_date_str} to {end_date_str}...\n"
 
207
  with gr.Row():
208
  with gr.Column(scale=1):
209
  ticker_input = gr.Textbox(label="Stock Ticker", value="AAPL", placeholder="e.g., AAPL, GOOGL")
210
+ start_date_input = gr.Date(label="Start Date", value=(datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d'))
211
+ end_date_input = gr.Date(label="End Date", value=datetime.now().strftime('%Y-%m-%d'))
 
212
  analyze_button = gr.Button("Analyze", variant="primary")
213
  status_output = gr.Textbox(label="Analysis Status", lines=5, interactive=False)
214
  # Optional: Add download button for the merged data
 
223
  # Hidden state to store the merged dataframe for download
224
  merged_df_state = gr.State(None)
225
 
226
+ def run_analysis_and_prepare_download(ticker, start_date, end_date):
227
  """Wrapper function to run analysis and prepare CSV for download."""
228
+ plot, insights, news, status, merged_df = perform_analysis(ticker, start_date, end_date)
 
 
 
 
 
 
 
 
229
 
230
  csv_path = None
231
  if merged_df is not None and not merged_df.empty:
 
238
 
239
  analyze_button.click(
240
  fn=run_analysis_and_prepare_download,
241
+ inputs=[ticker_input, start_date_input, end_date_input],
242
  outputs=[plot_output, insights_output, news_output, status_output, merged_df_state, download_data] # Update state and file output
243
  )
244
 
requirements.txt CHANGED
@@ -7,5 +7,4 @@ transformers
7
  scikit-learn
8
  matplotlib
9
  nltk
10
- python-dotenv
11
  gradio
 
7
  scikit-learn
8
  matplotlib
9
  nltk
 
10
  gradio
src/data_fetcher.py CHANGED
@@ -2,17 +2,14 @@ import yfinance as yf
2
  import pandas as pd
3
  from newsapi import NewsApiClient
4
  import os
5
- from dotenv import load_dotenv
6
  from datetime import datetime, timedelta
7
 
8
  def load_api_keys():
9
- """Loads API keys from the .env file."""
10
- load_dotenv()
11
  news_api_key = os.getenv("NEWS_API_KEY")
12
- alpha_vantage_key = os.getenv("ALPHA_VANTAGE_KEY") # Add ALPHA_VANTAGE_KEY=YOUR_KEY to .env if using
13
  if not news_api_key:
14
- print("Warning: NEWS_API_KEY not found in .env file.")
15
- # Add similar check for alpha_vantage_key if you plan to use it
16
  return news_api_key, alpha_vantage_key
17
 
18
  def get_stock_data(ticker, start_date, end_date):
@@ -60,7 +57,7 @@ def get_news_articles(query, from_date, to_date, language='en', sort_by='relevan
60
  print(f"Date range: {from_date} to {to_date}") # Added print
61
  news_api_key, _ = load_api_keys()
62
  if not news_api_key:
63
- print("Error: NewsAPI key not available. Cannot fetch news.") # Made error clearer
64
  return None
65
 
66
  try:
 
2
  import pandas as pd
3
  from newsapi import NewsApiClient
4
  import os
 
5
  from datetime import datetime, timedelta
6
 
7
  def load_api_keys():
8
+ """Loads API keys directly from environment variables."""
 
9
  news_api_key = os.getenv("NEWS_API_KEY")
10
+ alpha_vantage_key = os.getenv("ALPHA_VANTAGE_KEY")
11
  if not news_api_key:
12
+ print("Warning: NEWS_API_KEY environment variable not found.")
 
13
  return news_api_key, alpha_vantage_key
14
 
15
  def get_stock_data(ticker, start_date, end_date):
 
57
  print(f"Date range: {from_date} to {to_date}") # Added print
58
  news_api_key, _ = load_api_keys()
59
  if not news_api_key:
60
+ print("Error: NewsAPI key not available in environment variables. Cannot fetch news.")
61
  return None
62
 
63
  try: