<?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%BE%8E%E8%82%A1/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.finlab.tw</link>
	<description>深入淺出的量化投資，讓你在在茫茫股海中，找到專屬於自己的投資方法</description>
	<lastBuildDate>Fri, 07 Jul 2023 12:31:10 +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>美股探險記第4課:美股選股池分類器使用教學｜本益成長比最適合用在哪些產業？</title>
		<link>https://www.finlab.tw/us_stock_industry_peg/</link>
					<comments>https://www.finlab.tw/us_stock_industry_peg/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Fri, 07 Jul 2023 03:49:18 +0000</pubDate>
				<category><![CDATA[VIP文章]]></category>
		<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[股票策略]]></category>
		<category><![CDATA[PEG]]></category>
		<category><![CDATA[VIP限定]]></category>
		<category><![CDATA[產業分析]]></category>
		<category><![CDATA[美股]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=5424</guid>

					<description><![CDATA[美股該如何選股？如果你有實際開發過美股策略，會發現一件很奇怪的事，那就是台股有用的策略，在美股幾乎都失效。除了 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">美股該如何選股？如果你有實際開發過美股策略，會發現一件很奇怪的事，那就是台股有用的策略，在美股幾乎都失效。除了高效率市場的因素，我想還有一個關鍵假設，那就是選股池的影響性。<br>我們知道每個產業適用的指標不同，像本益比指標可能就不適合在獲利起伏很大的行業，例如原物料、營造，而在獲利穩定比較高的產業較具指標意義。<br>如果沒縮小選股池，針對特定產業找出指標，那就像在大海撈針，會對基本面選股有很大的影響美國是全球最大的資本市場，上市交易的標地很多，達上萬檔，細產業也分散到上百個，不像台股集中在製造業與電子業，就算台股沒分類，也很容易找到通用全市場的指標，但美股直接全市場選股，很容易因產業一致性的缺乏，導致許多雜訊出來，例如挑本益比低於10倍的股票，在A產業偏低，但在B產業是偏高，不可混為一談。</p>



<figure class="wp-block-image"><img src="https://pineapple-centaur-13d.notion.site/image/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2F7215288f-c611-4162-8b08-4def11a666a9%2Fnewplot_(12).png?id=3c3e1f3c-9626-4a5c-8cba-dec340bc7a7c&amp;table=block&amp;spaceId=9ed484a1-504e-442b-b113-ec69267e5d7a&amp;width=2000&amp;userId=&amp;cache=v2" alt="https%3A%2F%2Fs3 us west 2.amazonaws.com%2Fsecure.notion static.com%2F7215288f c611 4162 8b08 4def11a666a9%2Fnewplot (12)" title="美股探險記第1課:為什麼要投資美股？ 5"/><figcaption>台股製造業數據</figcaption></figure>



<p class="has-medium-font-size">為解決選股池的問題，FinLab Package 在 0.4.5 的版本開發了<a href="https://doc.finlab.tw/reference/data/#finlab.data.us_universe" target="_blank" rel="noopener">美股選股池控制</a>的功能，利用短短的程式碼，就能對美股做不同層級的分類，接下來會向大家介紹如何使用此功能，並找出本益成長比最適合用在哪些產業？</p>



<h2>美股選股池分類</h2>



<p class="has-medium-font-size">此功能的用途在當呼叫&nbsp;<code>data.get</code>&nbsp;或是&nbsp;<code>data.indicator</code>&nbsp;時，返回美股產業相關類股。<br>和台股不同的地方在美股因標的範圍較大，有4個篩選變數可以控制，預設都是全選。<br>細節請見<a href="https://doc.finlab.tw/reference/data/#finlab.data.us_universe" target="_blank" rel="noopener">美股選股池控制</a>的功能。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="824" src="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-上午8.31.30-1024x824.png" alt="截圖 2023 07 07 上午8.31.30" class="wp-image-5425" srcset="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-上午8.31.30-1024x824.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-上午8.31.30-300x241.png 300w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-上午8.31.30-768x618.png 768w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-上午8.31.30.png 1446w" sizes="(max-width: 1024px) 100vw, 1024px" title="美股探險記第4課:美股選股池分類器使用教學｜本益成長比最適合用在哪些產業？ 1"></figure>



<h3>參數說明</h3>



<ul class="has-medium-font-size"><li>market：證券種類，採取模糊比對。<br>若設定為 Common Stock ，則會篩選出美國國內上市企業與 ADR (海外存託憑證:外國公司在美國二次上市) 的普通股，不會選到一些流動性比較低的特別股。<br>若想排除 ADR，則可以設定為 Domestic Common Stock，就只會選到美國國內上市企業。</li><li>sector：產業主板塊，可視為比較粗略的產業分類。像是美股有許多高科技公司很吸引人，若想選定標的在科技股，將此參數設定為 Technology 。</li><li>industry：細產業，可視為比較細的產業分類，由於細產業很多，不方便一一列在文件上，我們可在<a href="https://ai.finlab.tw/database#%E7%BE%8E%E8%82%A1%E4%BC%81%E6%A5%AD%E5%9F%BA%E6%9C%AC%E8%B3%87%E8%A8%8A" target="_blank" rel="noopener">美股企業基本資訊</a>的資裡中找到資料，利用以下程式碼取得細產業索引： <code>set(data.get('us_tickers')['industry'])</code>。像是美股科技股中的軟體公司很吸引人，若想選定標的在軟體股，將此參數設定為 Software &#8211; Application 。</li><li>exchange：交易所。不同的交易所有不同的主流標地及規範。偏愛科技股或新創的，可選NASDAQ。<br>紐約證券交易所（New York Stock Exchange，簡稱NYSE）和納斯達克交易所（NASDAQ）是美國主要的證券交易所，它們在以下幾個方面存在差異：<br>1.交易模式：紐約交易所採用傳統的“交易員制”模式，即交易員在交易所的交易廳內進行股票交易。而納斯達克交易所採用電子交易系統，投資者通過計算機網絡進行交易。<br>2.有吸引力的上市公司類型：紐約交易所主要是大型傳統企業，如跨國公司和傳統產業公司。納斯達克交易所則更有吸引力的科技、生物技術和高成長性公司。<br>3.上市要求：紐約證券交易所對上市公司的要求較為嚴格，包括市值、財務狀況、歷史業績等方面的要求。納斯達克交易較多成長型公司，其上市要求相對較低。<br>4.交易時間：紐約交易所的交易時間為周一至週五上午9:30至下午4:00（美國東部時間）。納斯達克交易所的交易時間也是周一至週五上午9:30至下午4:00 :00，但還提供了一些延長交易時間的選項。<br>5.許多市場地位：紐約交易所是世界上最大、最多的股票交易所之一，吸引了許多大型企業和國際投資者。納斯達克交易所在科技股領域具有越來越大的影響力，吸引了新興市場科技公司和高科技投資者。</li></ul>



<h3>使用範例</h3>



<p class="has-medium-font-size">以下為幾個常用範例，幫助我們將資料限縮在特定範圍，限縮之後，就能針對本質較相近的股票做後續研究。</p>



<h3>限定在美股普通股中的科技類股</h3>



<pre class="wp-block-code"><code lang="python" class="language-python"><a href="https://doc.finlab.tw/reference/data/#__codelineno-0-1" target="_blank" rel="noopener"></a>with us_universe('Common Stock', ['Technology']):
<a href="https://doc.finlab.tw/reference/data/#__codelineno-0-2" target="_blank" rel="noopener"></a>    close_subset = data.get('us_price:close')
<a href="https://doc.finlab.tw/reference/data/#__codelineno-0-3" target="_blank" rel="noopener"></a>    print(close_subset)
</code></pre>



<figure class="wp-block-table has-medium-font-size"><table><thead><tr><th>date</th><th>AAOI</th><th>AAPL</th><th>..</th><th>ABCO</th><th>NVDA</th></tr></thead><tbody><tr><td>2017-01-03</td><td>39.65</td><td>38.3</td><td>..</td><td>7.8</td><td>17.55</td></tr><tr><td>2017-01-04</td><td>39.85</td><td>38.85</td><td>..</td><td>8.34</td><td>17.5</td></tr><tr><td>2017-01-05</td><td>39.25</td><td>38.1</td><td>..</td><td>8.25</td><td>17.3</td></tr><tr><td>2017-01-06</td><td>39</td><td>37.85</td><td>..</td><td>8.2</td><td>17.3</td></tr><tr><td>2017-01-09</td><td>38.2</td><td>37.2</td><td>..</td><td>7.88</td><td>16.6</td></tr></tbody></table></figure>



<h3>限定在美股特別股中的基礎原物料和能源類股</h3>



<pre class="wp-block-code"><code lang="python" class="language-python"><a href="https://doc.finlab.tw/reference/data/#__codelineno-1-1" target="_blank" rel="noopener"></a>with data.us_universe('Preferred Stock', ['Basic Materials','Energy']):
<a href="https://doc.finlab.tw/reference/data/#__codelineno-1-2" target="_blank" rel="noopener"></a>    close_subset = data.get('us_price:close')
<a href="https://doc.finlab.tw/reference/data/#__codelineno-1-3" target="_blank" rel="noopener"></a>    print(close_subset)
</code></pre>



<figure class="wp-block-table has-medium-font-size"><table><thead><tr><th>date</th><th>AEUA</th><th>ALIN-PA</th><th>..</th><th>ALIN-PB</th><th>ALIN-PE</th></tr></thead><tbody><tr><td>2017-01-03</td><td>39.65</td><td>38.3</td><td>..</td><td>7.8</td><td>17.55</td></tr><tr><td>2017-01-04</td><td>39.85</td><td>38.85</td><td>..</td><td>8.34</td><td>17.5</td></tr><tr><td>2017-01-05</td><td>39.25</td><td>38.1</td><td>..</td><td>8.25</td><td>17.3</td></tr><tr><td>2017-01-06</td><td>39</td><td>37.85</td><td>..</td><td>8.2</td><td>17.3</td></tr><tr><td>2017-01-09</td><td>38.2</td><td>37.2</td><td>..</td><td>7.88</td><td>16.6</td></tr></tbody></table></figure>



<h3>限定在美股 NASDAQ 交易所普通股中的軟體類股</h3>



<pre class="wp-block-code"><code lang="python" class="language-python"><a href="https://doc.finlab.tw/reference/data/#__codelineno-2-1" target="_blank" rel="noopener"></a>with data.us_universe('Common Stock', industry='Software', exchange='NASDAQ'):
<a href="https://doc.finlab.tw/reference/data/#__codelineno-2-2" target="_blank" rel="noopener"></a>    close_subset = data.get('us_price:close')
<a href="https://doc.finlab.tw/reference/data/#__codelineno-2-3" target="_blank" rel="noopener"></a>    print(close_subset)
</code></pre>



<figure class="wp-block-table has-medium-font-size"><table><thead><tr><th>date</th><th>ACIW</th><th>ACVA</th><th>..</th><th>ZI</th><th>ZS</th></tr></thead><tbody><tr><td>2017-01-03</td><td>39.65</td><td>38.3</td><td>..</td><td>7.8</td><td>17.55</td></tr><tr><td>2017-01-04</td><td>39.85</td><td>38.85</td><td>..</td><td>8.34</td><td>17.5</td></tr><tr><td>2017-01-05</td><td>39.25</td><td>38.1</td><td>..</td><td>8.25</td><td>17.3</td></tr><tr><td>2017-01-06</td><td>39</td><td>37.85</td><td>..</td><td>8.2</td><td>17.3</td></tr><tr><td>2017-01-09</td><td>38.2</td><td>37.2</td><td>..</td><td>7.88</td><td>16.6</td></tr></tbody></table></figure>



<h3>檢視有哪些細產業可選擇</h3>



<pre class="wp-block-code"><code lang="python" class="language-python"><a href="https://doc.finlab.tw/reference/data/#__codelineno-3-1" target="_blank" rel="noopener"></a>print(set(data.get('us_tickers')['industry']))
</code></pre>



<pre class="wp-block-code"><code class=""><a href="https://doc.finlab.tw/reference/data/#__codelineno-4-1" target="_blank" rel="noopener"></a>{'Advertising Agencies',
<a href="https://doc.finlab.tw/reference/data/#__codelineno-4-2" target="_blank" rel="noopener"></a> 'Aerospace &amp; Defense',
<a href="https://doc.finlab.tw/reference/data/#__codelineno-4-3" target="_blank" rel="noopener"></a> 'Agricultural Inputs',
<a href="https://doc.finlab.tw/reference/data/#__codelineno-4-4" target="_blank" rel="noopener"></a> 'Airlines',
<a href="https://doc.finlab.tw/reference/data/#__codelineno-4-5" target="_blank" rel="noopener"></a> 'Airports &amp; Air Services',
<a href="https://doc.finlab.tw/reference/data/#__codelineno-4-6" target="_blank" rel="noopener"></a> 'Aluminum',
<a href="https://doc.finlab.tw/reference/data/#__codelineno-4-7" target="_blank" rel="noopener"></a> ...}</code></pre>



<h2><span style="font-size: 49.4px;">本益成長比最適合用在哪些產業？</span></h2>



<h3>全市場回測</h3>



<p class="has-medium-font-size">我們來寫一個簡單的本益成長比(PEG)當範例，條件說明如下</p>



<ul class="has-medium-font-size"><li>本益比 &gt; 0：公司近一年獲利要是正數</li><li>營業利益成長率 &gt; 20：公司的獲利能力具一定水準，不是低利潤產業</li><li>營業利益成長率 &gt; 營收成長率：本業獲利成長大於營收成長，代表公司的銷貨是重質不重量。</li><li>篩選出來後，用本益成長比做排序選出本益成長比最低的前10名，若您不了解本益成長比的定義，可參考這篇文章「<a href="https://www.finlab.tw/finlab-tw-stock-peg-strategy/">進化後的本益比｜本益成長比選股策略</a>」。</li><li>每週再平衡。</li><li>停損為10%。<br></li></ul>



<h3>程式碼</h3>



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

本益比 = data.get('us_daily_metrics_all:pe')
營收= data.get('us_fundamental_all:revenue')
營業利益 = data.get('us_fundamental_all:opinc')

def 成長率(s):
    return ((s-s.shift(4)) / s.shift(4).abs()) * 100

營收成長率 = 成長率(營收)
營業利益成長率 = 成長率(營業利益)
peg = (本益比/營業利益成長率)

cond1 = 本益比 &gt; 0
cond2 = 營業利益成長率 &gt; 20
cond3 = 營業利益成長率 &gt; 營收成長率

cond_all = cond1 &amp; cond2 &amp; cond3
position = peg*cond_all
position = position[position &gt; 0].is_smallest(10)

report = sim(resample='W', position=position, fee_ratio=0, tax_ratio=0, stop_loss=0.1, name='美股本益成長比')
report.display()</code></pre>



<h3>回測結果</h3>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="536" src="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午8.06.34-1024x536.png" alt="截圖 2023 07 07 下午8.06.34" class="wp-image-5438" srcset="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午8.06.34-1024x536.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午8.06.34-300x157.png 300w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午8.06.34-768x402.png 768w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午8.06.34-1536x804.png 1536w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午8.06.34.png 1930w" sizes="(max-width: 1024px) 100vw, 1024px" title="美股探險記第4課:美股選股池分類器使用教學｜本益成長比最適合用在哪些產業？ 2"></figure>



<p class="has-medium-font-size">以這麼簡單的條件而言，發現效果相當不錯，接下來我們用選股池分類器來針對不同的板塊做回測。</p>



<h2>板塊分組回測</h2>



<p class="has-medium-font-size">將不同的板塊名稱輸入進選股池分類器，執行迴圈。並使用「<a href="https://doc.finlab.tw/reference/optimize/#finlab.optimize.combinations.ReportCollection" target="_blank" rel="noopener">回測組合比較報告</a>」的功能來比較不同板塊的回測結果。</p>



<h3>程式碼</h3>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab import data
from finlab.backtest import sim
from finlab.optimize.combinations import ReportCollection

dataset = {}

for ind in ['Basic Materials','Communication Services','Consumer Cyclical','Consumer Defensive','Energy','Financial Services','Healthcare','Industrials','Real Estate','Technology','Utilities']:
    with data.us_universe(sector=ind):

        本益比 = data.get('us_daily_metrics:pe')
        營收= data.get('us_fundamental:revenue')
        營業利益 = data.get('us_fundamental:opinc')


        def 成長率(s):
            return ((s-s.shift(4)) / s.shift(4).abs()) * 100

        營收成長率 = 成長率(營收)
        營業利益成長率 = 成長率(營業利益)
        peg = (本益比/營業利益成長率)

        cond1 = 本益比 > 0
        cond2 = 營業利益成長率 > 20
        cond3 = 營業利益成長率 > 營收成長率

        cond_all = cond1 &amp; cond2 &amp; cond3
        position = peg*cond_all
        position = position[position > 0].is_smallest(10)

        report = sim(resample='W', position=position, fee_ratio=0, tax_ratio=0, stop_loss=0.1, name='美股本益成長比', upload=False)
        dataset[ind] = report


indicators=['daily_mean','daily_sharpe','max_drawdown']
report_collection = ReportCollection(dataset)
# 策略分組指標報告
report_collection.plot_creturns().show()
report_collection.plot_stats('bar',indicators=indicators).show()
report_collection.plot_stats('heatmap',indicators=indicators)</code></pre>



<h3>回測結果</h3>



<p class="has-medium-font-size">可以發現「科技股」的報酬率一支獨秀，報酬率的前3名板塊與後3名的差距非常大。<br>綜合評分以「報酬率、夏普率、最大回撤幅度」分級平均計算，前3名依序是「<strong>Consumer Cyclical</strong>、<strong>Financial Services</strong>、<strong>Technology</strong>」。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="521" src="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午7.59.31-1024x521.png" alt="截圖 2023 07 07 下午7.59.31" class="wp-image-5439" srcset="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午7.59.31-1024x521.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午7.59.31-300x153.png 300w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午7.59.31-768x391.png 768w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午7.59.31-1536x782.png 1536w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午7.59.31-2048x1042.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="美股探險記第4課:美股選股池分類器使用教學｜本益成長比最適合用在哪些產業？ 3"></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="926" height="1024" src="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午8.08.57-926x1024.png" alt="截圖 2023 07 07 下午8.08.57" class="wp-image-5440" srcset="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午8.08.57-926x1024.png 926w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午8.08.57-271x300.png 271w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午8.08.57-768x849.png 768w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午8.08.57-1389x1536.png 1389w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午8.08.57.png 1447w" sizes="(max-width: 926px) 100vw, 926px" title="美股探險記第4課:美股選股池分類器使用教學｜本益成長比最適合用在哪些產業？ 4"></figure>



<h2>最終策略</h2>



<p class="has-medium-font-size">將策略範圍的選股池限定在「<strong>Consumer Cyclical</strong>、<strong>Financial Services</strong>、<strong>Technology</strong>」這三個使用本益成長比策略表現較好的板塊，為什麼不要只限定在第一名的產業就好？原因在適當產業多元化，能避免過度集中在特定產業循環的風險，在產業逆風年，個股很難有表現，但如果有做產業分散，就比較有機會抵抗單一產業的逆風時刻。</p>



<h3>程式碼</h3>



<p class="has-medium-font-size">每個產業選10檔股票，再將這3個產業的選股結果合併。</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab import data
from finlab.backtest import sim
import pandas as pd

def sector_postion(sector):
    with data.us_universe(sector=sector):
        本益比 = data.get('us_daily_metrics:pe')
        營收= data.get('us_fundamental:revenue')
        營業利益 = data.get('us_fundamental:opinc')

        def 成長率(s):
            return ((s-s.shift(4)) / s.shift(4).abs()) * 100

        營收成長率 = 成長率(營收)
        營業利益成長率 = 成長率(營業利益)
        peg = (本益比/營業利益成長率)

        cond1 = 本益比 > 0
        cond2 = 營業利益成長率 > 20
        cond3 = 營業利益成長率 > 營收成長率

        cond_all = cond1 &amp; cond2 &amp; cond3
        position = peg*cond_all
        position = position[position > 0].is_smallest(10)
        return position


positions = pd.concat([sector_postion(sector) for sector in ['Consumer Cyclical','Financial Services','Technology']],axis=1)
report = sim(position=positions, resample='W', fee_ratio=0, tax_ratio=0, stop_loss=0.1, name='美股本益成長比', live_performance_start='2021-06-01')</code></pre>



<h3>回測結果</h3>



<figure class="wp-block-image size-large"><img loading="lazy" width="912" height="1024" src="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午8.26.05-912x1024.png" alt="截圖 2023 07 07 下午8.26.05" class="wp-image-5441" srcset="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午8.26.05-912x1024.png 912w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午8.26.05-267x300.png 267w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午8.26.05-768x862.png 768w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-07-下午8.26.05.png 1127w" sizes="(max-width: 912px) 100vw, 912px" title="美股探險記第4課:美股選股池分類器使用教學｜本益成長比最適合用在哪些產業？ 5"></figure>



<p class="has-medium-font-size">撋報酬率降低一些，但夏普率和最大回撤幅度與原先的結果相比則有明顯提升。<br>還在為優化策略所苦嗎？你絕對不能錯過 <a href="https://doc.finlab.tw/reference/data/#finlab.data.us_universe" target="_blank" rel="noopener">美股選股池控制</a> 這個好用功能，趕緊來試試吧！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/us_stock_industry_peg/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5424</post-id>	</item>
		<item>
		<title>美股探險記第3課:1分鐘上手美股回測｜股價淨值比在美股策略還有效嗎？</title>
		<link>https://www.finlab.tw/us_start_build_pb_strategy_backtest/</link>
					<comments>https://www.finlab.tw/us_start_build_pb_strategy_backtest/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Sun, 02 Jul 2023 10:51:58 +0000</pubDate>
				<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[股票策略]]></category>
		<category><![CDATA[回測]]></category>
		<category><![CDATA[美股]]></category>
		<category><![CDATA[股價淨值比]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=5410</guid>

					<description><![CDATA[回測的美國航班即將起飛！ 我們在年初時，就有做過問卷調查，大家最希望的是有美股資料的功能，我們幫各位購買，並整 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">回測的美國航班即將起飛！</p>



<p class="has-medium-font-size">我們在年初時，就有做過問卷調查，大家最希望的是有美股資料的功能，我們幫各位購買，並整合了<a href="https://www.finlab.tw/us_database_doc/"> Sharadar 美股資料</a>，經歷了長達半年的馬拉松，終於將原本的台股系統，兼容美股的程式碼，可以無腦銜接！用你熟悉的語法，做其他國家市場的股票！只有一個爽字，雖然語法一樣，但是我們發現台股美股差異滿大的，策略都要重新研發，不太能直接移植。這邊我們先提供基礎範例，就先交給大家來一起研究啦！另外有個小缺點&#8230;就是資料商只允許在網頁上使用～所以當前只能在網頁上進行回測。</p>



<p class="has-medium-font-size"><br>這篇教學的目的在教大家如何快速上手策略開發，以及驗證一下台股策略的模板能不能完美複製到美股？還是會面臨失效的無情打擊？</p>



<h2>建立你第一個美股策略</h2>



<h2>複製策略</h2>



<p class="has-medium-font-size">在對一切都還是未知的情況下，最快的上手方式就是模仿。以下幾個簡單的步驟帶你複製FinLab 策略範例，走過回測策略的流程。<br>首先進入 <a href="https://ai.finlab.tw/strategies?tab=FinLab%E7%BE%8E%E8%82%A1" target="_blank" rel="noopener">FinLab的美股策略實驗室</a> ，點選「<a class="" href="https://ai.finlab.tw/strategyview/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=%E7%BE%8E%E8%82%A1_%E4%BD%8E%E8%82%A1%E5%83%B9%E6%B7%A8%E5%80%BC%E6%AF%94" target="_blank" rel="noopener">美股_低股價淨值比</a>」，這是免費開放給所有人的策略範例，不是VIP也可以試用。<br>之前在台股的<a href="https://ai.finlab.tw/notebook/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=%E8%82%A1%E5%83%B9%E6%B7%A8%E5%80%BC%E6%AF%94%E7%AD%96%E7%95%A5&amp;cid=sotMOMPufPwDHgGw8LQV" target="_blank" rel="noopener">策略教學</a>中很經典的策略，短短的程式碼就有不錯的效果，你若對細節有興趣，可以去看<a href="https://ai.finlab.tw/notebook/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=%E8%82%A1%E5%83%B9%E6%B7%A8%E5%80%BC%E6%AF%94%E7%AD%96%E7%95%A5&amp;cid=sotMOMPufPwDHgGw8LQV" target="_blank" rel="noopener">影音教學</a>，現在只是單純把資料換成美股，究竟表現回如何呢？<br>如果你是已經用過我們台股策略回測的朋友，那你會對多數步驟非常熟悉。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="580" src="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午5.58.53-1024x580.png" alt="截圖 2023 07 02 下午5.58.53" class="wp-image-5411" srcset="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午5.58.53-1024x580.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午5.58.53-300x170.png 300w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午5.58.53-768x435.png 768w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午5.58.53-1536x869.png 1536w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午5.58.53-2048x1159.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="美股探險記第3課:1分鐘上手美股回測｜股價淨值比在美股策略還有效嗎？ 6"></figure>



<p class="has-medium-font-size">點選進入後會看到策略的回測數據和「<a class="" href="https://ai.finlab.tw/strategyview/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=%E7%BE%8E%E8%82%A1_%E4%BD%8E%E8%82%A1%E5%83%B9%E6%B7%A8%E5%80%BC%E6%AF%94" target="_blank" rel="noopener">美股_低股價淨值比</a>」選股清單，點選右上角進入程式碼。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="565" src="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.08.12-1024x565.png" alt="截圖 2023 07 02 下午6.08.12" class="wp-image-5412" srcset="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.08.12-1024x565.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.08.12-300x166.png 300w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.08.12-768x424.png 768w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.08.12-1536x847.png 1536w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.08.12.png 1865w" sizes="(max-width: 1024px) 100vw, 1024px" title="美股探險記第3課:1分鐘上手美股回測｜股價淨值比在美股策略還有效嗎？ 7"></figure>



<p class="has-medium-font-size">接著你會看到程式碼，你可以先不用理解程式的部分，先點選「複製策略」。</p>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" src="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.09.17-1024x547.png" alt="截圖 2023 07 02 下午6.09.17" class="wp-image-5413" width="840" height="448" srcset="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.09.17-1024x547.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.09.17-300x160.png 300w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.09.17-768x410.png 768w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.09.17-1536x820.png 1536w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.09.17.png 1644w" sizes="(max-width: 840px) 100vw, 840px" title="美股探險記第3課:1分鐘上手美股回測｜股價淨值比在美股策略還有效嗎？ 8"></figure>



<p class="has-medium-font-size">接著會要求您重新命名策略，就完成複製策略的步驟，您之後可在「<a href="https://ai.finlab.tw/strategies?tab=%E6%88%91%E7%9A%84%E7%AD%96%E7%95%A5" target="_blank" rel="noopener">我的策略</a>」頁面看到您複製的策略。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="394" src="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.09.34-1024x394.png" alt="截圖 2023 07 02 下午6.09.34" class="wp-image-5414" srcset="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.09.34-1024x394.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.09.34-300x116.png 300w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.09.34-768x296.png 768w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.09.34-1536x591.png 1536w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.09.34-2048x789.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="美股探險記第3課:1分鐘上手美股回測｜股價淨值比在美股策略還有效嗎？ 9"></figure>



<h2>執行策略</h2>



<p class="has-medium-font-size">按左上角的啟動符號，下方的 warning 訊息為抓取的資料與用量，運算完後會在右側顯示回測結果。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="506" src="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.22.37-1024x506.png" alt="截圖 2023 07 02 下午6.22.37" class="wp-image-5416" srcset="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.22.37-1024x506.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.22.37-300x148.png 300w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.22.37-768x379.png 768w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.22.37-1536x758.png 1536w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.22.37-2048x1011.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="美股探險記第3課:1分鐘上手美股回測｜股價淨值比在美股策略還有效嗎？ 10"></figure>



<h2>分析策略</h2>



<h3>報酬分析</h3>



<p class="has-medium-font-size">近7年該策略的表現領先於 S&amp;P 500 指數(灰線)，表現還不錯。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="859" height="1024" src="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.27.39-859x1024.png" alt="截圖 2023 07 02 下午6.27.39" class="wp-image-5417" srcset="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.27.39-859x1024.png 859w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.27.39-252x300.png 252w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.27.39-768x916.png 768w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.27.39.png 1048w" sizes="(max-width: 859px) 100vw, 859px" title="美股探險記第3課:1分鐘上手美股回測｜股價淨值比在美股策略還有效嗎？ 11"></figure>



<h3>風險分析</h3>



<p class="has-medium-font-size">近7年該策略的下跌幅度小於 S&amp;P 500 指數(灰線)，在2020疫情空頭時，回檔比指數少。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="823" height="1024" src="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.26.21-823x1024.png" alt="截圖 2023 07 02 下午6.26.21" class="wp-image-5418" srcset="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.26.21-823x1024.png 823w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.26.21-241x300.png 241w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.26.21-768x955.png 768w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.26.21.png 1062w" sizes="(max-width: 823px) 100vw, 823px" title="美股探險記第3課:1分鐘上手美股回測｜股價淨值比在美股策略還有效嗎？ 12"></figure>



<h2>台股的股價淨值比策略表現</h2>



<p class="has-medium-font-size">不比不知道，表現比美股好很多啊！同樣的模式，一個在台股很有用，一個在美股則沒有那麼明顯的效果。為什麼會這樣呢？可能是每個市場主流的因子不同，也可能是美股兩話投資玩家很多，一些經典的指標已經變落後指標。<br>可見開發策略要針對不同市場因地制宜，在高效率市場的美股中，策略開發要像台股找到明顯的超額報酬，不是那麼簡單喔！</p>



<h3>報酬分析</h3>



<figure class="wp-block-image size-large"><img loading="lazy" width="893" height="1024" src="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.33.49-893x1024.png" alt="截圖 2023 07 02 下午6.33.49" class="wp-image-5420" srcset="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.33.49-893x1024.png 893w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.33.49-262x300.png 262w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.33.49-768x880.png 768w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.33.49.png 1121w" sizes="(max-width: 893px) 100vw, 893px" title="美股探險記第3課:1分鐘上手美股回測｜股價淨值比在美股策略還有效嗎？ 13"></figure>



<h3>風險分析</h3>



<figure class="wp-block-image size-large is-resized"><img loading="lazy" src="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.34.16-845x1024.png" alt="截圖 2023 07 02 下午6.34.16" class="wp-image-5419" width="840" height="1017" srcset="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.34.16-845x1024.png 845w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.34.16-248x300.png 248w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.34.16-768x931.png 768w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午6.34.16.png 1101w" sizes="(max-width: 840px) 100vw, 840px" title="美股探險記第3課:1分鐘上手美股回測｜股價淨值比在美股策略還有效嗎？ 14"></figure>



<h2>更多免費策略範例</h2>



<p class="has-medium-font-size">如果你對美股開發有興趣，我們之後也會上架更多的範例到<a href="https://ai.finlab.tw/strategies?tab=FinLab%E7%BE%8E%E8%82%A1" target="_blank" rel="noopener">策略實驗室</a>、<a href="https://doc.finlab.tw/tools/%E7%BE%8E%E8%82%A1_%E4%BD%8E%E5%83%B9%E8%82%A1%E4%BD%8E%E6%B3%A2%E5%8B%95%E7%AD%96%E7%95%A5/" target="_blank" rel="noopener">教學文檔</a>、部落格。<br>帶領大家找出美股的關鍵因子。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/us_start_build_pb_strategy_backtest/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5410</post-id>	</item>
		<item>
		<title>美股探險記第2課:美股資料庫使用者指南</title>
		<link>https://www.finlab.tw/us_database_doc/</link>
					<comments>https://www.finlab.tw/us_database_doc/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Thu, 29 Jun 2023 09:35:00 +0000</pubDate>
				<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[美股]]></category>
		<category><![CDATA[資料庫]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=5403</guid>

					<description><![CDATA[做量化投資最重要的起步點就是建構資料庫，有了資料，才能做各式各樣的分析，你可以使用本篇指南搭配 Finlab  [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">做量化投資最重要的起步點就是建構資料庫，有了資料，才能做各式各樣的分析，你可以使用本篇指南搭配 <a href="https://ai.finlab.tw/database#us" target="_blank" rel="noopener">Finlab 美股資料庫索引</a>，在 <a href="https://ai.finlab.tw/strategies?tab=FinLab%E5%8F%B0%E8%82%A1" target="_blank" rel="noopener">FinLab 策略建立頁面</a> 操作資料庫。</p>



<h2>FinLab 美股資料的超值之處</h2>



<p class="has-medium-font-size">美股資料不若台股有證交所、櫃買中心、公開資訊觀測站等官方機構有一致性格式、免費、豐富的資料。你如果想用免費的資源，如 Yahoo 財經，通常會遇到資料時間過短、缺漏的問題，想自己去爬官方的資料？美國的交易所很多家，且各自為政，許多交易所還是民營化公司，每一家資料庫買下來，所花費的金錢、時間會超越你的想像。<br>最好的解決辦法就是和資料商直接一站式購買或使用資料，只是美股資料對一般散戶而言，是不小的支出呀！以知名的美股回測網站 Portfolio 來說，散戶使用者要使用近5年資料回測，要花費 299美金/年。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="521" src="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午4.24.30-1024x521.png" alt="截圖 2023 07 02 下午4.24.30" class="wp-image-5404" srcset="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午4.24.30-1024x521.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午4.24.30-300x153.png 300w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午4.24.30-768x391.png 768w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午4.24.30-1536x781.png 1536w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午4.24.30-2048x1042.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="美股探險記第2課:美股資料庫使用者指南 15"></figure>



<p class="has-medium-font-size">FinLab 為降低用戶分析美股的成本，經<a href="https://data.nasdaq.com/publishers/sharadar" target="_blank" rel="noopener"> Sharadar</a> 資料商授權，可在 FinLab 量化平台上提供回測應用服務，但要注意的是，受限於授權規範，無法讓用戶任意下載資料。<br>目前Finlab 美股 Beta 版的資料庫尚未對用戶收費，你自己算算省下多少。<br>若未來採取收費，價格也會比外國廠商更佳划算、回測的時間區段也會超過5年，目前提供 <strong>2017 </strong>年以後得的資料做回側。</p>



<h2>關鍵資料說明指南</h2>



<p class="has-medium-font-size">接著會針對 FinLab 各式常用於美股策略建構的相關資料說明細節，這區塊的內容會隨著隨著資料多元化而與時俱進，可搭配 <a href="https://ai.finlab.tw/database#us" target="_blank" rel="noopener">Finlab 美股資料庫索引</a> 做對照。<br>大部分的美股資料都會在台灣時間中午12:00左右前更新完前一日資料。</p>



<h3>技術面資料</h3>



<h4>美股成交資訊</h4>



<p class="has-medium-font-size">美股的股價，包含開盤價、最高價、最低價、收盤價和成交量。<br>還原股價基於<strong>股票分割</strong>、<strong>股票股利</strong>、<strong>現金股利</strong>和<strong>分拆</strong>進行調整，採固定目前股價，向之前的歷史數據做還原，因此還原股價的序列可能會隨時間變動。<br>us_price 這份資裡的範圍為美國國內企業的普通股(如蘋果電腦：AAPL) &amp; 特別股(如：波克夏BRK.A)、海外存託憑證 (在美國以外的國家第一上市，又來美國股市募資的公司，如：台積電 TSM)，要注意此份資料並<strong>不包括</strong> ETF、期貨、選擇權、指數的資料。</p>



<h3>基本面資料</h3>



<h4>美股財報</h4>



<p class="has-medium-font-size">us_fundamental 為單季資料，us_fundamental_ART 為「近4季」累計資料，兩個都不會事後校正還原，都是第一次發布的資料，以固定回測運算。</p>



<h5>財報日期</h5>



<p class="has-medium-font-size">要注意的是索引的date為財報發佈日，美股財年不像台股有固定的發佈截止日，且美股公司的會計年度各有不同，主要包括如下兩方面的原因 (<a href="https://zhuanlan.zhihu.com/p/73062933" target="_blank" rel="noopener">資料來源</a>)</p>



<p class="has-medium-font-size">1） 行業特徵相關。美股零售業有近一半的公司財年結束日期處於1-3月，主要是因為12月和1月是零售行業的銷售旺季，使得財務報告週期與行業的收入周期更為一致。零售業巨頭沃爾瑪公司就將2月1日至次年1月31日設為一個會計年度；教育行業的公司往往以學年作為其會計年度，比如新東方教育以6月1日作為財年起始日，因為暑假是中國國內課外輔導需求的爆發期。</p>



<p class="has-medium-font-size">2）公司內部管理需要。研究蘋果公司的年報會發現近年來其會計年度截止日期一直在變動。蘋果公司將它的會計年度截止日期並非設定在具體的某一天，而是設定在每一個公曆年度9月份的最後一個星期六。它們將一個會計年度等分成52週，364天。每隔7年，有一個會計年度是53週，371天。</p>



<p class="has-medium-font-size">這項特色可能讓美股在財報選股方面，不像台股能有一致時間的比較性，造成選股上的困難。</p>



<h5>財報項目的貨幣單位問題</h5>



<p class="has-medium-font-size">若你想抓 TSM 台積電的 每股稅後盈餘(eps) ，你會發現 <code>data.get('us_fundamental:eps')</code> 這項資料怪怪的，數字怎麼那麼大？原因在 TSM是海外存託憑證(ADR) eps 為使用公司註冊地的貨幣(使用當季對美金平均匯率換算)，若要一致性使用美金為單位做比較，則要使用 <code>data.get('us_fundamental:epsusd')</code> 這類結尾帶有usd的指標。</p>



<h5>指標意義與說明哪裡看？</h5>



<p class="has-medium-font-size">在 <a href="https://ai.finlab.tw/database#us" target="_blank" rel="noopener">Finlab 美股資料庫索引</a> 頁面上若指標有出現「？」符號，滑鼠游標滑經過就會顯示指標說明。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="806" src="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午5.16.59-1024x806.png" alt="截圖 2023 07 02 下午5.16.59" class="wp-image-5405" srcset="https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午5.16.59-1024x806.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午5.16.59-300x236.png 300w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午5.16.59-768x605.png 768w, https://www.finlab.tw/wp-content/uploads/2023/07/截圖-2023-07-02-下午5.16.59.png 1335w" sizes="(max-width: 1024px) 100vw, 1024px" title="美股探險記第2課:美股資料庫使用者指南 16"></figure>



<h4>美股常用估值指標</h4>



<p class="has-medium-font-size">資料為每日更新，包含常用的市值、本益比、股價淨值比、股價營收比，方便你用經典的估值指標來選股。</p>



<h4>美股企業基本資訊</h4>



<p class="has-medium-font-size">這份資料提供美股標的的一須重要資訊，例如公司名稱、證券種類、所屬板塊與產業、註冊的交易所，會在限定產業類型的選股策略使用到。</p>



<h2>結論</h2>



<p class="has-medium-font-size">美股資料不若台股有豐富的短期籌碼資料，也沒有月營收提供短中期波段，主要依靠股價與財報，在一些制度面的細節也與台股不同，產業分類更複雜。在資料操作上要注意一下細節～希望這篇文章能讓美股新手們對美股資料有初步認識的輪廓。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/us_database_doc/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5403</post-id>	</item>
		<item>
		<title>美股探險記第1課:為什麼要投資美股？</title>
		<link>https://www.finlab.tw/why_invest_in_us_stocks/</link>
					<comments>https://www.finlab.tw/why_invest_in_us_stocks/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Tue, 27 Jun 2023 03:19:00 +0000</pubDate>
				<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[投資新手]]></category>
		<category><![CDATA[總體經濟]]></category>
		<category><![CDATA[選股策略]]></category>
		<category><![CDATA[美股]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=5390</guid>

					<description><![CDATA[只投資台股不好嗎？為何要投資美股？台股近幾年在全世界的股市表現名列前茅，很多人會疑惑資金集中在台股就有很好的績效了，像是FinLab的台股策略甚至就有年化40%以上的範例，幹嘛還要多費時間研究美股？]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">只投資台股不好嗎？為何要投資美股？台股近幾年在全世界的股市表現名列前茅，很多人會疑惑資金集中在台股就有很好的績效了，像是<a href="https://ai.finlab.tw/strategies?tab=FinLab%E5%8F%B0%E8%82%A1" target="_blank" rel="noopener">FinLab的台股策略</a>甚至就有年化40%以上的範例，幹嘛還要多費時間研究美股？</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="932" src="https://www.finlab.tw/wp-content/uploads/2023/06/截圖-2023-06-30-上午10.15.51-1024x932.png" alt="截圖 2023 06 30 上午10.15.51" class="wp-image-5391" srcset="https://www.finlab.tw/wp-content/uploads/2023/06/截圖-2023-06-30-上午10.15.51-1024x932.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/06/截圖-2023-06-30-上午10.15.51-300x273.png 300w, https://www.finlab.tw/wp-content/uploads/2023/06/截圖-2023-06-30-上午10.15.51-768x699.png 768w, https://www.finlab.tw/wp-content/uploads/2023/06/截圖-2023-06-30-上午10.15.51-1536x1397.png 1536w, https://www.finlab.tw/wp-content/uploads/2023/06/截圖-2023-06-30-上午10.15.51.png 1818w" sizes="(max-width: 1024px) 100vw, 1024px" title="美股探險記第1課:為什麼要投資美股？ 17"></figure>



<h2>地緣政治風險</h2>



<p class="has-medium-font-size">有一些風險是沒辦法使用回測衡量，因為歷史從未發生過，或是很少出現，且很難預測出現的時間點。<br>投資最怕的就是一夕之間歸零，什麼樣的風險會造成一個國家的股市迅速崩盤？不外乎是戰爭、天災、金融風暴，從俄羅斯股市的例子來看，他可說是動盪國家的代表，戰爭、天災、金融風暴、能源危機他都有參與到，每當有地緣政治的大事件發生，股價、匯率都會在短期內出現40%以上的崩盤。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="576" src="https://www.finlab.tw/wp-content/uploads/2023/06/mm-chart-2023-06-30_俄羅斯-股市RTS-960x540-1-1024x576.png" alt="mm chart 2023 06 30 俄羅斯 股市RTS 960x540 1" class="wp-image-5392" srcset="https://www.finlab.tw/wp-content/uploads/2023/06/mm-chart-2023-06-30_俄羅斯-股市RTS-960x540-1-1024x576.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/06/mm-chart-2023-06-30_俄羅斯-股市RTS-960x540-1-300x169.png 300w, https://www.finlab.tw/wp-content/uploads/2023/06/mm-chart-2023-06-30_俄羅斯-股市RTS-960x540-1-768x432.png 768w, https://www.finlab.tw/wp-content/uploads/2023/06/mm-chart-2023-06-30_俄羅斯-股市RTS-960x540-1-1536x864.png 1536w, https://www.finlab.tw/wp-content/uploads/2023/06/mm-chart-2023-06-30_俄羅斯-股市RTS-960x540-1-800x450.png 800w, https://www.finlab.tw/wp-content/uploads/2023/06/mm-chart-2023-06-30_俄羅斯-股市RTS-960x540-1.png 1920w" sizes="(max-width: 1024px) 100vw, 1024px" title="美股探險記第1課:為什麼要投資美股？ 18"><figcaption>資料來源：財經M平方</figcaption></figure>



<p class="has-medium-font-size">台股最大的風險就是地緣政治風險，雖然兩岸從未真的開戰過，最接近的一次是1997年台海危機，但長期以來都面臨中共的各種威脅是不變的事實，中共從未放棄用武力統一台灣。<br>尤其是近年美中科技貿易戰、共機共艦繞台，都讓台灣很難不被牽入大國之間的博弈。<br>經濟學人雜誌甚至還在2021年將台灣列為全世界最危險的地方。<br>若資金都重壓在一個國家，那你就要問問自己如果最糟糕的情況發生了？我可以承受嗎？<br>還是選擇預防勝於治療，提早將資金做分散的準備？將資金部署到安全性較高的國家來降低地緣風險，美國目前身為科技與軍事強國、且有完善的資本市場，美股可列為考慮用來當風散投資風險的國家。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="779" height="1024" src="https://www.finlab.tw/wp-content/uploads/2023/06/台灣危險-779x1024.webp" alt="台灣危險" class="wp-image-5393" srcset="https://www.finlab.tw/wp-content/uploads/2023/06/台灣危險-779x1024.webp 779w, https://www.finlab.tw/wp-content/uploads/2023/06/台灣危險-228x300.webp 228w, https://www.finlab.tw/wp-content/uploads/2023/06/台灣危險-768x1010.webp 768w, https://www.finlab.tw/wp-content/uploads/2023/06/台灣危險-1169x1536.webp 1169w, https://www.finlab.tw/wp-content/uploads/2023/06/台灣危險.webp 1558w" sizes="(max-width: 779px) 100vw, 779px" title="美股探險記第1課:為什麼要投資美股？ 19"><figcaption>資料來源：經濟學人</figcaption></figure>



<p class="has-medium-font-size"><br>股神巴菲特在2023年短進短出台積電讓投資人驚訝巴爺爺為何操作這麼短？結果股神也承認是因為地緣因素才割捨「護國神山」這樣的優良公司。</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="985" src="https://www.finlab.tw/wp-content/uploads/2023/06/截圖-2023-06-30-上午10.38.14-1024x985.png" alt="截圖 2023 06 30 上午10.38.14" class="wp-image-5394" srcset="https://www.finlab.tw/wp-content/uploads/2023/06/截圖-2023-06-30-上午10.38.14-1024x985.png 1024w, https://www.finlab.tw/wp-content/uploads/2023/06/截圖-2023-06-30-上午10.38.14-300x289.png 300w, https://www.finlab.tw/wp-content/uploads/2023/06/截圖-2023-06-30-上午10.38.14-768x739.png 768w, https://www.finlab.tw/wp-content/uploads/2023/06/截圖-2023-06-30-上午10.38.14-1536x1477.png 1536w, https://www.finlab.tw/wp-content/uploads/2023/06/截圖-2023-06-30-上午10.38.14.png 1593w" sizes="(max-width: 1024px) 100vw, 1024px" title="美股探險記第1課:為什麼要投資美股？ 20"><figcaption>資料來源：自由財經</figcaption></figure>



<p class="has-medium-font-size"><br>只投資台股並不一定不好，但連股神都考慮地緣風險，你能不跟進考慮嗎，了解台股和美股的特點和優缺點可以幫助您做出更明智的投資決策。以下是台股和美股的一些資本市場優缺點：</p>



<h2>台股的優點</h2>



<ul class="has-medium-font-size"><li>地域接近：對於台灣投資者而言，台股更為熟悉和容易接觸，包括了許多本地公司。</li><li>語言和文化優勢：對於以中文為母語的投資者來說，投資台股可以減少語言和文化障礙，更容易理解和獲取信息。</li><li>熟悉行業和市場：投資台股可以更容易了解本地市場和行業的動態，掌握相關信息。</li><li>潛在Alpha空間：外資的台股市場參與度約 30%，還不算競爭太過激烈的市場，一般來說，散戶參與度較高的市場，比較能利用投資人的交易行為錯誤取得超額報酬空間。</li><li>資金調度：台幣可用來當日常支出，降低會換匯風險。</li></ul>



<h2>台股的缺點</h2>



<ul class="has-medium-font-size"><li>有限的市場規模：相對於全球範圍內的資本市場，台股的市場規模較小，投資機會可能較為有限。</li><li>零股市場、個股期貨流通性仍較低，對小資金參與者不友善。</li><li>缺乏行業多樣性：台股市場的行業結構相對集中，以科技和製造業為主導，其他行業的選擇相對較少。</li></ul>



<figure class="wp-block-image is-resized"><img loading="lazy" src="https://pineapple-centaur-13d.notion.site/image/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2F7215288f-c611-4162-8b08-4def11a666a9%2Fnewplot_(12).png?id=3c3e1f3c-9626-4a5c-8cba-dec340bc7a7c&amp;table=block&amp;spaceId=9ed484a1-504e-442b-b113-ec69267e5d7a&amp;width=2000&amp;userId=&amp;cache=v2" alt="https%3A%2F%2Fs3 us west 2.amazonaws.com%2Fsecure.notion static.com%2F7215288f c611 4162 8b08 4def11a666a9%2Fnewplot (12)" width="840" height="441" title="美股探險記第1課:為什麼要投資美股？ 21"></figure>



<figure class="wp-block-image"><img src="https://pineapple-centaur-13d.notion.site/image/https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2F810934f1-4a90-4482-a8a9-f07caae6df0d%2Fnewplot_(13).png?id=239c5064-35ae-461a-a445-68e1b9e089d3&amp;table=block&amp;spaceId=9ed484a1-504e-442b-b113-ec69267e5d7a&amp;width=2000&amp;userId=&amp;cache=v2" alt="https%3A%2F%2Fs3 us west 2.amazonaws.com%2Fsecure.notion static.com%2F810934f1 4a90 4482 a8a9 f07caae6df0d%2Fnewplot (13)" title="美股探險記第1課:為什麼要投資美股？ 22"></figure>



<h2>美股的優點</h2>



<ul class="has-medium-font-size"><li>市場規模和機會：美國股市是全球最大的股票市場之一，擁有廣泛的投資機會和多樣的行業選擇。像是軟體業、服務業、軍火業、煙草業&#8230;，都是台股缺乏的產業板塊。</li><li>科技和創新領先：美國是全球科技創新的領導者，許多知名科技公司在美股上市，投資者可以參與到科技發展和創新的機會中。想是看好iphone產品，直接投資Apple就好，不用投資一堆Apple的台企供應鏈。</li><li>資本流動性高：美股市場具有高度的資金流動性，交易活躍，便於買賣股票。以「股」為最小單位來當主要交易，不像台股以「千股」為主要交易，小資族較能參與市場。</li><li>金融商品多樣化：有較豐富且低交易成本的 ETF 可操作，著名的 VT 就是在美國發行。</li></ul>



<h2>美股的缺點</h2>



<ul class="has-medium-font-size"><li>時差和語言障礙：對於台灣投資者而言，投資美股可能面臨時差和語言障礙，需要更多的跨國交流和信息獲取。</li><li>風險多樣化：美股市場的行業和公司眾多，需要更廣泛的研究和了解，以避免風險集中在某些特定股票或行業。</li><li>稅制：相較台灣，有較高的股息所得稅，遺產辦理手續繁雜。</li><li>美股投資不容易取得超額回報： 高市場效率，美國股市是全球最發達和最活躍的股票市場之一，市場參與者眾多，尤其是法人與量化基金成交佔比高，信息傳遞迅速，交易活躍度高。這使得市場相對高度有效，難以通過普通的選股和市場定時來獲得持續的超額回報，面對強大的量化基金交易對手，可能更難超越大盤。</li></ul>



<h2>結論</h2>



<p class="has-medium-font-size">對美國本土交易人而言，美股的缺點幾乎只剩下「美股投資不容易取得超額回報」這一項。<br>對台灣交易人而言，美股雖然要研發出策略超額報酬的策略比較難，但就算是報酬率較台股普通，仍對分散淺在地緣風險、產業風險有所幫助，投資組合的未來表現會比較穩定，不用擔心台灣「萬一」發生了什麼？<br>美股相對於台股，就像棒球的美國大聯盟與小聯盟，小聯盟玩到頂尖後，挑戰一下大聯盟，放眼世界，也是必經的道路，FinLab 美股 Beta 版已經上線，就讓 FinLab 帶你一起探險美股的世界吧～</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/why_invest_in_us_stocks/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">5390</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總體經濟指標輕鬆抓|美國汽車指標|美股回測外掛教學 23"></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總體經濟指標輕鬆抓|美國汽車指標|美股回測外掛教學 24"></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總體經濟指標輕鬆抓|美國汽車指標|美股回測外掛教學 25"></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總體經濟指標輕鬆抓|美國汽車指標|美股回測外掛教學 26"><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總體經濟指標輕鬆抓|美國汽車指標|美股回測外掛教學 27"></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>VIX美股大跌投資法：Python實作教學看這裡！</title>
		<link>https://www.finlab.tw/python%ef%bc%9avix%e7%be%8e%e8%82%a1%e5%a4%a7%e8%b7%8c%e6%8a%95%e8%b3%87%e6%b3%95/</link>
					<comments>https://www.finlab.tw/python%ef%bc%9avix%e7%be%8e%e8%82%a1%e5%a4%a7%e8%b7%8c%e6%8a%95%e8%b3%87%e6%b3%95/#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[程式交易]]></category>
		<category><![CDATA[美股]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=820</guid>

					<description><![CDATA[今天要介紹VIX，以及查看VIX如何幫助我們做美股長期投資。首先，究竟是什麼是VIX呢？VIX是一個預估12個月的波動程度，假如市場上的不確定因素越高，代表將來的股價會有非常高的不確定性，則VIX越高，假如市場普遍穩定，則VIX就會比較低。]]></description>
										<content:encoded><![CDATA[
<p>美股最近跌的慘慘慘，又到了聖誕假期，剛好又休市。我們當然趁現在來研究美股大跌時，要如何來投資，才是最佳的選擇呀！今天要介紹VIX，以及查看VIX如何幫助我們做美股長期投資。<a href="https://www.finlab.tw/Python%EF%BC%9AVIX%E7%BE%8E%E8%82%A1%E5%A4%A7%E8%B7%8C%E6%8A%95%E8%B3%87%E6%B3%95/thumbnail.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="881" height="454" src="http://34.96.136.135/wp-content/uploads/2020/07/thumbnail-3-2.png" alt="thumbnail 3 2" class="wp-image-821" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-3-2.png 881w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-3-2-300x155.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-3-2-768x396.png 768w" sizes="(max-width: 881px) 100vw, 881px" title="VIX美股大跌投資法：Python實作教學看這裡！ 28"></figure></div>



<p><a href="https://colab.research.google.com/drive/1PqjDggUwnKHWf1cgNAQbZCNvbR4puzSy" rel="noreferrer noopener" target="_blank">線上程式碼直接跑免安裝</a></p>



<h3 id="什麼是VIX">什麼是VIX</h3>



<p>首先，究竟是什麼是VIX呢？VIX是一個預估12個月的波動程度，假如市場上的不確定因素越高，代表將來的股價會有非常高的不確定性，則VIX越高，假如市場普遍穩定，則VIX就會比較低。通常VIX大概會在15附近，當大家極度恐慌時（例如恐怖攻擊、金融海嘯等），VIX會急速跳動到30～50，然後再緩和下來。</p>



<p>更<a href="https://www.cboe.com/micro/vix/vixwhite.pdf" rel="noreferrer noopener" target="_blank">嚴謹的數學公式</a>以連結的方式讓大家參考</p>



<p>於是有人就說可以參考VIX非常高的時候，當作是買點進行買入。<br>今天我們就用python來試試看是否有用？</p>



<h3 id="獲取歷史資料">獲取歷史資料</h3>



<p>取得歷史資料的方式非常簡單，可以到「芝加哥期交所」官網來下載 <a href="http://www.cboe.com/products/stock-index-options-spx-rut-msci-ftse/s-p-500-index-options/s-p-500-index/spx-historical-data" rel="noreferrer noopener" target="_blank">S&amp;P500歷史資料</a>，還有<a href="http://www.cboe.com/products/vix-index-volatility/vix-options-and-futures/vix-index/vix-historical-data" rel="noreferrer noopener" target="_blank">VIX歷史資料</a>，將下載下來的csv檔放在資料夾中，就可以開始今天的實驗了！</p>



<h3 id="目錄">目錄</h3>



<p>今天的教學主要分成以下幾個步驟</p>



<ol><li>利用pandas匯入csv檔資料</li><li>計算S&amp;P500的年報酬率，並繪圖</li><li>回測並檢討</li><li>稍微修改買入條件，並比較效果如何</li></ol>



<p>假如第一次接觸python的朋友，可以參考<a href="https://www.finlab.tw/Python%E8%82%A1%E7%A5%A8%E6%8A%95%E8%B3%87/">python安裝教學</a>，安裝好之後就可以一起來玩囉！</p>



<p>接下來我們就來玩玩這些資料吧</p>



<h3 id="1-利用pandas匯入歷史資料">1. 利用pandas匯入歷史資料</h3>



<p>首先，我們可以使用<code>pd.read_csv()</code>這個函示來匯入歷史資料如下：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">%matplotlib inline
import pandas as pd

vix = pd.read_csv("vixcurrent.csv", header=1, index_col='Date', parse_dates=['Date'])
vixc = vix['VIX Close']</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="379" src="http://34.96.136.135/wp-content/uploads/2020/07/vix-1024x379.png" alt="vix" class="wp-image-822" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/vix-1024x379.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/vix-300x111.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/vix-768x284.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/vix-1536x569.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/vix-2048x758.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="VIX美股大跌投資法：Python實作教學看這裡！ 29"></figure></div>



<p><a href="https://www.finlab.tw/Python%EF%BC%9AVIX%E7%BE%8E%E8%82%A1%E5%A4%A7%E8%B7%8C%E6%8A%95%E8%B3%87%E6%B3%95/vix.png"></a></p>



<p>其中，<code>header=1</code>是指從第一行是column 的名稱。<code>index_col</code>是將指定的column轉換成index，最後，<code>parse_dates</code>是將指定的column轉換成datetime的格式。</p>



<p>再來，也是用類似的方法將SPX的指數給拿出來：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">b = pd.read_excel("dailypricehistory.xls", header=4)['SPXSM']
b.index = pd.to_datetime(b.index, errors="coerce")
b = b.reindex(vixc.index)
b = b.dropna()
b.plot()</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="412" src="http://34.96.136.135/wp-content/uploads/2020/07/sp500-1024x412.png" alt="sp500" class="wp-image-823" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/sp500-1024x412.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/sp500-300x121.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/sp500-768x309.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/sp500-1536x618.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/sp500-2048x824.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="VIX美股大跌投資法：Python實作教學看這裡！ 30"></figure></div>



<p><a href="https://www.finlab.tw/Python%EF%BC%9AVIX%E7%BE%8E%E8%82%A1%E5%A4%A7%E8%B7%8C%E6%8A%95%E8%B3%87%E6%B3%95/sp500.png"></a></p>



<p>不過我們使用了一些額外的code，來稍微處理一下大盤指數，其中<code>b.dropna()</code>是將冗餘的資料去掉，另外，使用<code>b.reindex()</code>是因為，我們希望vixc跟b的長度是一樣的，每一天的index是對齊的。</p>



<h3 id="大盤歷史績效分析">大盤歷史績效分析</h3>



<p>接下來我們希望可以分析美股SP500的年報酬指數，我們可以這樣寫：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">(b.dropna()[-1]/b[0]) ** (250/len(b))</code></pre>



<p>其實公式就是：</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="228" height="74" src="http://34.96.136.135/wp-content/uploads/2020/07/Screenshot-2020-07-15-at-14.48.06.png" alt="Screenshot 2020 07 15 at 14.48.06" class="wp-image-824" title="VIX美股大跌投資法：Python實作教學看這裡！ 31"></figure>



<p>但由於我們要算年報酬，還要進一步修改，ndays 就是所有的歷史報酬天數，其中的250是一年的交易日估算。</p>



<p>從下圖可以看出，大盤的平均年報酬率大概是6％左右。<a href="https://www.finlab.tw/Python%EF%BC%9AVIX%E7%BE%8E%E8%82%A1%E5%A4%A7%E8%B7%8C%E6%8A%95%E8%B3%87%E6%B3%95/ann_ret.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="61" src="http://34.96.136.135/wp-content/uploads/2020/07/ann_ret-1024x61.png" alt="ann ret" class="wp-image-825" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/ann_ret-1024x61.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/ann_ret-300x18.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/ann_ret-768x45.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/ann_ret-1536x91.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/ann_ret-2048x121.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="VIX美股大跌投資法：Python實作教學看這裡！ 32"></figure></div>



<h3 id="VIX大於40，買入一年大盤能賺錢嗎？">VIX大於40，買入一年大盤能賺錢嗎？</h3>



<p>接下來，我們來看當VIX大於40的當天，買入大盤並持有250天，會發生什麼事情呢：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers"># vix 大於 th 時，進行買入
th = 40
# 持有 days 天
days = 250

# 當天是否買入
buy = (vixc > th)

# 確保最近三十天並沒有buy發生，才是需要買入的訊號
buy &amp;= (buy.shift().rolling(30).mean() == 0)

</code></pre>



<p>最後一行值得一提，因為其實VIX大於40後，有時候會常常飆高，但其實我們是希望VIX突然飆高的第一天，而不是變低後39，然後又飆高到40以上，這種訊號不是我們需要的，所以利用上方的最後一行代碼進行過濾。</p>



<h3 id="繪圖">繪圖</h3>



<p>將買點給畫出來：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">b.plot()
buy.astype(float).plot(secondary_y=True)
</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="334" src="http://34.96.136.135/wp-content/uploads/2020/07/buy1-1024x334.png" alt="buy1" class="wp-image-826" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/buy1-1024x334.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/buy1-300x98.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/buy1-768x251.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/buy1-1536x501.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/buy1-2048x668.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="VIX美股大跌投資法：Python實作教學看這裡！ 33"></figure></div>



<p><a href="https://www.finlab.tw/Python%EF%BC%9AVIX%E7%BE%8E%E8%82%A1%E5%A4%A7%E8%B7%8C%E6%8A%95%E8%B3%87%E6%B3%95/buy1.png"></a></p>



<h3 id="報酬率計算">報酬率計算</h3>



<p>接下來我們就來計算，當我們使用這個邏輯進行買賣時，效果如何：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers"># 當天收盤價
price_begin = b[buy]

# 隔250天後 的收盤價
price_end = b.shift(-days)[buy]

# 報酬率計算
ret = (price_end/price_begin)</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="199" src="http://34.96.136.135/wp-content/uploads/2020/07/return1-1024x199.png" alt="return1" class="wp-image-827" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/return1-1024x199.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/return1-300x58.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/return1-768x149.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/return1-1536x298.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/return1-2048x398.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="VIX美股大跌投資法：Python實作教學看這裡！ 34"></figure></div>



<p><a href="https://www.finlab.tw/Python%EF%BC%9AVIX%E7%BE%8E%E8%82%A1%E5%A4%A7%E8%B7%8C%E6%8A%95%E8%B3%87%E6%B3%95/return1.png"></a></p>



<p>我們可以發現報酬率滿不錯的，唯一一次沒有賺錢，是在2008年金融海嘯那次，我們可以將報酬率畫出來，方便大家理解</p>



<h3 id="持有250天的報酬率">持有250天的報酬率</h3>



<p>接下來我們可以將這四次持有250天的大盤報酬曲線畫出來，橫軸為時間，會得到很有趣的結果：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import matplotlib.pyplot as plt

def normalize(s):
    return s / s[0]

for d in ret.index.dropna():
    plt.plot(normalize(b.loc[d:].head(250).values))</code></pre>



<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/eq1-2-1-1024x396.png" alt="eq1 2 1" class="wp-image-828" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/eq1-2-1-1024x396.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/eq1-2-1-300x116.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/eq1-2-1-768x297.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/eq1-2-1-1536x593.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/eq1-2-1-2048x791.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="VIX美股大跌投資法：Python實作教學看這裡！ 35"></figure></div>



<p><a href="https://www.finlab.tw/Python%EF%BC%9AVIX%E7%BE%8E%E8%82%A1%E5%A4%A7%E8%B7%8C%E6%8A%95%E8%B3%87%E6%B3%95/eq1.png"></a></p>



<p>這張圖中藍色的為金融海嘯，所以當買入時，還跌了一段，還是賠了40％的資產，非常的恐怖…。可見這種方法還是不能亂用。</p>



<p>另外更有趣的是，紅色跟藍色的大盤趨勢非常像，而綠色跟橘色也很類似，感覺大盤的變化隨時間是有規律的。</p>



<h3 id="優化策略">優化策略</h3>



<p>接下來，我想要進行一個小修改，因為VIX是市場恐慌的程度，VIX高代表市場可能過於悲觀，但是不代表悲觀已經結束了，所以2008年的VIX才會噴到將近50左右的位置，所以我們不應該在VIX噴發時投資，應該要等它降溫時，投資會比較好，所以新的策略邏輯如下：</p>



<ol><li>VIX 近120天超過40</li><li>VIX 當天降到了30</li></ol>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">th = 40
days = 250

buy = (
    ((vixc > th).rolling(120).sum() > 0) &amp;
    (vixc &lt; 30)
)

buy &amp;= (buy.shift().rolling(30).mean() == 0)

price_begin = b[buy]
price_end = b.shift(-days)[buy]
ret = (price_end/price_begin)#.groupby(price_begin.index.year).first()
ret</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="371" src="http://34.96.136.135/wp-content/uploads/2020/07/method2-1-1024x371.png" alt="method2 1" class="wp-image-830" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/method2-1-1024x371.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/method2-1-300x109.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/method2-1-768x278.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/method2-1-1536x556.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/method2-1-2048x741.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="VIX美股大跌投資法：Python實作教學看這裡！ 36"></figure></div>



<p><a href="https://www.finlab.tw/Python%EF%BC%9AVIX%E7%BE%8E%E8%82%A1%E5%A4%A7%E8%B7%8C%E6%8A%95%E8%B3%87%E6%B3%95/method2.png"></a></p>



<p>我們發現，這四次的買點都是有獲利的，且大於平均年報酬率(6％)，說明了這可能是比較好的投資方法。然而取樣的點非常少，才4次，所以也有可能只是運氣好而已，過去不等於未來，投資風險就請大家自行斟酌囉！</p>



<p>相信大家可以用類似的方式，找到更好的投資方式喔！快來試試看吧～</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="403" src="http://34.96.136.135/wp-content/uploads/2020/07/eq2-1-2-1024x403.png" alt="eq2 1 2" class="wp-image-831" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/eq2-1-2-1024x403.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/eq2-1-2-300x118.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/eq2-1-2-768x302.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/eq2-1-2-1536x604.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/eq2-1-2-2048x806.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="VIX美股大跌投資法：Python實作教學看這裡！ 37"></figure></div>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/python%ef%bc%9avix%e7%be%8e%e8%82%a1%e5%a4%a7%e8%b7%8c%e6%8a%95%e8%b3%87%e6%b3%95/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">820</post-id>	</item>
	</channel>
</rss>
