<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>央行 &#8211; FinLab</title>
	<atom:link href="https://www.finlab.tw/tag/%E5%A4%AE%E8%A1%8C/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.finlab.tw</link>
	<description>深入淺出的量化投資，讓你在在茫茫股海中，找到專屬於自己的投資方法</description>
	<lastBuildDate>Thu, 03 Nov 2022 01:46:33 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.9</generator>

<image>
	<url>https://www.finlab.tw/wp-content/uploads/2020/07/favicon.png</url>
	<title>央行 &#8211; FinLab</title>
	<link>https://www.finlab.tw</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">179699571</site>	<item>
		<title>Python爬蟲教學｜ 財經數據｜台灣貨幣總計數 M1B &#038; M2</title>
		<link>https://www.finlab.tw/tw_monetary_aggregates_m1b_crawler/</link>
					<comments>https://www.finlab.tw/tw_monetary_aggregates_m1b_crawler/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Thu, 03 Nov 2022 01:43:39 +0000</pubDate>
				<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[總體經濟]]></category>
		<category><![CDATA[m1b]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[主計處]]></category>
		<category><![CDATA[台灣]]></category>
		<category><![CDATA[央行]]></category>
		<category><![CDATA[爬蟲]]></category>
		<category><![CDATA[貨幣總計數]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4792</guid>

					<description><![CDATA[全球經濟面臨空頭襲擊，資金行情被美國聯準會升息潮打擊，很多人說 2022 是總經盤， 牛市階段，個股棒棒開花，投資人反倒覺得總經不夠靈敏，而現今熊市時刻，覆巢之下無完卵 ，投資人開始注意總經的影響力。市面上有不錯的總經平台，如「財經Ｍ平方」提供數據圖表，可惜沒提供財經數據API的服務，若要使用總經數據，還是得自己想辦法，所幸有Python爬蟲可以幫我們解決需求。貨幣總計數M1B和M2象徵「流動資金」與「保守資金」的消長，或能幫助資金行情判斷，這篇文章將示範如何爬取M1B和M2的年增率。]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">全球經濟面臨空頭襲擊，資金行情被美國聯準會升息潮打擊，很多人說 2022 是總經盤， 牛市階段，個股棒棒開花，投資人反倒覺得總經不夠靈敏，而現今熊市時刻，覆巢之下無完卵 ，投資人開始注意總經的影響力。市面上有不錯的總經平台，如「<a href="https://www.macromicro.me/collections/11/tw-gdp-relative/133/tw-m1b-m2" target="_blank" rel="noopener">財經Ｍ平方</a>」提供數據圖表，可惜沒提供財經數據API的服務，若要使用總經數據，還是得自己想辦法，所幸有Python爬蟲可以幫我們解決需求。貨幣總計數M1B和M2象徵「流動資金」與「保守資金」的消長，或能幫助資金行情判斷，這篇文章將示範如何爬取M1B和M2的年增率。</p>



<h2>財經數據資料源</h2>



<p class="has-medium-font-size">貨幣總計數的資料最源頭來自台灣<a href="https://www.cbc.gov.tw/tw/lp-302-1.html" target="_blank" rel="noopener">中央銀行的新聞稿</a>，每月23-30號間發布「<a href="https://www.cbc.gov.tw/tw/cp-302-155810-06170-1.html" target="_blank" rel="noopener">上月金融狀況</a>」，頁內有M1B和M2的年增率的表格資料。然而新聞稿區的早期資料不是那麼完全，網頁格式也變動多次，如果要在此爬蟲所有歷史資料，並非最佳解。</p>



<figure class="wp-block-image size-large"><img width="1024" height="622" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.25.25-1024x622.png" alt="截圖 2022 11 03 上午8.25.25" class="wp-image-4793" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.25.25-1024x622.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.25.25-300x182.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.25.25-768x466.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.25.25-1536x933.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.25.25-2048x1244.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python爬蟲教學｜ 財經數據｜台灣貨幣總計數 M1B &amp; M2 1"><figcaption>央行每月金融情況新聞稿</figcaption></figure>



<p class="has-medium-font-size"><br>所幸 <a href="https://www.dgbas.gov.tw/point.asp?index=10" target="_blank" rel="noopener">行政院主計處</a> 也有M1B和M2的數據，而且看來是可以一次抓下JS圖表內的所有數據，會比央行省事省力的許多。然而不幸的是此資料並非完美，現在都已經2022/11/3了，主計處資料還停在8月數據，但中央銀行早在10/24就發布了，怎麼更新同步基調差那麼多？如果是10/31前公佈都還好，拖到11月就真的太慢了。<br>所以我們需要兩個Python爬蟲，一個爬主計處的財經數據歷史資料。一個爬中央銀行當月的貨幣總計數，作為之後更新最新資料使用。</p>



<h2>主計處Python爬蟲</h2>



<p class="has-medium-font-size">爬蟲開發的第一步是觀察網頁結構，如果資料是以html的table來呈現，那是用pandas的read_html，就非常好解析，據經驗，80％情況都是如此。然而如果不是table，就比較麻煩，若財經數據有直接渲染在網頁，可以用 Beatifulsoup 解析整份 html 檔，再定位標籤抓資料。<br>可以看到 <a href="https://www.dgbas.gov.tw/point.asp?index=10" target="_blank" rel="noopener">行政院主計處</a> 的最新M1B數據是7.55，我們可以在Chrome瀏覽器按右鍵選擇檢查，搜尋「7.55」放在哪邊？之後可以發現7.55出現在4個地方，然而table內只有一筆資料，由於我們要抓到歷史資料是放在圖表，圖表資料一般都放在&lt;scripttype type=&#8221;text/javascript&#8221;>標籤裡的變數，經過搜尋發現我們要把chartValue變數內的資料解析出來。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="682" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.26.47-1024x682.png" alt="截圖 2022 11 03 上午8.26.47" class="wp-image-4794" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.26.47-1024x682.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.26.47-300x200.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.26.47-768x511.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.26.47-1536x1022.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.26.47-2048x1363.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python爬蟲教學｜ 財經數據｜台灣貨幣總計數 M1B &amp; M2 2"><figcaption>行政院主計處M1B年增率</figcaption></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="490" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.38.35-1024x490.png" alt="截圖 2022 11 03 上午8.38.35" class="wp-image-4795" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.38.35-1024x490.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.38.35-300x143.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.38.35-768x367.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.38.35-1536x734.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午8.38.35-2048x979.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python爬蟲教學｜ 財經數據｜台灣貨幣總計數 M1B &amp; M2 3"></figure>



<h3>Python爬蟲程式範例</h3>



<p class="has-medium-font-size">流程和細節看程式註解，重點在BeautifulSoup網頁解析，和pandas如何產生目標時間序列。下列幾個要熟悉的工具說明。</p>



<ul class="has-medium-font-size"><li><a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" target="_blank" rel="noopener">BeautifulSoup</a></li><li><a href="https://pandas.pydata.org/docs/reference/api/pandas.date_range.html" target="_blank" rel="noopener">pandas.date_range</a></li><li><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.tseries.offsets.MonthEnd.html" target="_blank" rel="noopener">pandas.tseries.offsets.MonthEnd</a></li></ul>



<pre class="wp-block-code"><code lang="python" class="language-python">from bs4 import BeautifulSoup
import pandas as pd
import requests
from datetime import datetime


def crawl_history_from_dgbas():
    # 抓下網頁回傳資料
    response = requests.get('https://www.dgbas.gov.tw/point.asp?index=10')
    # 解析網頁
    parsed_file = BeautifulSoup(response.text)
    # 找出javascript區塊
    js_text = parsed_file.find_all('script', type="text/javascript")
    # 抓財經數據定位，資料為餘第3個javascript
    data = js_text[3].string

    # 文字資料定位，擷取數據部分，將js的日期型態Date.UTC取代成空白
    m1b = data[data.index('chartValue[6]') + len('chartValue[6]='):data.index(';\r\nchartValue[7]')].replace(
        'Date.UTC', '')
    # 將文字轉陣列
    eval_m1b = eval(m1b)
    # 取出數值，迴圈內d變數已被轉成空白，無意義
    m1b_values = [v for d, v in eval_m1b]

    # 重複上述動作，觀察chartValue內陣列定位，抓出M2數據
    m2 = data[data.index('chartValue[7]') + len('chartValue[7]='):data.index(';\r\nchartValue[8]')].replace(
        'Date.UTC', '')
    eval_m2 = eval(m2)
    m2_values = [v for d, v in eval_m2]
    
    # 日期處理，由於無法抓到即時公告日期，且央行公告日前每月不定，都在每月25號左右公告上月數據，為作業方便，目標將日期設為每月最後一天
    # 取出陣列內起始日期、結束日期
    start_date = eval_m1b[0][0]
    end_date = eval_m1b[-1][0]
    # 將日期格式轉為 pandas date_range 的參數格式，產生每月日期序列
    start = f'{start_date[0]}-{start_date[1]}-{start_date[2]}'
    end = f'{end_date[0]}-{end_date[1] + 1}-{end_date[2]}'
    # 日期序列為每月1日，為產生本月底公告去年數據的效果，使用tseries.offsets將日期後推
    dates = pd.date_range(start, end, freq='M') + pd.tseries.offsets.MonthEnd(2)
    
    # 產生m1b與m2數據，將數據併表
    m1b_df = pd.DataFrame({'stock_id': '貨幣總計數M1B', 'date': dates, '年增率(%)': m1b_values})
    m2_df = pd.DataFrame({'stock_id': '貨幣總計數M2', 'date': dates, '年增率(%)': m2_values})
    concat_df = pd.concat([m1b_df, m2_df])
    concat_df = concat_df.set_index(['stock_id', 'date'])
    return concat_df</code></pre>



<p></p>



<h3>Python爬蟲輸出結果</h3>



<figure class="wp-block-image size-full"><img loading="lazy" width="534" height="618" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.08.26.png" alt="截圖 2022 11 03 上午9.08.26" class="wp-image-4796" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.08.26.png 534w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.08.26-259x300.png 259w" sizes="(max-width: 534px) 100vw, 534px" title="Python爬蟲教學｜ 財經數據｜台灣貨幣總計數 M1B &amp; M2 4"></figure>



<h2>中央銀行Python爬蟲</h2>



<p class="has-medium-font-size">這個爬蟲要分兩步驟，首先由於每月金融情況新聞稿的連結沒有規律，所以要先解析<a href="https://www.cbc.gov.tw/tw/lp-302-1.html" target="_blank" rel="noopener">最新消息的>新聞稿的首頁</a>，取出近月新聞稿的超連結，再將連結傳到 python requests 取得表格數據，之後再將資料稍微整理成前面主計處爬蟲的資料格式。<br>另外要注意若每月25號前就執行此爬蟲，可能會有當月資料還沒公告的問題，所以要加上例外狀況處理，回傳一個空的dataframe。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="948" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.24.01-1024x948.png" alt="截圖 2022 11 03 上午9.24.01" class="wp-image-4797" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.24.01-1024x948.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.24.01-300x278.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.24.01-768x711.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.24.01-1536x1422.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-03-上午9.24.01.png 1657w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python爬蟲教學｜ 財經數據｜台灣貨幣總計數 M1B &amp; M2 5"></figure>



<h3>Python爬蟲程式範例</h3>



<pre class="wp-block-code"><code lang="python" class="language-python">def central_bank_crawl():
    
    # 資料目標日期，轉成民國型態的上月日期
    now = datetime.now()
    year = now.year - 1911
    month = (now.month + 10) % 12 + 1
    if month == 12:
        year -= 1
    
    # 解析出最新消息內近月金融情況新聞稿的超連結
    menu_response = requests.get('https://www.cbc.gov.tw/tw/lp-302-1.html')
    parsed_file = BeautifulSoup(menu_response.text)
    text = parsed_file.find('a', title=f"{year}年{month}月金融情況")

    # 沒資料則回傳空表
    if text is None:
        return pd.DataFrame()

    # 取出超連結
    href = text['href']
    
    # read_html 解析表格數據
    report_response = requests.get(f'https://www.cbc.gov.tw/{href}')
    report_df = pd.read_html(report_response.text)[0]
    report_df.columns = report_df.columns.get_level_values(1)
    report_df = report_df.iloc[:, :3]
    report_df = report_df.rename(columns={'項 目': 'stock_id', '年增率': '年增率(%)'})
    report_df = report_df[['stock_id', '年增率(%)']]
    report_df['date'] = datetime(now.year, now.month, 1) + pd.tseries.offsets.MonthEnd(1)
    report_df = report_df.set_index(['stock_id', 'date'])
    return report_df
</code></pre>



<p></p>



<h2>結論</h2>



<p class="has-medium-font-size"><a href="https://colab.research.google.com/drive/1RIp8diM2WQ2NFjVFGiS9fr3etoavqvB0?usp=sharing" target="_blank" rel="noopener">colab程式範例</a><br>這個爬蟲和證交所那類好爬的表格與穩定資料相比，有一些要注意的坑，處理上也比較多層，所以特別記錄一下。行政院主計處和央行還有許多總經數據，如果你有需求，可以自己用上述範例練習抓抓看，或直接使用 <a href="https://ai.finlab.tw/database#%E8%B2%A8%E5%B9%A3%E7%B8%BD%E8%A8%88%E6%95%B8%E5%B9%B4%E5%A2%9E%E7%8E%87" target="_blank" rel="noopener">FinLab資料庫</a> 來抓喔。</p>



<p class="has-medium-font-size">如果你對爬蟲想知道更多，可參考我們其他教學文章</p>



<p class="has-medium-font-size"><a href="https://www.finlab.tw/%e8%b6%85%e7%b0%a1%e5%96%ae%e5%8f%b0%e8%82%a1%e6%af%8f%e6%97%a5%e7%88%ac%e8%9f%b2%e6%95%99%e5%ad%b8/">超簡單台股每日爬蟲教學</a><br><a href="https://www.finlab.tw/%e8%b6%85%e7%b0%a1%e5%96%ae%e7%94%a8python%e6%8a%93%e5%8f%96%e6%af%8f%e6%9c%88%e7%87%9f%e6%94%b6/">超簡單用python抓取每月營收</a><br><a href="https://www.finlab.tw/%e4%b8%89%e5%a4%a7%e6%b3%95%e4%ba%ba%e7%88%ac%e8%9f%b2/">三大法人爬蟲：Python實作教學</a><br><a href="https://www.finlab.tw/%e7%b0%a1%e5%96%aepython%e4%b8%8a%e6%ab%83%e8%b3%87%e6%96%99%e7%88%ac%e8%9f%b2%e5%af%a6%e5%81%9a/">python上櫃資料爬蟲輕鬆做</a><br><a href="https://www.finlab.tw/python-%e8%b2%a1%e5%a0%b1%e7%88%ac%e8%9f%b2-1-%e7%b6%9c%e5%90%88%e6%90%8d%e7%9b%8a%e8%a1%a8/">財報爬蟲超簡單 – 用Python一次抓綜合損益、資產負債、營利分析</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/tw_monetary_aggregates_m1b_crawler/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4792</post-id>	</item>
	</channel>
</rss>
