iT邦幫忙

2025 iThome 鐵人賽

DAY 14
0
AI & Data

從網路爬蟲到資料洞察的應用系列 第 14

將多月資料合併成一個 DataFrame

  • 分享至 

  • xImage
  •  

那今天來做多個月合併吧。

程式碼

all_data = []
current_year, current_month = today.year, today.month

for year, month in stock._month_year_iter(start_month, start_year, current_month, current_year):
    print(f"正在抓取 {year} 年 {month} 月的資料...")
    monthly_data = stock.fetch(year, month)
    if monthly_data:
        # 將 twstock 的 namedtuple 轉換為字典列表
        data_list = [d._asdict() for d in monthly_data]
        all_data.extend(data_list)

詳細拆解

  1. 準備一個空清單來存資料
all_data = []
  • 我們會把每個月的交易資料逐一加進來。
  • 最後 all_data 會包含 6 個月(或你指定的數量)所有的交易日。
  1. 設定迴圈範圍
current_year, current_month = today.year, today.month
  • 這裡存放目前的年份與月份,等一下會跟起始年月搭配,決定要跑多少次迴圈。
  1. 使用 _month_year_iter 生成年月迭代器
for year, month in stock._month_year_iter(start_month, start_year, current_month, current_year):
  • _month_year_iter 是 twstock 內建的小工具,會依序產生「起始年月 → 結束年月」的範圍。
  • 例如:(2025, 4) → (2025, 9) 就會依序給出 (2025, 4)、(2025, 5)、…、(2025, 9)。
  1. 逐月抓取資料
monthly_data = stock.fetch(year, month)
  • stock.fetch(year, month) 會回傳該月份的股價資料。
  • 每天的資料會是一個 namedtuple,內容包括:日期、開盤價、收盤價、最高價、最低價、成交量等等。
  1. 把 namedtuple 轉成字典
data_list = [d._asdict() for d in monthly_data]
  • namedtuple 雖然能用「點」去取值(如 d.close),但不方便直接合併成表格。
  • _asdict() 可以把 namedtuple 轉換成字典,變成:
{
    'date': datetime.date(2025, 9, 24),
    'capacity': 10000000,
    'open': 600,
    'high': 610,
    'low': 595,
    'close': 605,
    ...
}
  • data_list 就是一個「字典的清單」。
  1. 累積到總清單
all_data.extend(data_list)
  • extend 會把 data_list 的所有元素加到 all_data 裡。
  • 執行完迴圈後,all_data 會包含所有月份的資料,等一下就能丟進 pd.DataFrame(all_data)。

總結

  • 先用 _month_year_iter 自動生成「月份清單」
  • 再用 fetch() 逐月抓取資料
  • 最後把結果轉換成字典,全部放到一個大清單 all_data
    那今天就先這樣。
    /images/emoticon/emoticon29.gif

上一篇
一次抓取多個月份的資料(迴圈組 URL)
下一篇
計算月平均價、月成交量
系列文
從網路爬蟲到資料洞察的應用16
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言