Shaikat01 commited on
Commit
2fe0dc5
Β·
verified Β·
1 Parent(s): 00421ea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -15
app.py CHANGED
@@ -44,38 +44,61 @@ 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 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
@@ -83,7 +106,6 @@ def fetch_stock_data(ticker, days=365):
83
  except Exception as e:
84
  return None, str(e)
85
 
86
-
87
  def make_arima_forecast(data, days):
88
  """Make ARIMA forecast"""
89
  try:
 
44
 
45
  def fetch_stock_data(ticker, days=365):
46
  """
47
+ Fetch stock data from a local CSV (handles multi-row headers)
48
+ or downloads from Yahoo Finance if not found.
49
+ Returns last `days` of data with standardized 'Price' column.
50
  """
51
  try:
52
  filename = f"{ticker.upper()}.csv"
53
  file_path = os.path.join(os.getcwd(), filename)
54
 
55
+ # βœ… Load local dataset if it exists
56
+ if os.path.exists(file_path):
57
+ print(f"πŸ“‚ Loading local dataset: {filename}")
58
 
59
+ # Try reading while skipping bad header rows
60
+ df = pd.read_csv(file_path, skiprows=2) # skip first two rows ("Ticker", "Date" lines)
61
+ df.rename(columns=lambda c: c.strip().lower(), inplace=True)
62
 
63
+ if 'date' not in df.columns:
64
+ # Maybe pandas treated first column as unnamed
65
+ df.rename(columns={df.columns[0]: 'date'}, inplace=True)
66
+
67
+ else:
68
+ print(f"🌐 Downloading {ticker} data from Yahoo Finance...")
69
+ end_date = datetime.now()
70
+ start_date = end_date - timedelta(days=days * 2)
71
+ df = yf.download(ticker, start=start_date, end=end_date, progress=False)
72
+
73
+ if df.empty:
74
+ return None, f"No data found for ticker: {ticker}"
75
+
76
+ df.to_csv(file_path)
77
+ print(f"πŸ’Ύ Saved downloaded dataset to: {file_path}")
78
+ df.reset_index(inplace=True)
79
+ df.rename(columns=lambda c: c.strip().lower(), inplace=True)
80
+
81
+ # βœ… Identify columns
82
  date_col = next((c for c in df.columns if 'date' in c or 'time' in c), None)
83
  close_col = next((c for c in df.columns if 'close' in c), None)
84
+ price_col = 'price' if 'price' in df.columns else close_col
85
 
86
+ if not date_col or not price_col:
87
+ return None, f"Could not detect date or price/close column in {filename}"
88
 
89
+ # βœ… Clean up and format
90
+ df[date_col] = pd.to_datetime(df[date_col], errors='coerce')
91
+ df.dropna(subset=[date_col, price_col], inplace=True)
92
  df.set_index(date_col, inplace=True)
93
  df.sort_index(inplace=True)
94
 
95
+ # βœ… Keep last `days` of data
96
  end_date = df.index.max()
97
  start_date = end_date - timedelta(days=days)
98
  df = df.loc[df.index >= start_date]
99
 
100
+ # βœ… Final column cleanup
101
+ df = df[[price_col]].copy()
102
  df.columns = ['Price']
103
 
104
  return df, None
 
106
  except Exception as e:
107
  return None, str(e)
108
 
 
109
  def make_arima_forecast(data, days):
110
  """Make ARIMA forecast"""
111
  try: