<?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/%E6%9C%88%E7%87%9F%E6%94%B6/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.finlab.tw</link>
	<description>深入淺出的量化投資，讓你在在茫茫股海中，找到專屬於自己的投資方法</description>
	<lastBuildDate>Thu, 17 Nov 2022 06:25:48 +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>月營收選股｜股價創新高｜新手必學的雙動能策略</title>
		<link>https://www.finlab.tw/revenue_and_price_engine_strategy/</link>
					<comments>https://www.finlab.tw/revenue_and_price_engine_strategy/#respond</comments>
		
		<dc:creator><![CDATA[Ben]]></dc:creator>
		<pubDate>Wed, 16 Nov 2022 06:55:47 +0000</pubDate>
				<category><![CDATA[Python新手教學]]></category>
		<category><![CDATA[FinLab 量化平台]]></category>
		<category><![CDATA[VIP文章]]></category>
		<category><![CDATA[基本面分析]]></category>
		<category><![CDATA[技術面]]></category>
		<category><![CDATA[投資新手]]></category>
		<category><![CDATA[財經PYTHON教學]]></category>
		<category><![CDATA[VIP限定]]></category>
		<category><![CDATA[創新高]]></category>
		<category><![CDATA[動能]]></category>
		<category><![CDATA[月營收]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=4884</guid>

					<description><![CDATA[月營收是台股獨特的基本面因子，操作台股的玩家，都知道月營收的影響性，常可先預判季財報，究竟月營收選股條件要怎麼寫？這篇就用超簡單的語法，結合「突破策略豆知識」技巧寫出15年來年化報酬37%的高報酬率策略，讓你迅速上手月營收突破這個台股經典的策略。]]></description>
										<content:encoded><![CDATA[
<p class="has-medium-font-size">月營收是台股獨特的基本面因子，操作台股的玩家，都知道月營收的影響性，常可先預判季財報，究竟月營收選股條件要怎麼寫？這篇就用超簡單的語法，結合「<a href="https://www.finlab.tw/breakthrough_stock_picking_strategies/">突破策略豆知識</a>」技巧寫出15年來年化報酬37%的高報酬率策略，讓你迅速上手月營收突破這個台股經典的策略。</p>



<figure class="wp-block-image size-large"><img width="1024" height="654" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128-1024x654.png" alt="截圖 2022 11 16 下午12.47.28 e1668593619128" class="wp-image-4885" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128-1024x654.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128-300x192.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128-768x491.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128.png 1396w" sizes="(max-width: 1024px) 100vw, 1024px" title="月營收選股｜股價創新高｜新手必學的雙動能策略 1"></figure>



<h2>月營收選股策略 &#8211; 創高基礎型態</h2>



<h3>程式範例</h3>



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

rev = data.get('monthly_revenue:當月營收')
rev_yoy_growth = data.get('monthly_revenue:去年同月增減(%)')

# 近2月平均營收
rev_ma = rev.average(2)

# 近2月平均營收創12個月來新高
condition = rev_ma == rev_ma.rolling(12, min_periods=6).max()

# 單月營收年增率與訊號相乘，若訊號為False，相乘結果為0
position= rev_yoy_growth*condition

# 符合選股條件的名單中，再選出單月營收年增率前10強，並在營收公告截止日換股。
position=position[position&gt;0].is_largest(10)

report=sim(position ,name="營收動能",upload=False)
report.display()</code></pre>



<p class="has-medium-font-size">程式非常簡單，只有10來行。說明幾個關鍵處。<br>月營收有個關鍵在要注意過年效應，有時候年假在1月、有時在2月中旬前，由於台股多數企業的營運區域都在華人地區，年假通常會停工或減班，如果是在1月過年，訂單常遞延到2月。因此在比較營收時，為了平滑過年效應，我會習慣取近2月平均營收來取代單月營收，不然1、2月若碰到年假，單月營收要創近12月新高的可能性實在太低。</p>



<p class="has-medium-font-size"><br>如果策略要實戰，縮減檔數是必須的，因為多數人沒那麼多資金全買，所以範例簡單用單月月營收來選最後10強。你可能會疑惑為何要寫<code>position[position&gt;0].is_largest(10)</code>，而不是<code>position.is_largest(10)</code>就好？那是因為<code>is_largest(10)</code>會選數值前10高的，若沒有排除不符合營收創高的標的，前10高的數值可能會選到不合條件的，會從股號小的標的開始補到10檔為止。</p>



<p class="has-medium-font-size">此策略的換股週期是用月營收索引，也就是月營收公告截止日，好處是貼近營收因子發酵期。<br>來看看策略的表現，非常不錯，15年來，年化高達 26% ! <br>你以為這樣就結束了嗎？其實還可以優化，繼續看下去。</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="800" height="600" src="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-36.png" alt="newplot 36" class="wp-image-4886" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-36.png 800w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-36-300x225.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-36-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" title="月營收選股｜股價創新高｜新手必學的雙動能策略 2"></figure>



<h2>營收股價雙創高的渦輪效應</h2>



<h3>股價創新高動能</h3>



<p class="has-medium-font-size">營收利多，最怕利多不漲，那很可能是市場早就反應，因此我們的目標是股價與營收連動，一同創高，代表股價的動能和營收創新高的關聯較大，如何寫出好棒棒的股價創新高動能策略，可以看先前的文章「<a href="https://www.finlab.tw/breakthrough_stock_picking_strategies/">突破策略豆知識</a>」，運用FinlabDataframe好用的sustiain方法確認突破強度。<br>程式與回測結果如下：</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from finlab.backtest import sim
from finlab import data
with data.universe(market='TSE_OTC'):
    close = data.get("price:收盤價")
    # 近5日內有3日以上的股價創前200日新高
    position = (close == close.rolling(200).max()).sustain(5,2)
    report = sim(position, resample="M", name="創新高延續動能策略", upload=False)
    report.display()</code></pre>



<figure class="wp-block-image size-full"><img loading="lazy" width="800" height="600" src="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-38.png" alt="newplot 38" class="wp-image-4887" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-38.png 800w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-38-300x225.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-38-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" title="月營收選股｜股價創新高｜新手必學的雙動能策略 3"></figure>



<h3>雙渦輪</h3>



<p class="has-medium-font-size">如果把營收創新高和股價創新高的程式做結合，會發生什麼事？</p>



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

close = data.get('price:收盤價')
vol = data.get('price:成交股數')
rev = data.get('monthly_revenue:當月營收')
rev_yoy_growth = data.get('monthly_revenue:去年同月增減(%)')

# 近2月平均營收
rev_ma = rev.average(2)

# 近2月平均營收創12個月來新高
condition1 = rev_ma == rev_ma.rolling(12, min_periods=6).max()
# 近5日內有2日股價創新高
condition2 = (close == close.rolling(200).max()).sustain(5,2)
# 近五日成交均量大於500張
condition3 = vol.average(5) &gt; 500*1000
conditions = condition1 &amp; condition2 &amp; condition3

# 符合選股條件的名單中，再選出單月營收年增率前10強，並在營收公告截止日換股。
position= rev_yoy_growth*conditions

position=position[position&gt;0].is_largest(10).reindex(rev.index_str_to_date().index, method='ffill')

# 設定position_limit避免重壓
report = sim(position=position,stop_loss=0.2,take_profit=0.8, position_limit=0.25, fee_ratio=1.425/1000*0.3,name="營收股價雙渦輪",upload=False)
report.display()</code></pre>



<p class="has-medium-font-size">上面程式要注意的小地方是有加上流動性條件，只買近五日成交均量大於500張的標的，避免太冷門的標的很難入手。由於月營收創高和股價創高的條件交集後，會轉成日週期索引，若要使用月營收截止日換股，必須要做reindex的動作，<code>rev.index_str_to_date</code> 會將月營收文字格式日期轉成月營收公告截止日，例如 2022-M10 變成 2022-11-11。<br><br>最後為避免重壓標地，設定position_limit=0.25，代表單擋持股上限為25%，避免只選到1-2檔全壓的大波動狀況。如果偏好降低波動，也可調成0.1，如此一來若只選到4檔標的，總持股比例只會有40%，在熊市時由於創新高標的本來就少，因此持股比例自然降低，具自然避險躲空頭的效果。<br><br>停損不建議設定小，此策略波動較大，設太小容易被洗掉。最後來看看加乘的效果吧！<br>15年來年化報酬37%！夏普率1.3，幾乎每一年都獲利，比前述單因子選股的表現優異許多，熊市年 2022 竟然還有16%正報酬，以條件這麼簡單的策略來說，算是很神的成績！</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="800" height="600" src="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-39.png" alt="newplot 39" class="wp-image-4888" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/newplot-39.png 800w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-39-300x225.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/newplot-39-768x576.png 768w" sizes="(max-width: 800px) 100vw, 800px" title="月營收選股｜股價創新高｜新手必學的雙動能策略 4"></figure>



<figure class="wp-block-image size-large"><img width="1024" height="654" src="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128-1024x654.png" alt="截圖 2022 11 16 下午12.47.28 e1668593619128" class="wp-image-4885" srcset="https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128-1024x654.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128-300x192.png 300w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128-768x491.png 768w, https://www.finlab.tw/wp-content/uploads/2022/11/截圖-2022-11-16-下午12.47.28-e1668593619128.png 1396w" sizes="(max-width: 1024px) 100vw, 1024px" title="月營收選股｜股價創新高｜新手必學的雙動能策略 1"></figure>



<h2>結論</h2>



<p class="has-medium-font-size"><a href="https://colab.research.google.com/drive/1qp-5ZPtJXFIc6x4EkCJezzMcwpFdc5jY?usp=sharing" target="_blank" rel="noopener">colab 範例</a><br><a href="https://ai.finlab.tw/strategyview/?uid=TJN4FDuqrwU8DML7DAjUYFIMutp2&amp;sid=%E7%87%9F%E6%94%B6%E8%82%A1%E5%83%B9%E9%9B%99%E6%B8%A6%E8%BC%AA" target="_blank" rel="noopener">量化平台部署範例</a><br>簡單卻很有實戰性，這就是FinLab與其他地方不同之處，不走太學術的路線，考慮實戰面，除了完整公開程式碼，還跟你講策略背後的思維。<br>此策略當然還有優化的空間～但這就是大家各自的功課了，Ben 把最核心的條件交給你了，一起去找股海的大秘寶吧！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/revenue_and_price_engine_strategy/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">4884</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-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="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)：簡單程式碼，爬全球的股票! 6"></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)：簡單程式碼，爬全球的股票! 7"><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>三種看月營收的進階方法！</title>
		<link>https://www.finlab.tw/%e4%b8%89%e7%a8%ae%e6%9c%88%e7%87%9f%e6%94%b6%e9%80%b2%e9%9a%8e%e7%9c%8b%e6%b3%95/</link>
					<comments>https://www.finlab.tw/%e4%b8%89%e7%a8%ae%e6%9c%88%e7%87%9f%e6%94%b6%e9%80%b2%e9%9a%8e%e7%9c%8b%e6%b3%95/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:21 +0000</pubDate>
				<category><![CDATA[基本面分析]]></category>
		<category><![CDATA[如何買股票]]></category>
		<category><![CDATA[月營收]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=623</guid>

					<description><![CDATA[說到台股基本面，就不得不提更新最快的月營收，每個月更新一次，讓投資人措手不及，今天就來教你怎麼看月營收！並比較這三種方法的獲利～]]></description>
										<content:encoded><![CDATA[
<p>說到台股基本面，就不得不提更新最快的<strong>月營收</strong>，每個月更新一次，讓投資人措手不及，今天就來教你怎麼看月營收！並比較這三種方法的獲利～<a href="https://www.finlab.tw/%E4%B8%89%E7%A8%AE%E6%9C%88%E7%87%9F%E6%94%B6%E9%80%B2%E9%9A%8E%E7%9C%8B%E6%B3%95/thumbnail.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="590" height="338" src="http://34.96.136.135/wp-content/uploads/2020/07/thumbnail-4.png" alt="thumbnail 4" class="wp-image-624" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-4.png 590w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-4-300x172.png 300w" sizes="(max-width: 590px) 100vw, 590px" title="三種看月營收的進階方法！ 8"></figure></div>



<h3 id="1-均線法">1. 均線法</h3>



<p>好像是財報狗的收費功能，其實還滿簡單計算的！</p>



<ul><li>當近三個月營收平均 &gt; 近一年月營收平均</li></ul>



<p>代表公司最近一季表現比較好，可能會有較亮眼的財報！但可能會有一些怪異的營建股，月營收突然暴增被選進來。</p>



<h3 id="2-突破法">2. 突破法</h3>



<p>這個是看Cmoney找到的，創新高的月營收容易被炒作，獲利效果還不錯，我發現24個月創新高最有用！</p>



<ul><li>創過去24個月創新高</li></ul>



<h3 id="3-成長法">3. 成長法</h3>



<p>這個是我自己研發的指標，其實我在<a href="https://www.finlab.tw/%E7%B5%95%E7%84%A1%E5%83%85%E6%9C%89%E7%9A%84%E8%B6%85%E5%BC%B7%E6%8C%87%E6%A8%99%EF%BC%81/">之前有講過</a>，計算稍微複雜一點：</p>



<ul><li>當我們要平滑月營收曲線時，取最近的 M 個值平均，產生新的曲線</li><li>新的曲線連續 N 個月不斷變高。</li></ul>



<p>主要是利用連續N個月，不斷成長的概念！</p>



<h3 id="最後還有MOM、QOQ、YOY">最後還有MOM、QOQ、YOY</h3>



<p>這些就是比較傳統一點的指標：</p>



<ul><li>MOM 這個月跟上個月比較</li><li>QOQ 當前一季跟前季比（三個月加總）</li><li>YOY 當月跟去年同月相比</li></ul>



<p>以下就是所有方法的回測，我們任意選擇一天觀察當月的指標，將符合條件的股票納入監測（假設平均買入），並在60天後賣出並選擇新的股票，每60天一次循環，以下是績效：<a href="https://www.finlab.tw/%E4%B8%89%E7%A8%AE%E6%9C%88%E7%87%9F%E6%94%B6%E9%80%B2%E9%9A%8E%E7%9C%8B%E6%B3%95/eq.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="710" height="437" src="http://34.96.136.135/wp-content/uploads/2020/07/eq-12.png" alt="eq 12" class="wp-image-625" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/eq-12.png 710w, https://www.finlab.tw/wp-content/uploads/2020/07/eq-12-300x185.png 300w" sizes="(max-width: 710px) 100vw, 710px" title="三種看月營收的進階方法！ 9"></figure></div>



<p>在這場大亂鬥中，從爛到優慢慢分析：</p>



<h3 id="傳統指標普遍效果較差">傳統指標普遍效果較差</h3>



<p>這三個指標，假如值為正就買入。<br>MOM 自然是最遜的指標，但也不能怪它，畢竟他只用了最近兩個月的數據<br>QOQ、YOY 表現比較好，但畢竟是傳統一點的指標，效果較差，但比MOM好很多了！</p>



<p>因為我是大於零就買入，所以可能效果比較不好，之後有機會再研究看看。</p>



<h3 id="第三名：均線法（average）">第三名：均線法（average）</h3>



<p>首先我們看到財報狗付費策略裡面，收錄的均線法（average），我們發現這個方法還不賴，每個月選到的股票大部分都在400檔以上，過年的二月也有一兩百檔，算是個很平穩的策略</p>



<h3 id="第二名：突破法（break-through）">第二名：突破法（break through）</h3>



<p>老實說<strong>突破法</strong>大部分的時間都輸給<strong>均線法</strong>，唯獨2015年中，壓注在單一檔股票（只有一檔符合條件），而該股票剛好是飆股，於是瞬間超越多數方法，然而非常不推薦一般選股使用。</p>



<h3 id="第一名：我發明的成長法（increase）">第一名：我發明的成長法（increase）</h3>



<p>最後我的<strong>成長法</strong>小勝一籌，原因是它選出的股票，獲利成長都常常很驚人（單看月營收的話）！但選出來的股票比較少，平常有一兩百檔，有時候只有數十檔，<strong>成長法</strong>的原理我在<a href="https://www.finlab.tw/%E7%B5%95%E7%84%A1%E5%83%85%E6%9C%89%E7%9A%84%E8%B6%85%E5%BC%B7%E6%8C%87%E6%A8%99%EF%BC%81/">那篇文章</a>&nbsp;有講過，有興趣可以看一看喔！</p>



<h3 id="選股參考：均線法">選股參考：均線法</h3>



<p><strong>均線法</strong>找出的股票數量比較多，每六檔股票裡面就有一檔，適合當選股的輔助判斷，每當你看某檔股票時，偶爾用均線法判斷一下。</p>



<h3 id="積極選股：成長法">積極選股：成長法</h3>



<p><strong>成長法</strong>找出的股票數量比較少，過濾了太多的股票（然而改變參數也是可以的），所以比較適合積極型選股，從中再挑選較好的股票。</p>



<p><strong>均線法</strong>跟<strong>成長法</strong>這兩個方法找出來的股票比較穩定，第二名的<strong>突破法</strong>有點像是賽到XDD，以後選股大可以參考這兩個指標，作為買賣參考依據！近日我會針對這兩個指標教大家實做！有興趣記得要關注這個部落格喔！</p>



<p>大家還知道月營收可以變出什麼有趣的指標嗎？可以分享給我喔！幫你測測看～</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/%e4%b8%89%e7%a8%ae%e6%9c%88%e7%87%9f%e6%94%b6%e9%80%b2%e9%9a%8e%e7%9c%8b%e6%b3%95/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">623</post-id>	</item>
		<item>
		<title>月營收這樣看！三種月營收選股法 &#8211; Python實作教學</title>
		<link>https://www.finlab.tw/python-%e7%b0%a1%e5%96%ae%e7%94%a8%e6%9c%88%e7%87%9f%e6%94%b6%e9%81%b8%e8%82%a1%ef%bc%81/</link>
					<comments>https://www.finlab.tw/python-%e7%b0%a1%e5%96%ae%e7%94%a8%e6%9c%88%e7%87%9f%e6%94%b6%e9%81%b8%e8%82%a1%ef%bc%81/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:21 +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=627</guid>

					<description><![CDATA[月營收的資訊是跟股價成高度相關，月營收好的股票比較容易漲，反之容易跌，被列為財報狗的付費功能之一。今天教大家如何用python免費使用此功能！這篇是完整的範例，教你如何下載月營收，過濾出可能會飆漲的股票。這個條件我很常用，效果也不錯，分享給大家！]]></description>
										<content:encoded><![CDATA[
<p>月營收的資訊是跟股價成高度相關，月營收好的股票比較容易漲，反之容易跌，被列為財報狗的付費功能之一。今天教大家如何用python免費使用此功能！這篇是完整的範例，教你如何下載月營收，過濾出可能會飆漲的股票。這個條件我很常用，效果也不錯，分享給大家！<a href="https://www.finlab.tw/Python-%E7%B0%A1%E5%96%AE%E7%94%A8%E6%9C%88%E7%87%9F%E6%94%B6%E9%81%B8%E8%82%A1%EF%BC%81/thumbnail.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="775" height="559" src="http://34.96.136.135/wp-content/uploads/2020/07/thumbnail-1-2.png" alt="thumbnail 1 2" class="wp-image-628" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-1-2.png 775w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-1-2-300x216.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-1-2-768x554.png 768w" sizes="(max-width: 775px) 100vw, 775px" title="月營收這樣看！三種月營收選股法 - Python實作教學 10"></figure></div>



<h3 id="下載近12個月的月報">下載近12個月的月報</h3>



<p>之前我們也講過<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/">如何獲取月營收的歷史資訊</a></p>



<p>請先到該網站把<code>monthly_report</code>給copy下來，我們接下來會用到喔！</p>



<p><code>monthly_report</code>這個函式，會下載上市公司月報，並整理成<code>pandas.DataFrame</code>，也就是一種存在python中的表格。接下來我們連續呼叫<code>monthly_report</code>來把近12個月的資料收集整齊：</p>



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

data = {}
n_days = 12
now = datetime.datetime.now()

year = now.year
month = now.month

while len(data) &lt; n_days:
    
    print('parsing', year, month)
    
    # 使用 crawPrice 爬資料
    try:
        data['%d-%d-01'%(year, month)] = monthly_report(year, month)
    except Exception as e:
        print('get 404, please check if the revenues are not revealed')
    
    # 減一個月
    month -= 1
    if month == 0:
        month = 12
        year -= 1

    time.sleep(10)</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="515" height="246" src="http://34.96.136.135/wp-content/uploads/2020/07/cmd1.png" alt="cmd1" class="wp-image-629" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/cmd1.png 515w, https://www.finlab.tw/wp-content/uploads/2020/07/cmd1-300x143.png 300w" sizes="(max-width: 515px) 100vw, 515px" title="月營收這樣看！三種月營收選股法 - Python實作教學 11"></figure></div>



<p><a href="https://www.finlab.tw/Python-%E7%B0%A1%E5%96%AE%E7%94%A8%E6%9C%88%E7%87%9F%E6%94%B6%E9%81%B8%E8%82%A1%EF%BC%81/cmd1.png"></a>執行的時候，有一行error，因為新的月報還沒有下來的原因，而其它天都是成功的，這樣都算是正常！</p>



<p>以上這段code請大家一定要看的懂喔！我們要的只有 data 這個 dictionary 物件，裡面依照不同的日期，存放著所有股票的月營收。例如，你可以顯示<code>data['2017-12-01']</code>，就會顯示以下這張表：<a href="https://www.finlab.tw/Python-%E7%B0%A1%E5%96%AE%E7%94%A8%E6%9C%88%E7%87%9F%E6%94%B6%E9%81%B8%E8%82%A1%EF%BC%81/cmd2.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="355" src="http://34.96.136.135/wp-content/uploads/2020/07/cmd2-1024x355.png" alt="cmd2" class="wp-image-630" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/cmd2-1024x355.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/cmd2-300x104.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/cmd2-768x266.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/cmd2.png 1126w" sizes="(max-width: 1024px) 100vw, 1024px" title="月營收這樣看！三種月營收選股法 - Python實作教學 12"></figure></div>



<p>代表 2017 年 12 月的月營收。</p>



<h3 id="數據處理-合成時間序列">數據處理 &#8211; 合成時間序列</h3>



<p>根據不同的日期，有不同的dataFrame，用起來有點麻煩，所以我們再經過一個處理，將所有數據結合，變成時間序列：</p>



<p>數據處理─結合月營收資訊</p>



<pre class="wp-block-code"><code class="">for k in data.keys():
    data[k].index = data[k]['公司代號']
    
df = pd.DataFrame({k:df['當月營收'] for k, df in data.items()}).transpose()
df.index = pd.to_datetime(df.index)
df = df.sort_index()</code></pre>



<p>最後產出的 df 可以囉！df 的結構如下：<a href="https://www.finlab.tw/Python-%E7%B0%A1%E5%96%AE%E7%94%A8%E6%9C%88%E7%87%9F%E6%94%B6%E9%81%B8%E8%82%A1%EF%BC%81/cmd3.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/cmd3-1024x314.png" alt="cmd3" class="wp-image-631" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/cmd3-1024x314.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/cmd3-300x92.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/cmd3-768x236.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/cmd3.png 1121w" sizes="(max-width: 1024px) 100vw, 1024px" title="月營收這樣看！三種月營收選股法 - Python實作教學 13"></figure></div>



<p>這個 df 超級好用，以下示範畫出 1101（台泥） 的月營收曲線圖：<a href="https://www.finlab.tw/Python-%E7%B0%A1%E5%96%AE%E7%94%A8%E6%9C%88%E7%87%9F%E6%94%B6%E9%81%B8%E8%82%A1%EF%BC%81/cmd4.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="377" src="http://34.96.136.135/wp-content/uploads/2020/07/cmd4-1024x377.png" alt="cmd4" class="wp-image-632" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/cmd4-1024x377.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/cmd4-300x110.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/cmd4-768x283.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/cmd4.png 1117w" sizes="(max-width: 1024px) 100vw, 1024px" title="月營收這樣看！三種月營收選股法 - Python實作教學 14"></figure></div>



<p>還有他的MOM：<a href="https://www.finlab.tw/Python-%E7%B0%A1%E5%96%AE%E7%94%A8%E6%9C%88%E7%87%9F%E6%94%B6%E9%81%B8%E8%82%A1%EF%BC%81/cmd5.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="336" src="http://34.96.136.135/wp-content/uploads/2020/07/cmd5-1024x336.png" alt="cmd5" class="wp-image-633" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/cmd5-1024x336.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/cmd5-300x99.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/cmd5-768x252.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/cmd5.png 1117w" sizes="(max-width: 1024px) 100vw, 1024px" title="月營收這樣看！三種月營收選股法 - Python實作教學 15"></figure></div>



<p>各種變化就讓大家自己去玩囉～這邊還是得著重在選股的功能上！</p>



<h3 id="開始選股">開始選股</h3>



<p>首先，大家可以參考最近寫的，<a href="https://www.finlab.tw/%E4%B8%89%E7%A8%AE%E6%9C%88%E7%87%9F%E6%94%B6%E9%80%B2%E9%9A%8E%E7%9C%8B%E6%B3%95/">三種月營收進階看法</a>，裡面的選股條件，接下來會一一實做：</p>



<h3 id="平均線法">平均線法</h3>



<p>平均線法選股</p>



<pre class="wp-block-code"><code class="">method1 = df.iloc[-3:].mean() > df.iloc[-12:].mean()
method1[method1 == True].index</code></pre>



<p>噹啷！就這麼一行，選出來了，會有非常多的標的，還可以再進行過濾。<br>這邊有一些厲害的 function 提一下：</p>



<ul><li>iloc[i:j] 選取第i個到第j個數據</li><li>mean() 選處取出來的series的平均</li></ul>



<h3 id="成長法">成長法</h3>



<p>成長法選股</p>



<pre class="wp-block-code"><code class="">method2 = df.rolling(4, min_periods=2).mean()
method2 = (method2 > method2.shift()).iloc[-5:].sum()
method2[method2 == 5]</code></pre>



<p>第一行首先是平滑，做出平均序列，其中<code>min_periods=2</code>&nbsp;代表只要有兩筆數據以上，就計算平均，不然就寫成NaN。<br>第二、三行是說這條平滑曲線，近五個月都是上升</p>



<h3 id="創新高法">創新高法</h3>



<p>創新高法選股</p>



<pre class="wp-block-code"><code class="">method3 = df.iloc[-1] == df.iloc[-12:].max()
method3[method3 == True].index</code></pre>



<h3 id="使用方法">使用方法</h3>



<p>可以將各種的條件再做組合，例如用<a href="https://www.finlab.tw/%E8%82%A1%E5%83%B9%E6%B7%A8%E5%80%BC%E6%AF%94%E6%9C%89%E9%80%99%E9%BA%BC%E7%A5%9E%EF%BC%9F/">股價淨值比</a>，或是&nbsp;<a href="https://www.finlab.tw/EPS%E8%B7%9FROE%E5%93%AA%E5%80%8B%E6%AF%94%E8%BC%83%E5%A5%BD%E7%94%A8%EF%BC%9F/">ROE</a>，實測都有不錯的效果喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/python-%e7%b0%a1%e5%96%ae%e7%94%a8%e6%9c%88%e7%87%9f%e6%94%b6%e9%81%b8%e8%82%a1%ef%bc%81/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">627</post-id>	</item>
		<item>
		<title>超簡單用python抓取每月營收</title>
		<link>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/</link>
					<comments>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/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 22 Jul 2020 07:05:01 +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=498</guid>

					<description><![CDATA[今天承接上次的超簡單python系列，教大家如何得到每家企業每個月的營收。這個系列的最終目的就是讓大家可以創造自己的投資自動化程式，甚至擁有自己的看盤軟體。]]></description>
										<content:encoded><![CDATA[
<p>今天承接上次的超簡單python系列，教大家如何得到每家企業每個月的營收。這個系列的最終目的就是讓大家可以創造自己的投資自動化程式，甚至擁有自己的看盤軟體。</p>



<p>真的不要把程式交易想像的很難，感覺爬2000多支股票，並整理資料，好像是一件很累很痛苦的是情，但真的只需要30行，你可能會覺得這些代碼真的太短了，但真的就是這麼短，然而這必須建立在python或是R，這些package豐富的腳本語言才有可能辦到，這兩個語言都不錯，但我比較喜歡寫python就是了XD，因為python還可以做很多酷炫的事情，例如寫server，或是一些自動化工具，然而R好像沒有這麼多功能？</p>



<p>那我們就來爬取吧！首先先決定要爬哪個網頁，我選擇的是<a href="http://mops.twse.com.tw/nas/t21/sii/t21sc03_103_2_0.html" rel="noreferrer noopener" target="_blank">TWSE官方網頁</a><br>它的網址是<br><a href="http://mops.twse.com.tw/nas/t21/sii/t21sc03_103_2_0.html" rel="noreferrer noopener" target="_blank">http://mops.twse.com.tw/nas/t21/sii/t21sc03_103_2_0.html</a></p>



<p>各位有看到103這個數字嗎？其實這個就是年份，而緊接在後面的 “2” 就是月份，所以只要改動這兩個值，我們就可以下載不同年月的歷史資訊：</p>



<p>月爬蟲</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">import pandas as pd
import requests
from io import StringIO
import time
def monthly_report(year, month):
    
    # 假如是西元，轉成民國
    if year > 1990:
        year -= 1911
    
    url = 'https://mops.twse.com.tw/nas/t21/sii/t21sc03_'+str(year)+'_'+str(month)+'_0.html'
    if year &lt;= 98:
        url = 'https://mops.twse.com.tw/nas/t21/sii/t21sc03_'+str(year)+'_'+str(month)+'.html'
    
    # 偽瀏覽器
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
    
    # 下載該年月的網站，並用pandas轉換成 dataframe
    r = requests.get(url, headers=headers)
    r.encoding = 'big5'

    dfs = pd.read_html(StringIO(r.text), encoding='big-5')

    df = pd.concat([df for df in dfs if df.shape[1] &lt;= 11 and df.shape[1] > 5])
    
    if 'levels' in dir(df.columns):
        df.columns = df.columns.get_level_values(1)
    else:
        df = df[list(range(0,10))]
        column_index = df.index[(df[0] == '公司代號')][0]
        df.columns = df.iloc[column_index]
    
    df['當月營收'] = pd.to_numeric(df['當月營收'], 'coerce')
    df = df[~df['當月營收'].isnull()]
    df = df[df['公司代號'] != '合計']
    
    # 偽停頓
    time.sleep(5)

    return df</code></pre>



<p>以上這段程式碼就是一個function可以在其它地方隨時呼叫，code真的超短，但這樣就夠了！</p>



<p>接下來我們隨意讀取任意年月份（可以用民國或是西元都支援）：</p>



<p>月爬蟲</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers"># 民國100年1月
monthly_report(100,1)

# 西元2011年1月
monthly_report(2011,1)</code></pre>



<p>就會跑出以下的表格：<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/table.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="890" height="319" src="http://34.96.136.135/wp-content/uploads/2020/07/table.png" alt="table" class="wp-image-499" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/table.png 890w, https://www.finlab.tw/wp-content/uploads/2020/07/table-300x108.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/table-768x275.png 768w" sizes="(max-width: 890px) 100vw, 890px" title="超簡單用python抓取每月營收 16"></figure></div>



<p>其實寫程式真的好簡單XDD，坊間財經軟體都好貴，不就是幾行code而已，是不是！<br>目前已經交完 日、月 的資料爬取了，下一次就是一季囉！</p>



<p>當然還有各式各樣可以爬的東西，有時間再跟大家介紹～</p>
]]></content:encoded>
					
					<wfw:commentRss>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/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">498</post-id>	</item>
	</channel>
</rss>
