Shaikat01 commited on
Commit
00421ea
·
verified ·
1 Parent(s): 7087e03

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -21
app.py CHANGED
@@ -44,43 +44,38 @@ SEQ_LENGTH = 60 # Should match your training
44
 
45
  def fetch_stock_data(ticker, days=365):
46
  """
47
- Load stock data from a local CSV file in the project root folder.
48
- If the file doesn't exist, returns an error message.
49
-
50
- Parameters:
51
- ticker (str): Stock ticker symbol (used as filename prefix)
52
- days (int): Number of days of recent data to keep (optional)
53
-
54
- Returns:
55
- tuple: (DataFrame, error_message)
56
  """
57
  try:
58
- # Construct the file path (e.g., ./AAPL.csv)
59
  filename = f"{ticker.upper()}.csv"
60
  file_path = os.path.join(os.getcwd(), filename)
61
 
62
- # Check if file exists
63
  if not os.path.exists(file_path):
64
  return None, f"Dataset file not found in root folder: {filename}"
65
 
66
- # Load dataset
67
  df = pd.read_csv(file_path)
 
 
 
 
 
68
 
69
- # Ensure 'Date' and 'Close' columns exist
70
- if 'Date' not in df.columns or 'Close' not in df.columns:
71
- return None, f"File must contain 'Date' and 'Close' columns in {filename}"
72
 
73
- # Parse dates and set index
74
- df['Date'] = pd.to_datetime(df['Date'])
75
- df.set_index('Date', inplace=True)
 
76
 
77
- # Keep only recent `days`
78
  end_date = df.index.max()
79
  start_date = end_date - timedelta(days=days)
80
  df = df.loc[df.index >= start_date]
81
 
82
- # Rename column for consistency
83
- df = df[['Close']].copy()
84
  df.columns = ['Price']
85
 
86
  return df, None
 
44
 
45
  def fetch_stock_data(ticker, days=365):
46
  """
47
+ Load stock data from a local CSV file in the root folder.
48
+ Automatically detects 'Date' and 'Close' columns (case-insensitive).
 
 
 
 
 
 
 
49
  """
50
  try:
 
51
  filename = f"{ticker.upper()}.csv"
52
  file_path = os.path.join(os.getcwd(), filename)
53
 
 
54
  if not os.path.exists(file_path):
55
  return None, f"Dataset file not found in root folder: {filename}"
56
 
 
57
  df = pd.read_csv(file_path)
58
+ df.columns = [col.strip().lower() for col in df.columns] # normalize column names
59
+
60
+ # Try to identify date and close columns
61
+ date_col = next((c for c in df.columns if 'date' in c or 'time' in c), None)
62
+ close_col = next((c for c in df.columns if 'close' in c), None)
63
 
64
+ if not date_col or not close_col:
65
+ return None, f"File must contain a date-like and close-like column in {filename}"
 
66
 
67
+ # Convert to datetime and set index
68
+ df[date_col] = pd.to_datetime(df[date_col])
69
+ df.set_index(date_col, inplace=True)
70
+ df.sort_index(inplace=True)
71
 
72
+ # Keep last `days`
73
  end_date = df.index.max()
74
  start_date = end_date - timedelta(days=days)
75
  df = df.loc[df.index >= start_date]
76
 
77
+ # Keep only close price
78
+ df = df[[close_col]].copy()
79
  df.columns = ['Price']
80
 
81
  return df, None