<?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/%E7%B8%BD%E9%AB%94%E7%B6%93%E6%BF%9F/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>
		<item>
		<title>FRED總體經濟指標輕鬆抓&#124;美國汽車指標&#124;美股回測外掛教學</title>
		<link>https://www.finlab.tw/fred%e7%b8%bd%e9%ab%94%e7%b6%93%e6%bf%9f%e6%8c%87%e6%a8%99%e8%bc%95%e9%ac%86%e6%8a%93%e7%be%8e%e5%9c%8b%e6%b1%bd%e8%bb%8a%e6%8c%87%e6%a8%99%e7%be%8e%e8%82%a1%e5%9b%9e%e6%b8%ac%e5%a4%96%e6%8e%9b/</link>
					<comments>https://www.finlab.tw/fred%e7%b8%bd%e9%ab%94%e7%b6%93%e6%bf%9f%e6%8c%87%e6%a8%99%e8%bc%95%e9%ac%86%e6%8a%93%e7%be%8e%e5%9c%8b%e6%b1%bd%e8%bb%8a%e6%8c%87%e6%a8%99%e7%be%8e%e8%82%a1%e5%9b%9e%e6%b8%ac%e5%a4%96%e6%8e%9b/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Wed, 25 May 2022 06:32:32 +0000</pubDate>
				<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[VIP文章]]></category>
		<category><![CDATA[生產力]]></category>
		<category><![CDATA[股票策略]]></category>
		<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[VIP限定]]></category>
		<category><![CDATA[回測]]></category>
		<category><![CDATA[爬蟲]]></category>
		<category><![CDATA[總體經濟]]></category>
		<category><![CDATA[美股]]></category>
		<category><![CDATA[選股策略]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=3577</guid>

					<description><![CDATA[這篇文章涉及FRED API串接、美股股價爬蟲、總體經濟指標繪圖、指標解說、美股回測～一條龍帶大家走一遍，開展了FinLab系統更多的可能性。]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">財經資料項目很多，除了以台股為主的<a href="https://ai.finlab.tw/database" target="_blank" rel="noopener">FinLab資料庫</a>，有時可能還有其他外部資料使用的需求，像是總體經濟、美股、港股、加密貨幣等等。市面上已經有不少免費又好用的財經資料庫API服務，FinLab不會再重新造輪，而是讓大家可以串接外部資料做更多元的應用。</p>



<p class="has-medium-font-size">這一篇文章會教大家使用FRED總體經濟網站的API輕鬆地獲取總經資料，並示範運用外部資料打造自己的總體經濟分析儀表板與如何套用美股標的到FinLab回測系統。</p>



<h2>FRED API 操作說明</h2>



<p class="has-medium-font-size"><a href="https://fred.stlouisfed.org/" target="_blank" rel="noopener">FRED</a> (Federal Reserve Economic Data) 是路易斯聯邦儲備銀行研究部維護的數據庫，網站提供免費、多元、更新及時的總經資料庫、檢索、圖表功能。</p>



<p class="has-medium-font-size">和市面上的總經網站主要的差別是提供 FRED® API 服務，允許開發人員編寫程序和構建應用程式，可以根據數據源、發布、類別、系列和其他偏好自定義請求資料，比較方便程式人客製化使用資料。</p>



<h3>帳號註冊&amp;獲取API_KEY</h3>



<p class="has-medium-font-size">依照<a href="https://fred.stlouisfed.org/docs/api/api_key.html" target="_blank" rel="noopener">FRED官網指示</a>來操作，先註冊帳號，之後再申請API_KEY。</p>



<h3>API使用規則</h3>



<p class="has-medium-font-size">講解幾個最常用的功能，其他功能詳見<a href="https://fred.stlouisfed.org/docs/api/fred/" target="_blank" rel="noopener">FRED API</a>文檔操作:</p>



<h4>拉取總經指標的時間序列</h4>



<p class="has-medium-font-size"><a href="https://fred.stlouisfed.org/docs/api/fred/series_observations.html" target="_blank" rel="noopener">詳見fred/series/observations</a>，例如我們要抓取美股汽車庫存銷售比 (AISRSA) 的時間序列，可以從網址結構獲取series_id (AISRSA)，並使用python的requests.get() 抓取api回傳資料，我們可以將fred_api寫成下列function，只要替換不同series_id，就能獲取各式資料。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">import requests
import json

def get_fred_series_data(series_id='AISRSA',api_key=''):
    res=requests.get(f'https://api.stlouisfed.org/fred/series/observations?series_id={series_id}&amp;api_key={api_key}&amp;file_type=json')
    df=json.loads(res.text)
    return df


aisrsa = get_fred_series_data('AISRSA')</code></pre>



<figure class="wp-block-image size-large"><a href="https://fred.stlouisfed.org/series/AISRSA" target="_blank" rel="noopener"><img loading="lazy" width="1024" height="661" src="https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.30.25-1024x661.png" alt="截圖 2022 05 25 下午12.30.25" class="wp-image-3589" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.30.25-1024x661.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.30.25-300x194.png 300w, https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.30.25-768x495.png 768w, https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.30.25-1536x991.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.30.25-2048x1321.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="FRED總體經濟指標輕鬆抓|美國汽車指標|美股回測外掛教學 6"></a><figcaption>資料網址:<a href="https://fred.stlouisfed.org/series/AISRSA" target="_blank" rel="noopener">https://fred.stlouisfed.org/series/AISRSA</a></figcaption></figure>



<h4>依據索引拉取其他相關指標</h4>



<p class="has-medium-font-size">當我們獲得&#8221;汽庫存銷售比&#8221;時，我們還想獲得其他汽車相關數據，像是&#8221;美國國內汽車製造數 (DAUPSA)&#8221;和&#8221;汽車零售銷售數 (DAUTOSA)&#8221;，之後將指標疊圖，做更細部的汽車進銷存分析。要怎麼知道汽車的索引還有哪些指標呢？<br>我們可以從 <a href="https://fred.stlouisfed.org/docs/api/fred/series_categories.html" target="_blank" rel="noopener">fred/series/categories</a> 獲得 AISRSA的索引分類資料，從下圖的程式回傳資料可以得知，上層索引名稱為Motor Vehicles，id為32993。</p>



<pre class="wp-block-code"><code lang="python" class="language-python"># https://fred.stlouisfed.org/docs/api/fred/series_categories.html
# return: {'categories': [{'id': 32993, 'name': 'Motor Vehicles', 'parent_id': 33202}]}
series_id='AISRSA'
res=requests.get(f'https://api.stlouisfed.org/fred/series/categories?series_id={series_id}&amp;api_key={api_key}&amp;file_type=json')
df=json.loads(res.text)
df</code></pre>



<p class="has-medium-font-size">再透過 <a href="https://fred.stlouisfed.org/docs/api/fred/category_series.html" target="_blank" rel="noopener">fred/category/series</a> 對應Motor Vehicles的id32993，取得汽車類別有哪些其他相關指標。再將其他相關指標的id透過前頭提到的<a href="https://fred.stlouisfed.org/docs/api/fred/series_observations.html" target="_blank" rel="noopener">fred/series/observations</a>，取得時間序列資料。</p>



<pre class="wp-block-code"><code lang="python" class="language-python"># https://fred.stlouisfed.org/docs/api/fred/category_series.html

category_id=32993
res=requests.get(f'https://api.stlouisfed.org/fred/category/series?category_id={category_id}&amp;api_key={api_key}&amp;file_type=json')
df=json.loads(res.text)</code></pre>



<p class="has-medium-font-size">覺得檢索方法複雜的，也可以透過網頁點選獲取相關id。</p>



<figure class="wp-container-2 wp-block-gallery-1 wp-block-gallery has-nested-images columns-default is-cropped">
<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="666" data-id="3592" src="https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.53.17-1024x666.png" alt="截圖 2022 05 25 下午12.53.17" class="wp-image-3592" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.53.17-1024x666.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.53.17-300x195.png 300w, https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.53.17-768x499.png 768w, https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.53.17-1536x999.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.53.17-2048x1332.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="FRED總體經濟指標輕鬆抓|美國汽車指標|美股回測外掛教學 7"></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="674" data-id="3591" src="https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.56.43-1024x674.png" alt="截圖 2022 05 25 下午12.56.43" class="wp-image-3591" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.56.43-1024x674.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.56.43-300x198.png 300w, https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.56.43-768x506.png 768w, https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.56.43-1536x1012.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午12.56.43-2048x1349.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="FRED總體經濟指標輕鬆抓|美國汽車指標|美股回測外掛教學 8"></figure>
</figure>



<h2>資料應用範例</h2>



<h3>美國汽車相關總體經濟指標繪圖</h3>



<p class="has-medium-font-size">FRED只有單指標的繪圖，但透過api的資料結合plotly，我們可以很輕鬆客製化車用數據儀表板，像系的程式見文尾的colab檔案。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="321" src="https://www.finlab.tw/wp-content/uploads/2022/05/newplot-7-1024x321.png" alt="newplot 7" class="wp-image-3578" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/newplot-7-1024x321.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/05/newplot-7-300x94.png 300w, https://www.finlab.tw/wp-content/uploads/2022/05/newplot-7-768x241.png 768w, https://www.finlab.tw/wp-content/uploads/2022/05/newplot-7-1536x482.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/05/newplot-7.png 1673w" sizes="(max-width: 1024px) 100vw, 1024px" title="FRED總體經濟指標輕鬆抓|美國汽車指標|美股回測外掛教學 9"><figcaption>美國汽車總經指標圖</figcaption></figure>



<h3>何時買的到新車?</h3>



<p class="has-medium-font-size">總經數據週期長，很少拿來直接交易應用，但若到極端值，倒是可以注意一下大局下的細節。</p>



<p class="has-medium-font-size">2008、2020年的經濟衰退造成汽車庫存銷售比攀升到3以上的高水位，但指標轉壞的數據公告時，汽車類股股價早已下跌一大段，反而是中長線好買點，總經數據的遞延性是要注意的地方。</p>



<p class="has-medium-font-size"><br>疫情後，美國汽車庫存銷售比受到汽車晶片缺乏的影響，雖然去年一直有新聞說會緩解，但新車製造數始終起不來，庫存銷售比現在低到只剩0.373，持續創造歷史低點，此現象前所未見。<br><br>正常來講，這個比率會大於1，確保有足夠數量應對市場需求。2015年來庫存去化到現在，美國車商如福特 (F)、通用 (GM)手上幾乎沒有新車庫存，在銷售數據不變下，庫存用盡會遇到無貨可賣的窘境。這連帶引發中古車價飆高、車用零組件廠商營收衰退、高端新車買不到等問題。前陣子台積電釋出消費電子有動能減緩的現象，手機鏡頭廠大立光也對未來展望保守，這兩家法說和財測都有一定參考價值。高毛利的手機晶片過去是晶圓代工廠的製造優先名單，汽車晶片相對低毛利，過去兩年在消費電子熱潮、晶圓代工產能有限下，只能委屈排在優先名單後。現在大廠釋出產業變化的看法，汽車電子能不能趁這個機會佔到產能，真的解決晶片荒呢？就看汽車庫存銷售比能不能物極必反，產生訂單遞延的爆發效應。除了整車廠，哪一些美股新車零組件能受惠呢？汽車族群經過利空測試後，復甦期與沈寂的股價表現值得留意。</p>



<h3>美股回測</h3>



<p class="has-medium-font-size"><a href="https://ai.finlab.tw/" target="_blank" rel="noopener">FinLab量化平台</a>目前沒有對外開放美股資料的使用，但其實回測模組是有相關的接口讓大家自由回測全球市場。以下會使用美股汽車製造商的股價與汽車總經數據做簡單的策略回測範例，向大家示範如何串接美股資料套用回測程式。</p>



<h4>美股資料爬蟲</h4>



<p class="has-medium-font-size">下列是運用yahoo資料源爬取美股股價，程式修改來自於這篇&#8221;<a href="https://www.finlab.tw/%e7%94%a8%e7%88%ac%e8%9f%b2%e7%88%ac%e5%85%a8%e4%b8%96%e7%95%8c%e8%82%a1%e5%83%b9/">用爬蟲爬全世界股價</a>&#8220;</p>



<pre class="wp-block-code"><code lang="python" class="language-python">import requests
import io
import datetime
import pandas as pd
import logging

# Get an instance of a logger
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

auto_manufacturers = {
    "BLBD": "BLUE BIRD CORP",
    "ELMS": "ELECTRIC LAST MILE SOLUTIONS INC",
    "F": "FORD MOTOR CO",
    "FFIE": "FARADAY FUTURE INTELLIGENT ELECTRIC INC",
    "FSR": "FISKER INC",
    "GM": "GENERAL MOTORS CO",
    "GOEV": "CANOO INC",
    "HYZN": "HYZON MOTORS INC",
    "LCID": "LUCID GROUP INC",
    "NKLA": "NIKOLA CORP",
    "PTRA": "PROTERRA INC",
    "RIDE": "LORDSTOWN MOTORS CORP",
}


def crawl_yahoo_finance(targets, all_data=True):

    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'}
    data = []
    for stock_id in targets:
        now = datetime.datetime.now()
        now_timestamp = int(now.timestamp()) + 86400
        if all_data:
            start_time = 0
        url = f"https://query1.finance.yahoo.com/v7/finance/download/{stock_id}?period1={start_time}&amp;" \
              f"period2={now_timestamp}&amp;interval=1d&amp;events=history"
        try:
            response = requests.get(url, headers=headers)
            f = io.StringIO(response.text)
            df = pd.read_csv(f, index_col='Date', parse_dates=['Date'])
            df = df[~df.index.duplicated(keep='last')]
            df['stock_id'] = stock_id
            df = df.reset_index()
            df = df.rename(columns={'Date': 'date', 'High': 'high', 'Low': 'low', 'Open': 'open', 'Close': 'close',
                                    'Volume': 'vol', 'Adj Close': 'adj_close'})
        except Exception as e:
            logger.error(e)
            df = None
        data.append(df)

    df = pd.concat(data)

    return df


auto_price = crawl_yahoo_finance(auto_manufacturers.keys())
# 處理股價格式成pivot
adj_close = auto_price.pivot(index='date', columns='stock_id', values='adj_close')
adj_close = FinlabDataFrame(adj_close)</code></pre>



<h4>總經指標格式處理</h4>



<p class="has-medium-font-size">總經指標要注意處理date，上月資料於近月底公布，ex:2021-4-30公告 2021-03月份數據，所以要使用date_range另外生成往後推的日期數列。<br>將汽車類股的stock_id對應進去，每一欄stock_id都有總經數據，並將總經數據dataframe套用到FinLab模組的FinlabDataFrame物件，方便之後選股條件交集運算。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">aisrsa_df = pd.DataFrame(aisrsa['observations'])
aisrsa_df['value'] = aisrsa_df['value'].astype(float)
dates = pd.to_datetime(aisrsa_df['date'])
start = dates.iloc[0]+ relativedelta(months=1)
end = dates.iloc[-1]+ relativedelta(months=2)
update_date = pd.date_range(start=start,end=end,freq='M')
aisrsa_df = pd.DataFrame({i:aisrsa_df['value'] for i in auto_manufacturers.keys()})
aisrsa_df.index = update_date
aisrsa_df.index.name = 'date'
aisrsa_df = FinlabDataFrame(aisrsa_df)
aisrsa_df</code></pre>



<h4>選股條件</h4>



<p class="has-medium-font-size">非常簡單，只有兩個條件。<br>還原股價站上月線，每月換股。<br>汽車庫存銷售銷售比大於12日均線，運用指標遞延的特性，抓汽車製造循環。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">cond1 = adj_close &gt; adj_close.average(20)
cond2 = aisrsa_df &gt; aisrsa_df.average(12)
position = cond1 &amp; cond2</code></pre>



<h4>美股市場market_info設定</h4>



<p class="has-medium-font-size">這一步是將美股回測套用到FinLab的關鍵。<br>回測工具 sim(market=&#8221;TWSTOCK&#8221;) 會依照個別市場的MarketInfo物件，拉取對應市場的資料，目前內建market只有TWMarketInfo (台股)、CryptoMarketInfo (加密貨幣)，所以要外插一個USMarketInfo 給market參數。<br>USMarket的benchmark改用SP500指數。<br>回測若要upload，要注意時間序列長度有寫入限制，範例回測2000年後的數據。</p>



<p class="has-medium-font-size">程式如下:</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab.market_info import MarketInfo
from finlab.backtest import sim

class USMarketInfo(MarketInfo):

    @staticmethod
    def get_benchmark():
        world_index = data.get('world_index:close')
        sp500 = world_index['^GSPC'].ffill()
        return sp500

    @staticmethod
    def get_asset_id_to_name():
        return {}

    @staticmethod
    def get_price(trade_at_price, adj=True):
        if isinstance(trade_at_price, pd.Series):
            trade_at_price.name = position.name
            return trade_at_price.to_frame()

        if isinstance(trade_at_price, pd.DataFrame):
            return trade_at_price

        if isinstance(trade_at_price, str):
            if adj &amp; (trade_at_price=='close'):
                trade_at_price = 'adj_' + trade_at_price

            price = auto_price.pivot(index='date', columns='stock_id', values=trade_at_price)
            return price

        raise Exception(f'**ERROR: trade_at_price is not allowed (accepted types: pd.DataFrame, pd.Series, str).')

report = sim(position=position.loc['2000':],resample='M',market=USMarketInfo,upload=True,name='test',stop_loss=0.1,position_limit=0.33)
report.display()</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="430" src="https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午2.09.28-1024x430.png" alt="截圖 2022 05 25 下午2.09.28" class="wp-image-3593" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午2.09.28-1024x430.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午2.09.28-300x126.png 300w, https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午2.09.28-768x322.png 768w, https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午2.09.28-1536x645.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/05/截圖-2022-05-25-下午2.09.28-2048x860.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="FRED總體經濟指標輕鬆抓|美國汽車指標|美股回測外掛教學 10"></figure>



<h2>結語</h2>



<p class="has-medium-font-size">這篇文章涉及FRED API串接、美股股價爬蟲、總經指標繪圖、指標解說、美股與總經回測～一條龍帶大家走一遍，開展了FinLab系統更多的可能性。<br> 一樣附上程式範例檔，一同來開發多元市場的策略吧！</p>



<h3><a href="https://drive.google.com/file/d/1fHDkeLZL12uDkb3uXBhq89VlXFuyGsl4/view?usp=sharing" target="_blank" rel="noopener">colab範例</a></h3>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/fred%e7%b8%bd%e9%ab%94%e7%b6%93%e6%bf%9f%e6%8c%87%e6%a8%99%e8%bc%95%e9%ac%86%e6%8a%93%e7%be%8e%e5%9c%8b%e6%b1%bd%e8%bb%8a%e6%8c%87%e6%a8%99%e7%be%8e%e8%82%a1%e5%9b%9e%e6%b8%ac%e5%a4%96%e6%8e%9b/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3577</post-id>	</item>
	</channel>
</rss>
