<?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%88%AC%E8%9F%B2/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.finlab.tw</link>
	<description>深入淺出的量化投資，讓你在在茫茫股海中，找到專屬於自己的投資方法</description>
	<lastBuildDate>Wed, 16 Nov 2022 13:34:55 +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爬蟲教學｜台股數據｜集保戶股權分散表</title>
		<link>https://www.finlab.tw/python_crawler_tdcc_inventory/</link>
					<comments>https://www.finlab.tw/python_crawler_tdcc_inventory/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Wed, 09 Nov 2022 04:44:46 +0000</pubDate>
				<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[投資新手]]></category>
		<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[爬蟲]]></category>
		<category><![CDATA[集保]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4834</guid>

					<description><![CDATA[籌碼數據豐富是台股一大特色~
集保餘額可以幫助我們判斷不同持股分級的持股者間的資金流動變化，每週公佈的特性可當較同步的指標，也減低日週期資料如「分點籌碼」的雜訊。
分析前得先要有資料，讓我們開始執行我們的Python爬蟲吧！]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">籌碼數據豐富是台股一大特色，像美國只有「每季」公告的 13F 報告揭露大機構(資產管理規模超過 1 億美元)的資金動向，且截止申報日是每個季度 (三個月) 結束之後的 45 天之內，實在落後太久，很難當即時指標。<br>但台股則是有日週期的「法人買賣超」、「融資融券」、「借還券」、「當沖」、「分點券商進出」&#8230;，週週期的則有本篇要抓的「集保戶股權分散表」、月週期則有「董監內部人持股變動與質押」，可說有許多工具可分析籌碼。<br>集保餘額可以幫助我們判斷不同持股分級的持股者間的資金流動變化，每週公佈的特性可當較同步的指標，也減低日週期資料如「分點籌碼」的雜訊。<br>分析前得先要有資料，讓我們開始執行我們的Python爬蟲吧！</p>



<h2>資料源</h2>



<p class="has-medium-font-size"><a href="https://www.tdcc.com.tw/portal/zh/about/about" target="_blank" rel="noopener">台灣集中保管結算所</a> 簡單說就是統計籌碼的單位，服務項目包括有價證券集中保管帳簿劃撥、集中交易及櫃檯買賣市場有價證券交割、興櫃股票款券結算交割、期貨結算電腦處理、無實體有價證券登錄、參加人有價證券電腦帳務處理等，並接受金融監督管理委員會證券期貨局委託辦理股務查核作業。</p>



<p class="has-medium-font-size">「<a href="https://www.tdcc.com.tw/portal/zh/smWeb/qryStock" target="_blank" rel="noopener">集保戶股權分散表</a>」是官方公開資料，每週六早上有新數據，資料查詢分兩種，一種是單一標的歷史資料查詢 (資料僅1年份) ; 另一種是總表查詢，可以一次抓全部資料，要注意總標指提供單週資料。所以若要歷史數據得自己每一檔慢慢搜集，或參考 <a href="https://ai.finlab.tw/database#inventory" target="_blank" rel="noopener">FinLab 資料庫</a>。</p>



<figure class="wp-block-image size-large"><img width="1024" height="647" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.06.43-1024x647.png" alt="截圖 2022 11 09 上午11.06.43" class="wp-image-4835" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.06.43-1024x647.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.06.43-300x190.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.06.43-768x485.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.06.43-1536x971.png 1536w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.06.43-2048x1294.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python爬蟲教學｜台股數據｜集保戶股權分散表 1"></figure>



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



<p class="has-medium-font-size">「集保戶股權分散表」爬蟲的資料處理細節見註解。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">def crawl():
    
    # 將網站回傳資料轉到 read_csv 解析，加入 headers 的功能為防止反爬蟲辨識，官方有時會擋 
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_1\
    0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} 
    res = requests.get("https://smart.tdcc.com.tw/opendata/getOD.ashx?id=1-5", headers=headers)
    df = pd.read_csv(StringIO(res.text))
    df = df.astype(str)
    df = df.rename(columns={
        '證券代號': 'stock_id',
        '股數': '持有股數', '占集保庫存數比例%': '占集保庫存數比例'
    })
    
    # 移除「公債」相關的id
    debt_id = list(set([i for i in df['stock_id'] if i[0] == 'Y']))
    df = df[~df['stock_id'].isin(debt_id)]
    
    # 官方有時會有不同格式誤傳，做例外處理
    if '占集保庫存數比例' not in df.columns:
        df = df.rename(columns={'佔集保庫存數比例%': '占集保庫存數比例'})
        
    # 持股分級=16時，資料都為0，要拿掉
    df = df[df['持股分級'] != '16']
    
    # 資料轉數字
    float_cols = ['人數', '持有股數', '占集保庫存數比例']
    df[float_cols] = df[float_cols].apply(lambda s: pd.to_numeric(s, errors="coerce"))
    
    # 抓表格上的時間資料做處理
    df['date'] = datetime.datetime.strptime(df[df.columns[0]][0], '%Y%m%d')
    
    #只要第二層欄位名稱
    df = df.drop(columns=df.columns[0])
    
    # 索引設置 unique index
    df = df.set_index(['stock_id', 'date', '持股分級'])
    return df</code></pre>



<h3>輸出格式</h3>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="941" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.44.52-1024x941.png" alt="截圖 2022 11 09 上午11.44.52" class="wp-image-4836" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.44.52-1024x941.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.44.52-300x276.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.44.52-768x706.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-09-上午11.44.52.png 1537w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python爬蟲教學｜台股數據｜集保戶股權分散表 2"><figcaption>Python爬蟲輸出結果</figcaption></figure>



<h2>未來開發</h2>



<p class="has-medium-font-size">Python爬蟲蒐集完資料後，我們就可以用資料來撰寫策略或做資料視覺化～究竟「集保戶股權分散表」有沒有用？讓我們繼續看下去。<br>了解更多 <a href="https://www.finlab.tw/?s=%E7%88%AC%E8%9F%B2">爬蟲實做</a> ～</p>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/python_crawler_tdcc_inventory/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4834</post-id>	</item>
		<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 loading="lazy" 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 3"><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 4"><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 5"></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 6"></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 7"></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總體經濟指標輕鬆抓|美國汽車指標|美股回測外掛教學 8"></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總體經濟指標輕鬆抓|美國汽車指標|美股回測外掛教學 9"></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總體經濟指標輕鬆抓|美國汽車指標|美股回測外掛教學 10"></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總體經濟指標輕鬆抓|美國汽車指標|美股回測外掛教學 11"><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總體經濟指標輕鬆抓|美國汽車指標|美股回測外掛教學 12"></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>
		<item>
		<title>爬蟲 Python 新手教學(Part 1)：簡單程式碼，爬全球的股票!</title>
		<link>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/</link>
					<comments>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/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:39 +0000</pubDate>
				<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[月營收]]></category>
		<category><![CDATA[爬蟲]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[股票]]></category>
		<category><![CDATA[量化投資]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=840</guid>

					<description><![CDATA[Python 超簡單新手教學！這個系列文章的第一篇，我們要來介紹如何使用 Python 製作爬蟲爬取股價！而且全球股價都適用喔！今天讓我們回到原點，從最簡單的程式開始教起，想要做股票數據分析，一定要先得到股票資料，所以我們就從股票資料如何獲取開始吧！]]></description>
										<content:encoded><![CDATA[
<p>現在開始並不算晚，用 Python 做選股交易，超越大盤，已經變得非常非常簡單，所以系列文章的第一篇，我們要來介紹如何簡單使用 Python 爬股價！有了股價之後，才能有價格資料進而做出決策。值得一提的是，這是全球股價都適用的爬蟲，今天就讓我們回到原點，從最簡單的 Python 開始教起，想要做股票數據分析，一定要先得到股票資料，所以我們就從股票資料如何獲取開始吧！<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/t.png"></a></p>



<figure class="wp-container-4 wp-block-gallery-3 wp-block-gallery has-nested-images columns-default is-cropped">
<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="488" data-id="1916" src="https://www.finlab.tw/wp-content/uploads/2020/07/t-1-1024x4881-min.jpg" alt="爬蟲爬取全世界股票資料" class="wp-image-1916" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/t-1-1024x4881-min.jpg 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/t-1-1024x4881-min-300x143.jpg 300w, https://www.finlab.tw/wp-content/uploads/2020/07/t-1-1024x4881-min-768x366.jpg 768w" sizes="(max-width: 1024px) 100vw, 1024px" title="爬蟲 Python 新手教學(Part 1)：簡單程式碼，爬全球的股票! 13"></figure>
<figcaption class="blocks-gallery-caption">用 Python 來製作爬蟲！</figcaption></figure>



<h3 id="從頭開始學python">從頭開始學 python</h3>



<p>這篇文章中<br>我們會帶著初學者開始再從頭瞭解<br>如何用 python 分析財經資料，並從中獲利！</p>



<p>你是程式新手嗎？<br>不用擔心，只要跟著這一系列的教學，<br>保證你一定學的會！<br>這一系列教學將會是hahow課程中的化簡，但是可以幫助新手無痛的開始使用python！</p>



<p>請點選此<a href="https://colab.research.google.com/drive/16U16Pcg45vG8lBNQUhzmBXy74VsKz8OV?usp=sharing" target="_blank" rel="noreferrer noopener">此課程範例，免費線上運行程式碼</a></p>



<h3 id="設定python環境">使用 Google Colab 來寫 Python</h3>



<p>Google ，佛心來著的公司，最近推出了免費雲端寫程式的平台： Google Colab<br>不用安裝任何軟體，可以線上免費使用 Python 實在是太方便了！只要打開 <a href="https://colab.research.google.com/" rel="noreferrer noopener" target="_blank">Colab</a> 並且新增一個 notebook ，並將下方的 Code 複製貼上跑一跑囉！當然你也可以打開已經寫好的<a href="https://colab.research.google.com/drive/16U16Pcg45vG8lBNQUhzmBXy74VsKz8OV?usp=sharing" target="_blank" rel="noreferrer noopener">課程範例，免費線上運行程式碼</a>！讓你快速體驗 Colab 的實力！廢話不多說，進入今天的正題吧！</p>



<h3 id="爬取歷史股價">用 Python 製作爬蟲爬取歷史股價</h3>



<p>首先要先獲取股價資料，我們會用常用的  Python 函式庫：yfinance<br>它可以將網路上的資料給下載下來，給程式使用，我們可以先用 pip 來安裝 yfinance，pip 就像是程式安裝精靈，可以幫我們安裝各式各樣的 Python package。</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">!pip install yfinance</code></pre>



<p>上面第一個字是驚嘆號！是 Colab 上使用 bash 語法必需要使用的開頭。假如你是在自己的電腦，例如 cmd 或是 anaconda prompt，就不需要驚嘆號喔！</p>



<p>接下來</p>



<pre title="開啟 yfinance" class="wp-block-code"><code lang="python" class="language-python line-numbers">import yfinance as yf</code></pre>



<p>這邊的import，就像是我們在電腦裡面打開某個軟體來使用，一樣的意思。我們打開 yfinance，並且重新將它取名為「yf」，方便我們之後呼叫（打兩個字比較輕鬆啦！）</p>



<p>接下來我們可以用它來下載「台積電」的資料：</p>



<pre class="wp-block-code"><code class="">df = yf.Ticker("2330.TW").history(period="max")
df</code></pre>



<p><br>上述指令中，我們輸入的股票代號為：</p>



<ul><li>2330.TW 是台積電在 <a href="https://finance.yahoo.com/quote/2330.TW?p=2330.TW&amp;.tsrc=fin-srch" target="_blank" rel="noreferrer noopener">yahoo finance</a> 上的 symbol，你也可以任意換成其他的，例如蘋果（AAPL），特斯拉（TSLA），微軟（MSFT）等等</li><li>period=&#8217;max&#8217; ，我們希望拿取最多的歷史資料</li></ul>



<p>透過上述簡單的語法，就可以將台積電在這兩個區間股價資訊給爬下來了！我們可以用 Python 把網址裡內的內容給爬下來。</p>



<h3>顯示爬蟲下載數據</h3>



<p>可以將下載下來的資料（ df ）顯示出來，之所以叫做 df，是 DataFrame 的簡寫：</p>



<pre class="wp-block-code"><code class="">df</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="587" src="https://www.finlab.tw/wp-content/uploads/2022/05/image-9-1024x587.png" alt="image 9" class="wp-image-3567" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/image-9-1024x587.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/05/image-9-300x172.png 300w, https://www.finlab.tw/wp-content/uploads/2022/05/image-9-768x440.png 768w, https://www.finlab.tw/wp-content/uploads/2022/05/image-9.png 1532w" sizes="(max-width: 1024px) 100vw, 1024px" title="爬蟲 Python 新手教學(Part 1)：簡單程式碼，爬全球的股票! 14"><figcaption>DataFrame 的資料</figcaption></figure>



<p>我們可以看到下載了非常多種類的資料，包含了股票的「開高低收」，另外也有除權息增減資的資訊！該有的價格資料都有了！順帶一題，這個類似表格的格式，是 Python 裡面一個非常重要的 Package 「Pandas」，處理數據非常的方便，可以把它想像是強大且靈活的 Excel。</p>



<h3 id="全球股價">全球股價爬蟲</h3>



<p>你可以將任何一檔股價，包含美股港股台股陸股，用同樣的方式爬下來，只要在<a rel="noreferrer noopener" href="https://finance.yahoo.com/" target="_blank">yahoo finance</a>可以找到，就一定可以下載的下來喔！例如微軟（MSFT）、蘋果（AAPL）、特斯拉（TSLA），都可以用類似的方法來下載！</p>



<p>有了 google 提供的免費伺服器，我們可以在<a href="https://colab.research.google.com/drive/1BYfdokxdj8Sn3cruXuqwsiQOY42cwMsR?usp=sharing" class="rank-math-link" target="_blank" rel="noopener">雲端執行此單元程式碼範例</a></p>



<p>行有餘力，請點選<a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B82%E5%85%A8%E7%90%83%E6%8C%87%E6%95%B8%E4%B8%80%E6%AC%A1%E6%8A%93/">下一單元，將全球大盤指數都下載下來</a>！</p>



<p>這一系列是我們影音課程的化簡版，<br>假如對此教程有興趣，歡迎參考我們的<a href="https://www.finlab.tw/video-course/">影音課程</a>，裡面有更詳細並完整的教學，包含資料庫建置、數據分析、回測等等。當然我們也有免費的文章，以爬蟲來說，就有非常多篇，你可以先逛一逛：</p>



<ul><li><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></li><li><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></li><li><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></li><li><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></li><li><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></li><li><a href="https://www.finlab.tw/python_crawler_tdcc_inventory/">Python爬蟲教學｜台股數據｜集保戶股權分散表</a></li></ul>



<p>除了爬股票分析的資料，我們還有爬一些奇特的數據，有需要也可以來看看：</p>



<ul><li><a href="https://www.finlab.tw/real-estate-analysis1/">用程式分析房地產可行嗎？房地產爬蟲教學在這裡！</a></li><li><a href="https://www.finlab.tw/btc-crawler-py/">用Python投資加密貨幣：爬蟲下載歷史數據 (Part 2)</a></li><li><a href="https://www.finlab.tw/us_unemployment_rate_seasonally_adjusted_crawler/">Python爬蟲教學｜美國勞動部統計局API｜失業率</a></li><li><a href="https://www.finlab.tw/tw_monetary_aggregates_m1b_crawler/">Python爬蟲教學｜ 財經數據｜台灣貨幣總計數 M1B &amp; M2</a></li></ul>
]]></content:encoded>
					
					<wfw:commentRss>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/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">840</post-id>	</item>
		<item>
		<title>Python新手教學(Part 2)：全球指數一次抓</title>
		<link>https://www.finlab.tw/python%e6%96%b0%e6%89%8b%e6%95%99%e5%ad%b82%e5%85%a8%e7%90%83%e6%8c%87%e6%95%b8%e4%b8%80%e6%ac%a1%e6%8a%93/</link>
					<comments>https://www.finlab.tw/python%e6%96%b0%e6%89%8b%e6%95%99%e5%ad%b82%e5%85%a8%e7%90%83%e6%8c%87%e6%95%b8%e4%b8%80%e6%ac%a1%e6%8a%93/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:39 +0000</pubDate>
				<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[爬蟲]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[股票]]></category>
		<category><![CDATA[股票分析]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=851</guid>

					<description><![CDATA[我們已經知道怎麼抓取任意一檔股票歷史價格了，但有時候我們一次需要很多檔股票，怎麼辦呢？難道每個股票我們都要寫這麼多行，才能抓下來嗎？今天我們教你如何將上一次的功能包裝成 function，然後一次下載全球指數！]]></description>
										<content:encoded><![CDATA[
<p>我們已經知道怎麼抓取任意一檔股票歷史價格了，但有時候我們一次需要很多檔股票，怎麼辦呢？難道每個股票我們都要寫這麼多行，才能抓下來嗎？今天我們教你如何將上一次的功能包裝成 function，然後一次下載全球指數！<a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B82%E5%85%A8%E7%90%83%E6%8C%87%E6%95%B8%E4%B8%80%E6%AC%A1%E6%8A%93/thumbnail.png"></a></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="679" src="http://34.96.136.135/wp-content/uploads/2020/07/thumbnail-5-2-1024x679.png" alt="thumbnail 5 2" class="wp-image-853" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-5-2-1024x679.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-5-2-300x199.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-5-2-768x510.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-5-2-1536x1019.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-5-2.png 1664w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 2)：全球指數一次抓 15"></figure></div>


<h3 id="上次的程式碼爬取台積電">上次的程式碼爬取台積電</h3>



<p>首先，我們上次已經教了怎麼樣爬取一檔股票：「台積電2330」，這次我們重新複習一下，下方的程式，假如有任何一個部分忘記了，都可以去<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>複習喔！</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import yfinance as yf

df = yf.Ticker("2330.TW").history(period="max")
df</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="443" src="http://34.96.136.135/wp-content/uploads/2020/07/1-2-1024x443.png" alt="1 2" class="wp-image-854" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/1-2-1024x443.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/1-2-300x130.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/1-2-768x332.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/1-2-1536x664.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/1-2-2048x885.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 2)：全球指數一次抓 16"></figure></div>


<p><a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B82%E5%85%A8%E7%90%83%E6%8C%87%E6%95%B8%E4%B8%80%E6%AC%A1%E6%8A%93/1.png"></a></p>



<p>但是以上的程式碼只能爬「台積電」的股價，我想要爬其他的指數怎麼辦呢？</p>



<h3 id="將上述程式碼打包成function">將上述程式碼打包成function</h3>



<p>我們可以用<code>function</code>將上面的程式碼打包起來，方便我們多次使用，變成下面這樣，其實跟之前長的非常像，可以先比較一下：首先，第一行多了<code>def crawl_price(stock_id):</code>，這行的意思就是宣告一個可呼叫的程式區塊，叫做<code>crawl_price(stock_id)</code>，再來，原本的程式碼前方都被加了4個空白格，代表這些功能是同一個<code>function</code>中被執行的代碼。</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import yfinance as yf

def crawl_price(stock_id):
  df = yf.Ticker(stock_id).history(period="max")
  return df

</code></pre>



<p>上面的代碼中，有個特別可以注意的變數：<code>stock_id</code>，當今天<code>stock_id</code>被傳進<code>function</code>中的時候，url就會隨著<code>stock_id</code>的不同，而出現不同的<code>url</code>所以我們就可以爬到不同的股票歷史股價！</p>



<p>既然我們已經寫好了此<code>function</code>，接下來就可以呼叫它，得到不同股票的歷史股價</p>



<h3 id="使用function">使用function</h3>



<p>假如以後我們需要爬取不同的股票，例如「鴻海2354」，我們就可以寫：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">df = crawl_price("2354.TW")
df.Close.plot()</code></pre>



<p>就可以順利將鴻海的股票爬取下來喔！<a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B82%E5%85%A8%E7%90%83%E6%8C%87%E6%95%B8%E4%B8%80%E6%AC%A1%E6%8A%93/2.png"></a></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="536" src="http://34.96.136.135/wp-content/uploads/2020/07/2-2-1024x536.png" alt="2 2" class="wp-image-855" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/2-2-1024x536.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/2-2-300x157.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/2-2-768x402.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/2-2-1536x804.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/2-2-2048x1072.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 2)：全球指數一次抓 17"></figure></div>


<p>接下來我們就來爬取世界上重要的指數吧！</p>



<h3 id="國際重要指數清單">國際重要指數清單</h3>



<p>首先我們必須要爬取到國際重要指數清單，可以到以下網址來獲取：<br><a href="https://finance.yahoo.com/world-indices/" rel="noreferrer noopener" target="_blank">https://finance.yahoo.com/world-indices/</a><a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B82%E5%85%A8%E7%90%83%E6%8C%87%E6%95%B8%E4%B8%80%E6%AC%A1%E6%8A%93/3.png"></a></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="568" src="http://34.96.136.135/wp-content/uploads/2020/07/3-1-2-1024x568.png" alt="3 1 2" class="wp-image-857" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/3-1-2-1024x568.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/3-1-2-300x167.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/3-1-2-768x426.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/3-1-2-1536x853.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/3-1-2-2048x1137.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 2)：全球指數一次抓 18"></figure></div>


<p>接下來我們就可以將上述清單給手動複製起來？！<br>不，我們要用更炫的方法，當然是要用程式來爬呀：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">url = "https://finance.yahoo.com/world-indices/"
response = requests.get(url)

import io
f = io.StringIO(response.text)
dfs = pd.read_html(f)
world_index = dfs[0]</code></pre>



<p>上述的程式碼，剛開始很簡單，就是用<code>requests.get</code>來獲取此網頁的資料，網頁中的資料都存在<code>response.text</code>中，跟之前一模一樣。</p>



<p>不過第5行有點不一樣，我們使用<code>io.StringIO(response.text)</code>將資料存成檔案<code>f</code><br>第6行，我們將此文件利用<code>pd.read_html(f)</code>來分析網頁<code>f</code>中的表格，將所有的表格存成 a list of dataframe<br>第7行，我們將第一張dataframe給拿出來。<a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B82%E5%85%A8%E7%90%83%E6%8C%87%E6%95%B8%E4%B8%80%E6%AC%A1%E6%8A%93/4.png"></a></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="435" src="http://34.96.136.135/wp-content/uploads/2020/07/4-1-2-1024x435.png" alt="4 1 2" class="wp-image-859" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/4-1-2-1024x435.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/4-1-2-300x128.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/4-1-2-768x327.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/4-1-2-1536x653.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/4-1-2-2048x871.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 2)：全球指數一次抓 19"></figure></div>


<p>這樣我們就有了此表格中的symbol和name，以供之後歷史股價的爬取</p>



<p>這個單元的程式碼範例，都可以<a href="https://colab.research.google.com/drive/1TxyeRy6ukAhrJ10x80YoIoYTChd4EUEQ?usp=sharing" class="rank-math-link" target="_blank" rel="noopener">在colab上直接運行</a>喔！趕快來跑跑看吧！</p>



<h3 id="最後，終於要爬取全球股價了！">最後，終於要爬取全球股價了！</h3>



<p>萬事俱備！只欠東風，不過由於這次的教學已經很多了，所以大家可以自己練習看看，或是前往<a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B83%E5%85%A8%E7%90%83%E6%8C%87%E6%95%B8%E6%AD%B7%E5%8F%B2%E6%95%B8%E6%93%9A/">下一個單元</a>，來爬取所有的歷史指數吧！</p>



<p>這一系列是我們影音課程的化簡版，<br>假如對此教程有興趣，歡迎點選下方影音課程，會豐富到炸裂喔～</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/python%e6%96%b0%e6%89%8b%e6%95%99%e5%ad%b82%e5%85%a8%e7%90%83%e6%8c%87%e6%95%b8%e4%b8%80%e6%ac%a1%e6%8a%93/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">851</post-id>	</item>
		<item>
		<title>Python新手教學(Part 3)：全球指數歷史數據下載大全</title>
		<link>https://www.finlab.tw/python%e6%96%b0%e6%89%8b%e6%95%99%e5%ad%b83%e5%85%a8%e7%90%83%e6%8c%87%e6%95%b8%e6%ad%b7%e5%8f%b2%e6%95%b8%e6%93%9a/</link>
					<comments>https://www.finlab.tw/python%e6%96%b0%e6%89%8b%e6%95%99%e5%ad%b83%e5%85%a8%e7%90%83%e6%8c%87%e6%95%b8%e6%ad%b7%e5%8f%b2%e6%95%b8%e6%93%9a/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:39 +0000</pubDate>
				<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[爬蟲]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[股票]]></category>
		<category><![CDATA[股票分析]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=861</guid>

					<description><![CDATA[這個單元我們要利用 for 迴圈將所有的歷史數據爬下來，並且繪製所有的歷史股價。我們也會介紹一些 for 迴圈的進階技巧，並且將這些技巧結合起來，完成這次的功能，想要學習python，就慢慢跟著我們一步一步來吧！]]></description>
										<content:encoded><![CDATA[
<p>這個單元我們要利用 for 迴圈將所有的歷史數據爬下來，並且繪製所有的歷史股價。我們也會介紹一些 for 迴圈的進階技巧，並且將這些技巧結合起來，完成這次的功能，想要學習python，就慢慢跟著我們一步一步來吧！<a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B83%E5%85%A8%E7%90%83%E6%8C%87%E6%95%B8%E6%AD%B7%E5%8F%B2%E6%95%B8%E6%93%9A/thumbnail.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="679" src="http://34.96.136.135/wp-content/uploads/2020/07/thumbnail-5-4-1024x679.png" alt="thumbnail 5 4" class="wp-image-864" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-5-4-1024x679.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-5-4-300x199.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-5-4-768x510.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-5-4-1536x1019.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-5-4.png 1664w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 3)：全球指數歷史數據下載大全 20"></figure></div>



<p>延續<a href="https://www.finlab.tw/python%e6%96%b0%e6%89%8b%e6%95%99%e5%ad%b82%e5%85%a8%e7%90%83%e6%8c%87%e6%95%b8%e4%b8%80%e6%ac%a1%e6%8a%93/" class="rank-math-link">上個單元</a>，我們應該已經爬取了<code>world_index</code>這張表格：<a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B83%E5%85%A8%E7%90%83%E6%8C%87%E6%95%B8%E6%AD%B7%E5%8F%B2%E6%95%B8%E6%93%9A/1.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="314" src="http://34.96.136.135/wp-content/uploads/2020/07/1-3-1-1024x314.png" alt="1 3 1" class="wp-image-866" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/1-3-1-1024x314.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/1-3-1-300x92.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/1-3-1-768x235.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/1-3-1-1536x471.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/1-3-1-2048x627.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 3)：全球指數歷史數據下載大全 21"></figure></div>



<p>然後還有一個我們寫好的function</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import json
import requests
import datetime
import pandas as pd
import numpy as np

def crawl_price(stock_id):

    d = datetime.datetime.now()
    url = "https://query1.finance.yahoo.com/v8/finance/chart/"+stock_id+"?period1=0&amp;period2="+str(int(d.timestamp()))+"&amp;interval=1d&amp;events=history&amp;=hP2rOschxO0"

    res = requests.get(url)
    data = json.loads(res.text)
    df = pd.DataFrame(data['chart']['result'][0]['indicators']['quote'][0], index=pd.to_datetime(np.array(data['chart']['result'][0]['timestamp'])*1000*1000*1000))
    return df</code></pre>



<p>接下來就可以將他們結合，來爬取歷史資料了！在爬取資料之前，有幾個程式的小技巧必須要學會</p>



<h3 id="1-for-迴圈">1. for 迴圈</h3>



<p>假如我們要執行重複性的動作，通常第一件事情就是想到for 迴圈，例如我們想要印出1～9，不用for迴圈，我們可以寫成</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">print(1)
print(2)
print(3)
print(4)
print(5)
print(6)
print(7)
print(8)
print(9)</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="328" src="http://34.96.136.135/wp-content/uploads/2020/07/2-3-1024x328.png" alt="2 3" class="wp-image-867" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/2-3-1024x328.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/2-3-300x96.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/2-3-768x246.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/2-3-1536x493.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/2-3-2048x657.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 3)：全球指數歷史數據下載大全 22"></figure></div>



<p><a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B83%E5%85%A8%E7%90%83%E6%8C%87%E6%95%B8%E6%AD%B7%E5%8F%B2%E6%95%B8%E6%93%9A/2.png"></a>但很明顯我們就已經快要中風了，所以改成for迴圈後</p>



<pre class="wp-block-code"><code lang="python" class="language-python">for i in [1,2,3,4,5,6,7,8,9]:
    print(i)</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="216" src="http://34.96.136.135/wp-content/uploads/2020/07/3-2-1-1024x216.png" alt="3 2 1" class="wp-image-868" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/3-2-1-1024x216.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/3-2-1-300x63.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/3-2-1-768x162.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/3-2-1-1536x325.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/3-2-1-2048x433.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 3)：全球指數歷史數據下載大全 23"></figure></div>



<p><a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B83%E5%85%A8%E7%90%83%E6%8C%87%E6%95%B8%E6%AD%B7%E5%8F%B2%E6%95%B8%E6%93%9A/3.png"></a></p>



<p>這樣短短的就寫完了！其中<br>第一行：我們有一個變數i，他會從1～9不斷變換，並且執行下方的print(i)。第二行要記得加上前方四個空白，通常叫做縮排「indent」，當第一行有<code>for</code>這個標示後，之後就必須用縮排indent直到寫完for迴圈裡的內容為止。</p>



<p>但有時候我們希望同時做兩個迴圈呢？</p>



<h3 id="使用zip">使用zip</h3>



<p>我們可以使用zip，一次執行兩個list：</p>



<pre class="wp-block-code"><code lang="python" class="language-python">for number, letter in zip([1,2,3], ['a', 'b', 'c']):
    print(number, letter)</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="129" src="http://34.96.136.135/wp-content/uploads/2020/07/4-2-1024x129.png" alt="4 2" class="wp-image-869" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/4-2-1024x129.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/4-2-300x38.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/4-2-768x97.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/4-2-1536x194.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/4-2-2048x258.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 3)：全球指數歷史數據下載大全 24"></figure></div>



<p><a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B83%E5%85%A8%E7%90%83%E6%8C%87%E6%95%B8%E6%AD%B7%E5%8F%B2%E6%95%B8%E6%93%9A/4.png"></a></p>



<p>最後，我們要使用 dictionary 將全球的指數給存起來。</p>



<h3 id="dictionary">dictionary</h3>



<p>這邊先示範最簡單的用法：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">d = {}
d['a'] = 1
d['b'] = 2

# 查找
print(d['b']) # 2

# 迴圈
# 其中，d.items 有點像是zip的感覺，
# 針對dictionary中的['a', 'b']和[1,2]進行迴圈）
for letter, number in d.items():
    print(letter, number)
# a 1
# b 2</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="248" src="http://34.96.136.135/wp-content/uploads/2020/07/6-1-1-1024x248.png" alt="6 1 1" class="wp-image-870" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/6-1-1-1024x248.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/6-1-1-300x73.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/6-1-1-768x186.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/6-1-1-1536x372.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/6-1-1-2048x496.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 3)：全球指數歷史數據下載大全 25"></figure></div>



<p><a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B83%E5%85%A8%E7%90%83%E6%8C%87%E6%95%B8%E6%AD%B7%E5%8F%B2%E6%95%B8%E6%93%9A/6.png"></a>結合上述的小功能，就可以寫一個程式將世界指數都抓下來了！<br>我建議你自己試試看～<br>寫完之後再往下拉看範例：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import time
world_index_history = {}
for symbol, name in zip(world_index['Symbol'], world_index['Name']):
    
    print(name)
    
    world_index_history[name] = crawl_price(symbol)
    time.sleep(5)</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="445" src="http://34.96.136.135/wp-content/uploads/2020/07/5-2-1024x445.png" alt="5 2" class="wp-image-871" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/5-2-1024x445.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/5-2-300x130.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/5-2-768x334.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/5-2-1536x668.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/5-2-2048x890.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 3)：全球指數歷史數據下載大全 26"></figure></div>



<p><a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B83%E5%85%A8%E7%90%83%E6%8C%87%E6%95%B8%E6%AD%B7%E5%8F%B2%E6%95%B8%E6%93%9A/5.png"></a>假如你有認真研究前三點功能，相信這些代碼應該難不倒你！其中沒有教到的是，我們利用<code>time.sleep(5)</code>，來休息一下，不要抓的太頻繁，不然會被封鎖，除此之外，上述代碼非常簡單，寫一個for迴圈，將所有的指數都抓下來，存在<code>world_index_history</code>中。</p>



<h3 id="繪製指數">繪製指數</h3>



<p>接下來，我們可以用一樣的for迴圈，來將指數給畫出來</p>



<pre class="wp-block-code"><code lang="python" class="language-python">for name, history in world_index_history.items():
    history.close.plot()</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="597" src="http://34.96.136.135/wp-content/uploads/2020/07/f-1-1024x597.png" alt="f 1" class="wp-image-873" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/f-1-1024x597.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/f-1-300x175.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/f-1-768x447.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/f-1-1536x895.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/f-1-2048x1193.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 3)：全球指數歷史數據下載大全 27"></figure></div>



<p><a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B83%E5%85%A8%E7%90%83%E6%8C%87%E6%95%B8%E6%AD%B7%E5%8F%B2%E6%95%B8%E6%93%9A/f.png"></a></p>



<p>這個<a href="https://colab.research.google.com/drive/1W-pA4jdlPVfil9WZqsRK0Nd8Mel4tMlx?usp=sharing" class="rank-math-link" target="_blank" rel="noopener">單元的程式碼，都可以使用 colab 來執行</a>喔！趕快來玩玩看吧！</p>



<h3 id="有了指數，接下來要做什麼呢？">有了指數，接下來要做什麼呢？</h3>



<p><a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B84%E7%9B%B8%E9%97%9C%E6%80%A7%E5%88%86%E6%9E%90/">下個單元</a>，我們要來分析一下這些指數，看看哪些適合投資，哪些不適合，敬請期待～</p>



<p>這一系列是我們影音課程的化簡版，</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/python%e6%96%b0%e6%89%8b%e6%95%99%e5%ad%b83%e5%85%a8%e7%90%83%e6%8c%87%e6%95%b8%e6%ad%b7%e5%8f%b2%e6%95%b8%e6%93%9a/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">861</post-id>	</item>
		<item>
		<title>Python新手教學(Part 4)：台股的好兄弟是？台股相關性研究</title>
		<link>https://www.finlab.tw/python%e6%96%b0%e6%89%8b%e6%95%99%e5%ad%b84%e7%9b%b8%e9%97%9c%e6%80%a7%e5%88%86%e6%9e%90/</link>
					<comments>https://www.finlab.tw/python%e6%96%b0%e6%89%8b%e6%95%99%e5%ad%b84%e7%9b%b8%e9%97%9c%e6%80%a7%e5%88%86%e6%9e%90/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:39 +0000</pubDate>
				<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[爬蟲]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[股票]]></category>
		<category><![CDATA[股票分析]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=875</guid>

					<description><![CDATA[為什麼美股大跌，在台灣的投資人要很緊張？原因就是相關性！想知道台股跟哪國指數最同步嗎？不是S&#038;P 500美國指數，也不是深圳指數，那究竟是哪國呢？這篇文章我們就來研究一下吧！]]></description>
										<content:encoded><![CDATA[
<p>為什麼美股大跌，在台灣的投資人要很緊張？原因就是相關性！想知道台股跟哪國指數最同步嗎？不是S&amp;P 500美國指數，也不是深圳指數，那究竟是哪國呢？這篇文章我們就來研究一下吧！<a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B84%E7%9B%B8%E9%97%9C%E6%80%A7%E5%88%86%E6%9E%90/last.png"></a></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="988" src="http://34.96.136.135/wp-content/uploads/2020/07/last-1-1024x988.png" alt="last 1" class="wp-image-877" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/last-1-1024x988.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/last-1-300x289.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/last-1-768x741.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/last-1.png 1108w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 4)：台股的好兄弟是？台股相關性研究 28"></figure></div>


<h2 id="相關性最白話">相關性</h2>



<p>首先我們先介紹什麼是相關性，<br>相關性最白話的講法，你可以想像，看到天空烏雲密佈，代表可能要下雨了，<br>代表天空的顏色跟下雨機率有相關，<br>你可以由一個現象，去預測另一個現象，這就是相關性！</p>



<h3 id="相關性稍微數學一點">相關性稍微數學一點</h3>



<p>相關性也可以更數值化的方式表示，先用以下例子講解：<a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B84%E7%9B%B8%E9%97%9C%E6%80%A7%E5%88%86%E6%9E%90/2.png"></a></p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="263" src="http://34.96.136.135/wp-content/uploads/2020/07/2-4-1024x263.png" alt="2 4" class="wp-image-878" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/2-4-1024x263.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/2-4-300x77.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/2-4-768x197.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/2-4-1536x395.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/2-4.png 1914w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 4)：台股的好兄弟是？台股相關性研究 29"></figure></div>


<p>這張圖中：</p>



<ul><li>我們可以看上方左側圖，天氣溫度跟買冰棒人數的變化圖，可以想像某人每一天記錄天氣溫度與冰棒人數，每天畫一個黃點，時間久了，就可以看出黃點之間的關係，也就是天氣越熱，越有人會想要買冰棒！</li><li>同理，上方中間那張圖，某人也可以記錄每天生病的人數，此時就發現，天氣越冷，越多人會感冒！</li><li>當然某人覺得有趣，於是又記錄了溫度與擲筊的關係，最後發現：沒什麼關連</li></ul>



<p>好了，某人已將觀測值變成數字記錄起來了，但每次都必須畫這麼多點，才能看出相關性，也太累了吧？能不能用一個數字取代呢？</p>



<p>這時就可以用</p>



<h3 id="correlation-coefficient-（相關性係數）">correlation coefficient （相關性係數）</h3>



<p>有人可能覺得太多點點了，有密集恐懼症，希望可以將上方這三張圖，每張圖用一個數字代表就好，這樣就不需要看到這麼多點點。</p>



<p>所以某人提出了 correlation coefficient ，從上面第一張圖開始從左而又，分別可以用 1、-1、0來代表：</p>



<ul><li>1 代表正相關，也就是X越高Y越高，X越低Y越低（成正比）</li><li>─1 代表負相關，也就是X越高Y越低，或X越低Y越高（成反比）</li><li>0 代表無相關性</li></ul>



<p>上述只是化簡後的例子<br>事實上相關性係數不是整數，而是會介於─1～1間，代表正負相關的程度！</p>



<p>讀到這裡，你可能會問，</p>



<h3 id="所以跟投資有什麼關係？">所以相關性跟投資有什麼關係？</h3>



<p>投資就是預測未來現象與當下現象的相關性！<br>就像你看到天空烏雲密佈，就能預測接下來會下雨，<br>我們也可以將相關性係數用於全球指數，</p>



<p>為什麼美股大跌，在台灣的投資人要很緊張？原因就是相關性！<br>台股跟美股有正相關。</p>



<p>我們可以用Python將相關性畫出來，假如你還沒有爬取歷史股價的話，可以先到<a href="https://www.finlab.tw/python%e6%96%b0%e6%89%8b%e6%95%99%e5%ad%b83%e5%85%a8%e7%90%83%e6%8c%87%e6%95%b8%e6%ad%b7%e5%8f%b2%e6%95%b8%e6%93%9a/" class="rank-math-link">前個單元</a>爬取喔！</p>



<h2>程式碼撰寫</h2>



<h3>歷史數據回顧</h3>



<p>首先我們可以看一下上個單元爬下來的歷史數據</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">print(world_index_history['S&amp;P 500'].head())</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="241" src="http://34.96.136.135/wp-content/uploads/2020/07/3-3-1024x241.png" alt="3 3" class="wp-image-879" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/3-3-1024x241.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/3-3-300x71.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/3-3-768x181.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/3-3-1536x362.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/3-3-2048x483.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 4)：台股的好兄弟是？台股相關性研究 30"></figure></div>


<p><a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B84%E7%9B%B8%E9%97%9C%E6%80%A7%E5%88%86%E6%9E%90/3.png"></a>還記得<code>world_index_history</code>嗎？它是一個dictionary，根據不同的字串，例如<code>S&amp;P 500</code>，可以叫出相對應的表格（dataframe）</p>



<p>有了&nbsp;<code>world_index_history</code>&nbsp;我們就可以將國際指數的相關性給畫出來，但首先，我們要先來瞭解</p>



<h3 id="Adj-Close跟Close的差異？"><code>比對歷史數據，發現close價格不一樣？</code></h3>



<p>假如你認真的比對歷史數據（例如玩股網），就會發現離現在越久遠以前的歷史價格，誤差越大！這是為什麼呢？其實這個並不是誤差喔！因為 yahoo finance 的歷史價格是「調整後收盤價」代表這是考慮了除權息的價格變化，所計算出來的價格。</p>



<h3 id="簡單的例子">簡單的例子</h3>



<p>當除權息、增減資時，一般股價會有大波動，以除權息為例，股票價格瞬間下跌<br>然而帳戶裡的股票張數會變多（例如領股利）<br>或是帳戶資金量變多（領股息）<br>總體來講是不賺不賠的</p>



<p>所以當除權息時，<br>正常的收盤價&nbsp;會突然下跌很多，<br>而 yahoo finance 的調整後收盤價，不會因為除權息有巨幅下跌<br>更能夠精確的反映股票價值，跟投資的獲利狀況！</p>



<h3 id="Python-終於開始了">Python 終於開始了</h3>



<p>首先我們先將所有指數的&nbsp;<code>Adj Close</code>&nbsp;先集合起來，變成一張表格(dataframe)</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">close = {}
for name, price in world_index_history.items():
    if len(price) != 0:
        close[name] = price['Close']

close = pd.DataFrame(close)
close = close.resample('1d').last().dropna(how='all', axis=1).dropna(how='all', axis=0)</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="433" src="http://34.96.136.135/wp-content/uploads/2020/07/5-3-1024x433.png" alt="5 3" class="wp-image-881" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/5-3-1024x433.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/5-3-300x127.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/5-3-768x325.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/5-3-1536x650.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/5-3-2048x867.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 4)：台股的好兄弟是？台股相關性研究 31"></figure></div>


<p><a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B84%E7%9B%B8%E9%97%9C%E6%80%A7%E5%88%86%E6%9E%90/5.png"></a></p>



<p>接下來就可以來觀察每檔指數的&nbsp;<code>Adj Close</code>&nbsp;相關性，</p>



<pre class="wp-block-code"><code lang="python" class="language-python">corr = close.corr()
print(corr)</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1022" height="544" src="http://34.96.136.135/wp-content/uploads/2020/07/6-2.png" alt="6 2" class="wp-image-882" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/6-2.png 1022w, https://www.finlab.tw/wp-content/uploads/2020/07/6-2-300x160.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/6-2-768x409.png 768w" sizes="(max-width: 1022px) 100vw, 1022px" title="Python新手教學(Part 4)：台股的好兄弟是？台股相關性研究 32"></figure></div>


<p><a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B84%E7%9B%B8%E9%97%9C%E6%80%A7%E5%88%86%E6%9E%90/6.png"></a></p>



<p>上圖可以看到一個二維的表，就是每個指數跟每個指數之間的相關性，<br>上圖中可以發現，指數自己跟自己的相關性一定是1，代表完全正相關！<br>而這張表會是symmetric matrix，也就是做對角線會是對稱的。</p>



<p>接下來我們可以用更視覺化的方式來表示，假如沒有sns的package，要記得先去安裝<code>pip install sns</code>即可，想瞭解如何安裝，可以到<a href="https://www.finlab.tw/Python%E8%82%A1%E7%A5%A8%E6%8A%95%E8%B3%87/">此安裝教學</a>的下半部分，有簡單的教學喔！</p>



<pre class="wp-block-code"><code lang="python" class="language-python">import seaborn as sns
sns.heatmap(corr, square=True ,vmax=1.0, linecolor='white', annot=True)</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="988" src="http://34.96.136.135/wp-content/uploads/2020/07/last-1-2-1024x988.png" alt="last 1 2" class="wp-image-884" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/last-1-2-1024x988.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/last-1-2-300x289.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/last-1-2-768x741.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/last-1-2.png 1108w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 4)：台股的好兄弟是？台股相關性研究 33"></figure></div>


<p><a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B84%E7%9B%B8%E9%97%9C%E6%80%A7%E5%88%86%E6%9E%90/last.png"></a></p>



<p>假如你發現圖比我的小，字看不清楚，可以改成以下程式碼</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers"># set figure size
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (18, 18)

# original code
import seaborn as sns
sns.heatmap(corr, square=True ,vmax=1.0, linecolor='white', annot=True)
</code></pre>



<p>有了以上的code，我們就可以知道</p>



<h3 id="台灣股票跟誰最連動">台灣股票跟誰最連動</h3>



<p>我們可以人眼觀察，發現台灣指數<code>TSEC weighted index</code>跟英國前一百大<code>Cboe UK 100</code>超像！相關係數高達0.9，代表非常非常像</p>



<p>我們可以將這兩個指數畫出來檢查一下：</p>



<pre class="wp-block-code"><code class="">close['Cboe UK 100']['2015':].plot()
close['TSEC weighted index']['2015':].plot()</code></pre>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="343" src="http://34.96.136.135/wp-content/uploads/2020/07/7-1-1024x343.png" alt="7 1" class="wp-image-886" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/7-1-1024x343.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/7-1-300x100.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/7-1-768x257.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/7-1-1536x514.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/7-1-2048x686.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="Python新手教學(Part 4)：台股的好兄弟是？台股相關性研究 34"></figure></div>


<p><a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B84%E7%9B%B8%E9%97%9C%E6%80%A7%E5%88%86%E6%9E%90/7.png"></a></p>



<p>雖然價格不同，但是趨勢還真的頗像的耶！然而台灣的加權指數，在2020年的價格，跟某幾個美國的指數相關性非常高，究竟是哪一個指數呢？可以使用<a href="https://colab.research.google.com/drive/1W-pA4jdlPVfil9WZqsRK0Nd8Mel4tMlx?usp=sharing" class="rank-math-link" target="_blank" rel="noopener">我們寫好的colab範例</a>跑跑看喔！</p>



<h3 id="如何用於交易？">如何用於交易？</h3>



<p>兩個相關性很高的股票，可以拿來做pair trading配對交易，但也不是只看相關性，<br>這個就容我們之後再慢慢分析吧！<br>這個單元會一直帶你從零開始，慢慢學習，直到機器學習的部分喔！敬請期待～<br>下一個單元中，我們來看一下<a href="https://www.finlab.tw/Python%E6%96%B0%E6%89%8B%E6%95%99%E5%AD%B8%EF%BC%9A%E9%A2%A8%E9%9A%AA%E8%88%87%E5%A0%B1%E9%85%AC/">要怎麼控制報酬與風險</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/python%e6%96%b0%e6%89%8b%e6%95%99%e5%ad%b84%e7%9b%b8%e9%97%9c%e6%80%a7%e5%88%86%e6%9e%90/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">875</post-id>	</item>
		<item>
		<title>如何用Python獲得上市上櫃股票清單?</title>
		<link>https://www.finlab.tw/python%ef%bc%9a%e5%a6%82%e4%bd%95%e7%8d%b2%e5%be%97%e4%b8%8a%e5%b8%82%e4%b8%8a%e6%ab%83%e8%82%a1%e7%a5%a8%e6%b8%85%e5%96%ae/</link>
					<comments>https://www.finlab.tw/python%ef%bc%9a%e5%a6%82%e4%bd%95%e7%8d%b2%e5%be%97%e4%b8%8a%e5%b8%82%e4%b8%8a%e6%ab%83%e8%82%a1%e7%a5%a8%e6%b8%85%e5%96%ae/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:38 +0000</pubDate>
				<category><![CDATA[PYTHON財經]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[入門教學]]></category>
		<category><![CDATA[爬蟲]]></category>
		<category><![CDATA[程式交易]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=748</guid>

					<description><![CDATA[接下來為期幾天，將為大家打下python更深刻的基礎，適合剛學python，但是對pandas不太熟的讀者，這次我們就來把所有的股票代號給爬下來，並整理一番喔！]]></description>
										<content:encoded><![CDATA[
<p>接下來為期幾天，將為大家打下python更深刻的基礎，適合剛學python，但是對pandas不太熟的讀者，這次我們就來把所有的股票代號給爬下來，並整理一番喔！</p>



<p>Python真的很厲害～可以用少少的語法達到非常多的功能<br>我覺得python搭配excel是沒有必要的，直接使用python替代excel才是最佳的方式！<a href="https://www.finlab.tw/Python%EF%BC%9A%E5%A6%82%E4%BD%95%E7%8D%B2%E5%BE%97%E4%B8%8A%E5%B8%82%E4%B8%8A%E6%AB%83%E8%82%A1%E7%A5%A8%E6%B8%85%E5%96%AE/6.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="643" src="http://34.96.136.135/wp-content/uploads/2020/07/6-1-1024x643.png" alt="6 1" class="wp-image-750" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/6-1-1024x643.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/6-1-300x188.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/6-1-768x482.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/6-1-1536x965.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/6-1.png 1592w" sizes="(max-width: 1024px) 100vw, 1024px" title="如何用Python獲得上市上櫃股票清單? 35"></figure></div>



<p>這禮拜終於比較悠閒一點，開始寫blog了，目前主要還是繼續培養大家的python實力為主，因為有一些同學說明課程有些地方跳的比較快，其實可以參考一些網路上免費的python課程來補齊，不過此blog也會隨時補充一些實用的功能，或是簡單的 python 常用的package和語法，幫助大家熟練 python。</p>



<p>今天要做的就是取得上市櫃股票代號與分類，首先，我們想要爬的網頁是：<br><a href="http://isin.twse.com.tw/isin/C_public.jsp?strMode=2" rel="noreferrer noopener" target="_blank">http://isin.twse.com.tw/isin/C_public.jsp?strMode=2</a></p>



<p>其中<code>strMode=2</code>就是上市，而<code>strMode=4</code>就是上櫃，接下來我們就來將此網頁下載下來吧！</p>



<h3 id="爬取網頁">爬取網頁</h3>



<pre class="wp-block-code"><code class="">import requests

res = requests.get("http://isin.twse.com.tw/isin/C_public.jsp?strMode=2")</code></pre>



<p>其中，我們使用了常用的 package 叫做 requests，可以模擬網頁瀏覽器，其中&nbsp;<code>requests.get</code>&nbsp;就是模擬我們連到該網頁，下載網頁的原始碼～<a href="https://www.finlab.tw/Python%EF%BC%9A%E5%A6%82%E4%BD%95%E7%8D%B2%E5%BE%97%E4%B8%8A%E5%B8%82%E4%B8%8A%E6%AB%83%E8%82%A1%E7%A5%A8%E6%B8%85%E5%96%AE/1.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="360" src="http://34.96.136.135/wp-content/uploads/2020/07/1-1-1024x360.png" alt="1 1" class="wp-image-751" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/1-1-1024x360.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/1-1-300x106.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/1-1-768x270.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/1-1-1536x540.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/1-1-2048x720.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="如何用Python獲得上市上櫃股票清單? 36"></figure></div>



<h3 id="將網頁轉成-DataFrame">將網頁轉成 DataFrame</h3>



<p>我們用了上述的程式碼，就可以獲得該網頁的原始碼，瀏覽器就是用這些原始碼渲染成網頁讓您操作的，我們可以從網頁原始碼中萃取出表格，產生 DataFrame</p>



<pre class="wp-block-code"><code class="">import pandas as pd

df = pd.read_html(res.text)[0]
df</code></pre>



<p>第一行：<code>pd</code>&nbsp;就是我們萃取原始碼的package，全名叫做&nbsp;<code>pandas</code>&nbsp;，你可以想像&nbsp;<code>pandas</code>&nbsp;就是 python 界的&nbsp;<code>excel</code>&nbsp;軟體，可以操作各式各樣的表格，進行運算。</p>



<p>第三行：我們可以利用&nbsp;<code>pd.read_html</code>&nbsp;將我們剛剛爬取到的網頁原始碼&nbsp;<code>res.text</code>&nbsp;中的表格給萃取出來，而其中&nbsp;<code>[0]</code>&nbsp;是指說，萃取出來的可能有很多張表格，我們只需要第一張表格即可～<a href="https://www.finlab.tw/Python%EF%BC%9A%E5%A6%82%E4%BD%95%E7%8D%B2%E5%BE%97%E4%B8%8A%E5%B8%82%E4%B8%8A%E6%AB%83%E8%82%A1%E7%A5%A8%E6%B8%85%E5%96%AE/2.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="396" src="http://34.96.136.135/wp-content/uploads/2020/07/2-1-1024x396.png" alt="2 1" class="wp-image-752" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/2-1-1024x396.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/2-1-300x116.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/2-1-768x297.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/2-1-1536x594.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/2-1-2048x792.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="如何用Python獲得上市上櫃股票清單? 37"></figure></div>



<h3 id="整理資料-1-整理column名稱">整理資料 1 整理column名稱</h3>



<p>可以看到上圖，目前column名稱只是1、2、3、4，一些數字而已，但我們希望它們是有意義的文字，而我們又可以發現，其中第一行row，就是我們所需要的，所以，我們可以將第一行變成columns的名稱：</p>



<pre class="wp-block-code"><code class=""># 設定column名稱
df.columns = df.iloc[0]
# 刪除第一行
df = df.iloc[1:]</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="413" src="http://34.96.136.135/wp-content/uploads/2020/07/3-2-1024x413.png" alt="3 2" class="wp-image-754" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/3-2-1024x413.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/3-2-300x121.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/3-2-768x310.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/3-2-1536x620.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/3-2-2048x827.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="如何用Python獲得上市上櫃股票清單? 38"></figure></div>



<p><a href="https://www.finlab.tw/Python%EF%BC%9A%E5%A6%82%E4%BD%95%E7%8D%B2%E5%BE%97%E4%B8%8A%E5%B8%82%E4%B8%8A%E6%AB%83%E8%82%A1%E7%A5%A8%E6%B8%85%E5%96%AE/3.png"></a></p>



<h3 id="整理資料-2-刪除冗餘行列">整理資料 2 刪除冗餘行列</h3>



<p>接下來我們發現整理好column名稱後，還是有一些row很明顯是多餘的，我們必須要把它們刪除，刪除的方式，最簡單就是使用&nbsp;<code>dropna</code>，並且設定當&nbsp;<code>row</code>&nbsp;或是&nbsp;<code>column</code>&nbsp;的&nbsp;<code>NaN</code>&nbsp;數量大於某個數字（例如3）時，我們就將該&nbsp;<code>column</code>&nbsp;或&nbsp;<code>row</code>&nbsp;移除：</p>



<pre class="wp-block-code"><code class=""># 先移除row，再移除column，超過三個NaN則移除
df = df.dropna(thresh=3, axis=0).dropna(thresh=3, axis=1)</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="363" src="http://34.96.136.135/wp-content/uploads/2020/07/4-1-1024x363.png" alt="4 1" class="wp-image-755" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/4-1-1024x363.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/4-1-300x106.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/4-1-768x272.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/4-1-1536x544.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/4-1-2048x725.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="如何用Python獲得上市上櫃股票清單? 39"></figure></div>



<p><a href="https://www.finlab.tw/Python%EF%BC%9A%E5%A6%82%E4%BD%95%E7%8D%B2%E5%BE%97%E4%B8%8A%E5%B8%82%E4%B8%8A%E6%AB%83%E8%82%A1%E7%A5%A8%E6%B8%85%E5%96%AE/4.png"></a></p>



<h3 id="設定index">設定index</h3>



<p>我們可以看到index目前也是數字，我們希望它是股票代號，則可以使用</p>



<pre class="wp-block-code"><code class="">df = df.set_index('有價證券代號及名稱')</code></pre>



<p>即可！<a href="https://www.finlab.tw/Python%EF%BC%9A%E5%A6%82%E4%BD%95%E7%8D%B2%E5%BE%97%E4%B8%8A%E5%B8%82%E4%B8%8A%E6%AB%83%E8%82%A1%E7%A5%A8%E6%B8%85%E5%96%AE/5.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="367" src="http://34.96.136.135/wp-content/uploads/2020/07/5-1024x367.png" alt="5" class="wp-image-756" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/5-1024x367.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/5-300x107.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/5-768x275.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/5-1536x550.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/5-2048x733.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="如何用Python獲得上市上櫃股票清單? 40"></figure></div>



<p>由今天的練習，我們學到了使用&nbsp;<code>requests</code>&nbsp;來模擬瀏覽器，用&nbsp;<code>pandas</code>&nbsp;解析出網頁中的 table，並且利用&nbsp;<code>pandas</code>&nbsp;中的功能，將 table 作整理！</p>



<p>博士班口試結束了，接下來我會盡力開始維持blog正常出貨！也希望能提供更多的選股、程式上的教學！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/python%ef%bc%9a%e5%a6%82%e4%bd%95%e7%8d%b2%e5%be%97%e4%b8%8a%e5%b8%82%e4%b8%8a%e6%ab%83%e8%82%a1%e7%a5%a8%e6%b8%85%e5%96%ae/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">748</post-id>	</item>
		<item>
		<title>python上櫃資料爬蟲輕鬆做</title>
		<link>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/</link>
					<comments>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/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:22 +0000</pubDate>
				<category><![CDATA[PYTHON財經]]></category>
		<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[爬蟲]]></category>
		<category><![CDATA[股票]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=657</guid>

					<description><![CDATA[謝謝各位的支持，有很多人寄信來問各式各樣不同的研究！但因為討論熱烈，我目前先挑比較簡單的做，其它的在清單中，依序補上。最近發現上櫃的股票也滿多人在看的，今天教大家如何用python抓取上櫃公司的收盤價！]]></description>
										<content:encoded><![CDATA[
<p>謝謝各位的支持，有很多人寄信來問各式各樣不同的研究！<br>但因為討論熱烈，我目前先挑比較簡單的做，其它的在清單中，依序補上～<br>最近發現上櫃的股票也滿多人在看的，今天教大家如何用python抓取上櫃公司的收盤價！<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/thumbnail.jpeg"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="259" height="194" src="http://34.96.136.135/wp-content/uploads/2020/07/thumbnail-4.jpeg" alt="thumbnail 4" class="wp-image-658" title="python上櫃資料爬蟲輕鬆做 41"></figure></div>



<p>首先，我們只要從這個網址，把資料get下來就行了！</p>



<p>爬取上櫃股價網址</p>



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

link = 'http://www.tpex.org.tw/web/stock/aftertrading/daily_close_quotes/stk_quote_download.php?l=zh-tw&amp;d=107/02/09&amp;s=0,asc,0'
r = requests.get(link)
r.ok</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="134" src="http://34.96.136.135/wp-content/uploads/2020/07/get-1024x134.png" alt="get" class="wp-image-659" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/get-1024x134.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/get-300x39.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/get-768x101.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/get.png 1121w" sizes="(max-width: 1024px) 100vw, 1024px" title="python上櫃資料爬蟲輕鬆做 42"></figure></div>



<p><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/get.png"></a>可以看到網址中，包含了日期：107/02/09，這個字樣，可以改成其它日期。<br>get下來就是csv檔了！直接丟進pandas：</p>



<p>使用pandas讀取</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">lines = r.text.replace('\r', '').split('\n')

import pandas as pd
from io import StringIO
df = pd.read_csv(StringIO("\n".join(lines[3:])), header=None)
df.head()</code></pre>



<p>但我發現一個小問題：</p>



<ul><li>在csv檔中，第一行是：”a”,”b”,”c”</li><li>但是在其它行，則顯示：a,b,c</li></ul>



<p>有沒有雙引號很重要，會讓pandas沒辦法直接讀進來，所以我們前面幾行先去除（上段code中<code>lines[3:]</code>）</p>



<p>就可以得到下圖：<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/unindex.png"></a></p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="307" src="http://34.96.136.135/wp-content/uploads/2020/07/unindex-1024x307.png" alt="unindex" class="wp-image-660" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/unindex-1024x307.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/unindex-300x90.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/unindex-768x230.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/unindex.png 1124w" sizes="(max-width: 1024px) 100vw, 1024px" title="python上櫃資料爬蟲輕鬆做 43"></figure>



<p>但我們的index跟column都還沒設定好（都是數字），要把它轉換成有意義的label：</p>



<p>整理index跟columns</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">df.columns = list(map(lambda l: l.replace(' ',''), lines[2].split(',')))
df.index = df['代號']
df = df.drop(['代號'], axis=1)
df.head()</code></pre>



<p>首先先來換column，裡面有些複雜的程式（第一行）慢慢講解：</p>



<ol><li><code>lambda l: l.replace(' ','')</code>&nbsp;是一個函式，但是我懶得命名，所以就用&nbsp;<code>lambda</code>&nbsp;賴省略函式名稱，它會讀入，這個函式讀入&nbsp;<code>l</code>，並將<code>l</code>裡面的空白刪除並outpu出來。</li><li>其中的<code>map(func, array)</code>就指：將<code>array</code>裡面所有元素，都用<code>func</code>處理一遍。</li><li><code>line[2].split(',')</code>：將字串依照 “,” 分割成好幾個小字串。</li></ol>



<p>總體來說，就是將資串分割-&gt;針對每個子字串刪除空白。</p>



<p>另外針對<code>index</code>，我們就單純用<code>df.index = df['代號']</code>來設定，並用<code>df.drop</code>將原本的&nbsp;<code>column</code>刪除，<br>其實知道pandas有<code>df.set_index()</code>這個函式，但是發現存檔怪怪的，所以改用途法煉鋼（第2、3行）</p>



<p>這樣差不多就完成了：<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/index.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="360" src="http://34.96.136.135/wp-content/uploads/2020/07/index-1024x360.png" alt="index" class="wp-image-661" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/index-1024x360.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/index-300x105.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/index-768x270.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/index.png 1119w" sizes="(max-width: 1024px) 100vw, 1024px" title="python上櫃資料爬蟲輕鬆做 44"></figure></div>



<p>那要如何把檔案存起來呢？</p>



<p>我們可以利用save file</p>



<pre class="wp-block-code"><code lang="python" class="language-python">df.to_csv('test.csv')
pd.read_csv('test.csv', index_col='代號').head()</code></pre>



<p>來存檔跟讀檔喔！跑出來會是一模一樣的！<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/save.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="329" src="http://34.96.136.135/wp-content/uploads/2020/07/save-1024x329.png" alt="save" class="wp-image-662" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/save-1024x329.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/save-300x97.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/save-768x247.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/save.png 1119w" sizes="(max-width: 1024px) 100vw, 1024px" title="python上櫃資料爬蟲輕鬆做 45"></figure></div>



<p>今天的簡易教學就到這邊！可以下載下來玩玩看喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>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/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">657</post-id>	</item>
		<item>
		<title>三大法人爬蟲：Python實作教學</title>
		<link>https://www.finlab.tw/%e4%b8%89%e5%a4%a7%e6%b3%95%e4%ba%ba%e7%88%ac%e8%9f%b2/</link>
					<comments>https://www.finlab.tw/%e4%b8%89%e5%a4%a7%e6%b3%95%e4%ba%ba%e7%88%ac%e8%9f%b2/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:22 +0000</pubDate>
				<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[爬蟲]]></category>
		<category><![CDATA[程式交易]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=714</guid>

					<description><![CDATA[三大法人是台灣獨有的資料，每一檔股票每天都會公佈，非常實用！
之前也有介紹利用「投信買賣超」來交易的策略，相信如有看到並使用過的人，就知道它的威力！]]></description>
										<content:encoded><![CDATA[
<p>三大法人是台灣獨有的資料，每一檔股票每天都會公佈，非常實用！<br>之前也有介紹<a href="https://www.finlab.tw/%E6%8A%95%E4%BF%A1%E8%B7%9F%E7%9B%A4%E6%B3%95%EF%BC%81/">利用「投信買賣超」來交易的策略</a>，相信如有看到並使用過的人，就知道它的威力！<a href="https://www.finlab.tw/%E4%B8%89%E5%A4%A7%E6%B3%95%E4%BA%BA%E7%88%AC%E8%9F%B2/thumbnail.jpeg"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="683" src="http://34.96.136.135/wp-content/uploads/2020/07/thumbnail-1-3-1024x683.jpeg" alt="thumbnail 1 3" class="wp-image-715" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-1-3-1024x683.jpeg 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-1-3-300x200.jpeg 300w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-1-3-768x512.jpeg 768w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-1-3.jpeg 1050w" sizes="(max-width: 1024px) 100vw, 1024px" title="三大法人爬蟲：Python實作教學 46"></figure></div>



<p>三大法人買賣超還有很多種用法，我們之後再一一說明，<br>今天最主要就是先獲取到「三大法人」的資料！之後呢，我們會利用這個財經資料<br>來建立一個投信買賣超的簡單策略。</p>



<pre class="wp-block-code"><code class="">import requests
from io import StringIO
import pandas as pd

date = '20180102'
r = requests.get('http://www.tse.com.tw/fund/T86?response=csv&amp;date='+date+'&amp;selectType=ALLBUT0999')#
df = pd.read_csv(StringIO(r.text), header=1).dropna(how='all', axis=1).dropna(how='any')
df</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="897" height="489" src="http://34.96.136.135/wp-content/uploads/2020/07/df-2.png" alt="df 2" class="wp-image-716" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/df-2.png 897w, https://www.finlab.tw/wp-content/uploads/2020/07/df-2-300x164.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/df-2-768x419.png 768w" sizes="(max-width: 897px) 100vw, 897px" title="三大法人爬蟲：Python實作教學 47"></figure></div>



<p><a href="https://www.finlab.tw/%E4%B8%89%E5%A4%A7%E6%B3%95%E4%BA%BA%E7%88%AC%E8%9F%B2/df.png"></a>什麼！這樣就爬好了～！對呀～那請問怎麼把他們都存在資料庫中呢？<br>假如您有上課程的話，可以結合我們寫好的GUI外掛可以用：</p>



<pre class="wp-block-code"><code class=""># finlab 軟體包要上課才有喔～
from finlab.crawler import widget, date_range

# 讀入一些package
import sqlite3
import os
import requests
from io import StringIO
import pandas as pd

# 爬取資料
def crawl_legal_person(date):
    
    # 將時間物件變成字串：'20180102'
    datestr = date.strftime('%Y%m%d')
    
    # 下載三大法人資料
    try:
        r = requests.get('http://www.tse.com.tw/fund/T86?response=csv&amp;date='+datestr+'&amp;selectType=ALLBUT0999')#
    except:
        return None

    # 製作三大法人的DataFrame
    try:
        df = pd.read_csv(StringIO(r.text), header=1).dropna(how='all', axis=1).dropna(how='any')
    except:
        return None
    
    # 微調整（為了配合資料庫的格式）

    # 刪除逗點
    df = df.astype(str).apply(lambda s: s.str.replace(',',''))

    # 刪除「證券代號」中的「"」和「=」
    df['stock_id'] = df['證券代號'].str.replace('=','').str.replace('"','')

    # 刪除「證券代號」這個欄位
    df = df.drop(['證券代號'], axis=1)

    # 設定index
    df['date'] = date
    df = df.set_index(['stock_id', 'date'])
    
    # 將dataframe的型態轉成數字
    return df.apply(lambda s: pd.to_numeric(s, errors='coerce')).dropna(how='all', axis=1)

# 打開資料庫
conn = sqlite3.connect(os.path.join('data', 'data.db'))

# 開啟GUI介面
widget(conn, 'legal_person', crawl_legal_person, date_range)</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="707" height="528" src="http://34.96.136.135/wp-content/uploads/2020/07/gui.png" alt="gui" class="wp-image-717" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/gui.png 707w, https://www.finlab.tw/wp-content/uploads/2020/07/gui-300x224.png 300w" sizes="(max-width: 707px) 100vw, 707px" title="三大法人爬蟲：Python實作教學 48"></figure></div>



<p><a href="https://www.finlab.tw/%E4%B8%89%E5%A4%A7%E6%B3%95%E4%BA%BA%E7%88%AC%E8%9F%B2/gui.png"></a>才多加幾行，我們就將GUI的插件給寫好了～<br>可以調整時間範圍，來下載每天的三大法人買賣超，並且存在資料庫裡面～<br>下一次我們就來實做三大法人的策略囉！敬請期待～！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/%e4%b8%89%e5%a4%a7%e6%b3%95%e4%ba%ba%e7%88%ac%e8%9f%b2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">714</post-id>	</item>
	</channel>
</rss>
