AlanRex commited on
Commit
30035b6
·
1 Parent(s): ec48a74

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -37
app.py CHANGED
@@ -215,51 +215,74 @@ def calculate_volume_profile(df, num_bins=50):
215
 
216
  return bin_edges, hist, price_centers
217
 
218
- # === 修正後的 get_business_climate_data 函式 ===
219
  def get_business_climate_data():
220
- """從國發會網站抓取真實景氣燈號資料"""
221
  try:
222
- url = 'https://www.ndc.gov.tw/Content_List.aspx?n=84A4AFB5532512F5'
223
- # 發送 GET 請求
224
- response = requests.get(url, timeout=10)
225
- response.raise_for_status() # 如果請求失敗,會拋出 HTTPError
226
-
227
- # 使用 pandas 讀取 HTML 表格
228
- df_list = pd.read_html(response.text, match='景氣對策信號綜合判斷分數及構成項目')
229
-
230
- if not df_list:
231
- print("未在網頁中找到景氣對策信號表格。")
232
  return pd.DataFrame()
233
-
234
- df = df_list[0]
235
-
236
- # 數據清理
237
- df.columns = df.iloc[0] # 將第一行作為標題
238
- df = df.iloc[1:]
239
- df = df.reset_index(drop=True)
240
-
241
- # 重新命名欄位以便操作
242
- df = df.rename(columns={'年月': 'Date', '綜合判斷分數': 'Index'})
243
-
244
- # 格式化日期
245
- df['Date'] = df['Date'].apply(lambda x: datetime.strptime(str(x), '%Y.%m'))
246
-
247
- # 轉換數值
248
- df['Index'] = pd.to_numeric(df['Index'], errors='coerce')
249
- df = df.dropna(subset=['Index'])
250
-
251
- return df.sort_values('Date', ascending=True)
 
 
 
252
 
253
  except Exception as e:
254
- print(f"Error fetching business climate data: {e}")
255
  return pd.DataFrame()
256
 
257
- # 新增: 模擬的PMI數據獲取函式
258
  def get_pmi_data():
259
- dates = pd.date_range(end=datetime.now(), periods=24, freq='MS')
260
- pmi_values = np.random.uniform(40, 60, size=24)
261
- df = pd.DataFrame({'Date': dates, 'Index': pmi_values})
262
- return df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263
 
264
  # 建立 Dash 應用程式
265
  app = dash.Dash(__name__, suppress_callback_exceptions=True)
 
215
 
216
  return bin_edges, hist, price_centers
217
 
 
218
  def get_business_climate_data():
219
+ """獲取台灣景氣燈號資料"""
220
  try:
221
+ # 檢查檔案是否存在
222
+ if not os.path.exists('business_climate.csv'):
223
+ print("business_climate.csv 檔案不存在")
 
 
 
 
 
 
 
224
  return pd.DataFrame()
225
+
226
+ # 讀取CSV檔案,假設列名為 Date 和 Index
227
+ df = pd.read_csv('business_climate.csv')
228
+
229
+ # 檢查列名並調整
230
+ if 'Date' not in df.columns:
231
+ # 如果第一列是日期,重新命名
232
+ df.columns = ['Date', 'Index'] if len(df.columns) == 2 else df.columns
233
+
234
+ # 轉換日期格式 (處理 YYYY-MM 格式)
235
+ if 'Date' in df.columns:
236
+ try:
237
+ # 如果是 YYYY-MM 格式,轉換為日期
238
+ df['Date'] = pd.to_datetime(df['Date'] + '-01', format='%Y-%m-%d', errors='coerce')
239
+ except:
240
+ df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
241
+
242
+ # 移除日期轉換失敗的行
243
+ df = df.dropna(subset=['Date'])
244
+
245
+ print(f"成功讀取景氣燈號資料:{len(df)} 筆記錄")
246
+ return df
247
 
248
  except Exception as e:
249
+ print(f"無法獲取景氣燈號資料: {str(e)}")
250
  return pd.DataFrame()
251
 
 
252
  def get_pmi_data():
253
+ """獲取台灣 PMI 資料"""
254
+ try:
255
+ # 檢查檔案是否存在
256
+ if not os.path.exists('taiwan_pmi.csv'):
257
+ print("taiwan_pmi.csv 檔案不存在")
258
+ return pd.DataFrame()
259
+
260
+ # 讀取CSV檔案
261
+ df = pd.read_csv('taiwan_pmi.csv')
262
+
263
+ # 檢查列名並調整 (處理 DATE/INDEX 或其他可能的列名)
264
+ if 'DATE' in df.columns:
265
+ df = df.rename(columns={'DATE': 'Date', 'INDEX': 'Index'})
266
+ elif len(df.columns) == 2:
267
+ df.columns = ['Date', 'Index']
268
+
269
+ # 轉換日期格式
270
+ if 'Date' in df.columns:
271
+ try:
272
+ # 如果是 YYYY-MM 格式,轉換為日期
273
+ df['Date'] = pd.to_datetime(df['Date'] + '-01', format='%Y-%m-%d', errors='coerce')
274
+ except:
275
+ df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
276
+
277
+ # 移除日期轉換失敗的行
278
+ df = df.dropna(subset=['Date'])
279
+
280
+ print(f"成功讀取 PMI 資料:{len(df)} 筆記錄")
281
+ return df
282
+
283
+ except Exception as e:
284
+ print(f"無法獲取 PMI 資料: {str(e)}")
285
+ return pd.DataFrame()
286
 
287
  # 建立 Dash 應用程式
288
  app = dash.Dash(__name__, suppress_callback_exceptions=True)