<?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>BTC &#8211; FinLab</title>
	<atom:link href="https://www.finlab.tw/tag/btc/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.finlab.tw</link>
	<description>深入淺出的量化投資，讓你在在茫茫股海中，找到專屬於自己的投資方法</description>
	<lastBuildDate>Tue, 12 Jul 2022 02:04:18 +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>BTC &#8211; FinLab</title>
	<link>https://www.finlab.tw</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">179699571</site>	<item>
		<title>機器學習 Python 做比特幣交易，如何找到好的特徵？增進模型的有效工具</title>
		<link>https://www.finlab.tw/python-machine-learning-bitcoin-feature-engineering/</link>
					<comments>https://www.finlab.tw/python-machine-learning-bitcoin-feature-engineering/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Wed, 11 May 2022 05:30:26 +0000</pubDate>
				<category><![CDATA[AI看股票]]></category>
		<category><![CDATA[BTC]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[機器學習]]></category>
		<category><![CDATA[比特幣]]></category>
		<category><![CDATA[程式交易]]></category>
		<category><![CDATA[量化投資]]></category>
		<guid isPermaLink="false">https://www.finlab.tw/?p=3520</guid>

					<description><![CDATA[這篇文章用機器學習實作能獲利的 BTCUSDT 交易模型，使用 Tunta 優化特徵，獲得更好的交易預測能力， [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>這篇文章用<a href="https://www.finlab.tw/category/ai%e7%9c%8b%e8%82%a1%e7%a5%a8/">機器學習</a>實作能獲利的 <a href="https://www.finlab.tw/category/%e5%8a%a0%e5%af%86%e8%b2%a8%e5%b9%a3/">BTCUSDT</a> 交易模型，使用 Tunta 優化特徵，獲得更好的交易預測能力，會有機器學習範例講解。現在的機器學習，已經越來越複雜，一個能夠實戰的模型，最好是有數百甚至是上千個 features。然而這麼多 features，並不是常人用手工一個個產生出來的，必須要大量的仰賴自動化生成。例如像是 Numerai 平台，最近更新的 <a href="https://forum.numer.ai/t/super-massive-data-release-deep-dive/4053" target="_blank" rel="noopener">features 數量都已經破千了</a>，代表更多的 features 確實會對於訓練模型有所幫助。</p>



<p>Numerai 提供股票的 features，由資料科學家（我們）訓練模型並產生結果，上傳後匯聚成最後的權重，來控制對沖基金的部位。我們沒辦法知道每檔股票的名稱，所以沒辦法用 Numerai 的 features 來做交易，但我們上傳到平台上，假如績效好的話，Numerai 會額外給我們加密貨幣 NMR 當作獎勵，雖然 Numerai 是很棒的練兵的地方，但是由於要用 Stake NMR 加密貨幣才能獲利，而且 NMR 的價格波動會導致獲利的風險偏高。所以還是自己做交易比較實在，想要機器學習自學，就看這篇吧！</p>



<p>那要怎麼樣產生出上千個 features 呢？好在用 Python 製作 features 是很簡單的，只要用常見的 Packages 像是 Talib 或 pandas_ta ，加上參數的變化，就可以隨機產生出很多的 features。但困難在於，做了好幾千個 features，究竟哪些是重要的呢？假如用了沒意義的 features，反而混淆訓練結果，造成模型的績效效果不好。</p>



<h2>Tuneta 介紹</h2>



<p>介紹給大家 <a class="rank-math-link" href="https://github.com/jmrichardson/tuneta/tree/53960a8d83cec586a3d91e2667dcf0f364522533" target="_blank" rel="noopener">Tuneta</a> 這個工具可以幫我們最佳化技術指標的參數。它有以下幾個功能：</p>



<ol><li>支援 <a href="https://www.finlab.tw/python-%e7%b0%a1%e5%96%ae158%e7%a8%ae%e6%8a%80%e8%a1%93%e6%8c%87%e6%a8%99%e8%a8%88%e7%ae%97/">Talib</a>、Pandas_ta、finta，這三種不同的函式庫，有統一的接口，你再也不用擔心不同函式庫整合的問題。</li><li>針對每種技術指標，可以最佳化參數，讓產生出來的 feature 跟 lable 之間有最高的 correlation</li><li>並不是使用一般的 Pearson correlation coefficient 來判斷，而是使用一種叫做 distance correlation 的判斷機制，就算是非線性的關係也會被納入考慮。</li><li>使用 KNN 將搜尋的參數分群 Cluster，然後針對每一個 Cluster 找出中心點，這個作法可以找到參數高原。</li><li>產生每個 features 後，支援 sklearn 的 pipeline 格式，可以快速的引入當前的項目之中，點也不費力。</li></ol>



<h2>Tuneta 的效果</h2>



<p>以下是 Tuneta 做機器學習例子，加入我自己的機器學習系統中，確實對於 Model 的判斷有顯著的增長，並且使用 feature importance 分析，這些 tuneta 產生的 feature 確實分數都滿高的：</p>



<figure class="wp-block-image size-full"><img width="974" height="455" src="https://www.finlab.tw/wp-content/uploads/2022/05/image-8.png" alt="image 8" class="wp-image-3551" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/image-8.png 974w, https://www.finlab.tw/wp-content/uploads/2022/05/image-8-300x140.png 300w, https://www.finlab.tw/wp-content/uploads/2022/05/image-8-768x359.png 768w" sizes="(max-width: 974px) 100vw, 974px" title="機器學習 Python 做比特幣交易，如何找到好的特徵？增進模型的有效工具 1"><figcaption>機器學習 LightGBM 特徵重要性分析</figcaption></figure>



<p>機器學習深度學習，我覺得在做交易時比較少用到。比較常使用的是傳統 treebase 的模型，而非神經網路。我覺得這個 Package 的缺點在於，有時候我們會需要重複的指標當作 features，例如「sma(10)」和「sma(60)」，但是它只能幫我們產生出單個技術指標的最佳解。不過經過驗證，產生出來的 features，確實效果都還不錯！接下來我們就真的來建構一個模型吧！</p>



<h2>實驗設計</h2>



<p>機器學習python實作，我們使用 pandas_ta 的 default 參數，將所有 pandas_ta 的技術指標計算出來。另外對比 tuneta 優化後產生的技術指標，比較兩個模型的預測結果，並且用回測來驗證是否能真正幫助到獲利。</p>



<p>使用 colab 來建構統一的環境，方便大家還原實驗的結果。首先我們要先來下載 tuneta，但除了 tuneta 以外，還要有歷史資料，可以安裝 finlab-crypto 來獲得。</p>



<pre title="環境架設" class="wp-block-code"><code lang="bash" class="language-bash line-numbers">!pip install finlab-crypto -q
!wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz
!tar -xzvf ta-lib-0.4.0-src.tar.gz
%cd ta-lib
!./configure --prefix=/usr
!make
!make install
!pip install Ta-Lib
!pip install -U tuneta
!pip uninstall numpy --yes
!pip install numpy</code></pre>



<h2>下載歷史資料和 feature 建構</h2>



<p>安裝了所需的 Package ，就可以來下載歷史資料：</p>



<pre title="下載歷史資料" class="wp-block-code"><code lang="python" class="language-python line-numbers">from finlab_crypto import crawler

ohlcv = crawler.get_all_binance('BTCUSDT', '4h')
ohlcv.head()</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="242" src="https://www.finlab.tw/wp-content/uploads/2022/05/image-1-1024x242.png" alt="image 1" class="wp-image-3530" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/image-1-1024x242.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/05/image-1-300x71.png 300w, https://www.finlab.tw/wp-content/uploads/2022/05/image-1-768x182.png 768w, https://www.finlab.tw/wp-content/uploads/2022/05/image-1.png 1133w" sizes="(max-width: 1024px) 100vw, 1024px" title="機器學習 Python 做比特幣交易，如何找到好的特徵？增進模型的有效工具 2"><figcaption>下載BTC歷史資料</figcaption></figure>



<h3>使用 Pandas_ta 產生 features</h3>



<p>接下來我們先用 pandas_ta 自動產生出預設的技術指標，當作對照組：</p>



<pre title="產生技術指標的 features" class="wp-block-code"><code lang="python" class="language-python line-numbers">import pandas_ta as ta
ohlcv.ta.strategy("Momentum")

default_features = ohlcv.iloc[:, 11:]
ohlcv = ohlcv.iloc[:, :11]
default_features.head()</code></pre>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="325" src="https://www.finlab.tw/wp-content/uploads/2022/05/image-2-1024x325.png" alt="image 2" class="wp-image-3531" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/image-2-1024x325.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/05/image-2-300x95.png 300w, https://www.finlab.tw/wp-content/uploads/2022/05/image-2-768x244.png 768w, https://www.finlab.tw/wp-content/uploads/2022/05/image-2.png 1043w" sizes="(max-width: 1024px) 100vw, 1024px" title="機器學習 Python 做比特幣交易，如何找到好的特徵？增進模型的有效工具 3"><figcaption>產生出 features</figcaption></figure>



<h3>使用 Tuneta 產生 features</h3>



<p>接下來我們用 tuneta 產生實驗組，眼尖的人會發現我是用 tta，也就是 talib 函式庫來產生 features，你也可以用 pta，也就是 pandas_ta 函式庫。但是在 colab 上要跑很久，所以我擅自改成 tta。在這邊實驗有點不完備，但留給大家自行發揮。</p>



<pre title="tuneta 產生 features" class="wp-block-code"><code lang="python" class="language-python line-numbers">from tuneta.tune_ta import TuneTA

train_test_split = '2021-1-1'

X1 = ohlcv.loc[:train_test_split].iloc[:-8]
y1 = (ohlcv.close.shift(-2) / ohlcv.close).loc[:train_test_split].iloc[:-8]

tt = TuneTA(n_jobs=4, verbose=True)
tt.fit(X1, y1,
    indicators=['tta'],
    ranges=[(2, 30)],
    trials=100,
    early_stop=20,
)
tt.prune()
print(tt.report())

tt_features = tt.transform(ohlcv)
tt_features.tail()</code></pre>



<figure class="wp-block-image size-full"><img loading="lazy" width="578" height="524" src="https://www.finlab.tw/wp-content/uploads/2022/05/image-3.png" alt="image 3" class="wp-image-3532" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/image-3.png 578w, https://www.finlab.tw/wp-content/uploads/2022/05/image-3-300x272.png 300w" sizes="(max-width: 578px) 100vw, 578px" title="機器學習 Python 做比特幣交易，如何找到好的特徵？增進模型的有效工具 4"><figcaption>tuneta 產生出來的 feature 和相關性分析</figcaption></figure>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="258" src="https://www.finlab.tw/wp-content/uploads/2022/05/image-4-1024x258.png" alt="image 4" class="wp-image-3533" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/image-4-1024x258.png 1024w, https://www.finlab.tw/wp-content/uploads/2022/05/image-4-300x76.png 300w, https://www.finlab.tw/wp-content/uploads/2022/05/image-4-768x194.png 768w, https://www.finlab.tw/wp-content/uploads/2022/05/image-4.png 1249w" sizes="(max-width: 1024px) 100vw, 1024px" title="機器學習 Python 做比特幣交易，如何找到好的特徵？增進模型的有效工具 5"></figure>



<p>最後我們來比較兩種不同的 feature 做出來的效果。像是一般的方法訓練即可。</p>



<h2>模型訓練</h2>



<pre title="模型建構" class="wp-block-code"><code lang="python" class="language-python line-numbers">import lightgbm as lgb

# generate training data
X1_train, y1_train = default_features.loc[:train_test_split].iloc[:-8], ohlcv.close.pct_change(-2).loc[:train_test_split].iloc[:-8]
X2_train, y2_train = tt_features.loc[:train_test_split].iloc[:-8], ohlcv.close.pct_change(-2).loc[:train_test_split].iloc[:-8]

# train
model1 = lgb.LGBMRegressor()
model1.fit(X1_train, y1_train)

model2 = lgb.LGBMRegressor()
model2.fit(X2_train, y2_train)

# test and predict
X1_test, y1_test = default_features.loc[train_test_split:], ohlcv.close.pct_change(-2).loc[train_test_split:]
X2_test, y2_test = tt_features.loc[train_test_split:], ohlcv.close.pct_change(-2).loc[train_test_split:]

y1 = pd.Series(model1.predict(X1_test), X1_test.index)
y2 = pd.Series(model2.predict(X2_test), X2_test.index)</code></pre>



<p>最後我們來看一下究竟效果如何，可以用真實報酬跟預測結果的相關性來比較，越高代表越好。下面的實驗中，我們可以看到對照組的模型 ( model2 ) 比實驗組好很多。</p>



<pre title="比較兩個模型的相關性" class="wp-block-code"><code lang="python" class="language-python line-numbers">import pandas as pd

pd.DataFrame({'real': y1_test, 'pred': y1}).corr().iloc[1,0], pd.DataFrame({'real': y2_test, 'pred': y2}).corr().iloc[1,0]</code></pre>



<pre class="wp-block-preformatted">(0.007258040702236883, 0.02274027435611208)</pre>



<hr class="wp-block-separator has-css-opacity"/>



<p>最後我們可以做一個簡單的回測，試試看用這兩個模型做交易，績效會有什麼不一樣。首先，要決定進場的時機，將模型預測的分布顯示出來：</p>



<figure class="wp-block-image size-full"><img loading="lazy" width="798" height="426" src="https://www.finlab.tw/wp-content/uploads/2022/05/image-5.png" alt="image 5" class="wp-image-3534" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/image-5.png 798w, https://www.finlab.tw/wp-content/uploads/2022/05/image-5-300x160.png 300w, https://www.finlab.tw/wp-content/uploads/2022/05/image-5-768x410.png 768w" sizes="(max-width: 798px) 100vw, 798px" title="機器學習 Python 做比特幣交易，如何找到好的特徵？增進模型的有效工具 6"><figcaption>模型預測分布</figcaption></figure>



<p>有了上圖，就可以設計進場時機，為預測結果大於 0.04 時進場8小時。接下來撰寫回測模擬：</p>



<pre title="回測" class="wp-block-code"><code lang="python" class="language-python line-numbers">y1_test[y1 &gt; 0.04].add(1).cumprod().plot()
y2_test[y2 &gt; 0.04].add(1).cumprod().plot()</code></pre>



<figure class="wp-block-image size-full"><img loading="lazy" width="507" height="340" src="https://www.finlab.tw/wp-content/uploads/2022/05/image-6.png" alt="image 6" class="wp-image-3535" srcset="https://www.finlab.tw/wp-content/uploads/2022/05/image-6.png 507w, https://www.finlab.tw/wp-content/uploads/2022/05/image-6-300x201.png 300w" sizes="(max-width: 507px) 100vw, 507px" title="機器學習 Python 做比特幣交易，如何找到好的特徵？增進模型的有效工具 7"></figure>



<p>上圖的回測結果中，綠色為實驗組，比對照組的報酬率顯著上升不少。</p>



<h4>小節</h4>



<p>由以上的實驗，可以證明對於 feature ，使用 Tuneta 參數優化是非常有效的。現在行情不好，大家可以趁現在默默耕耘，等時機到的時候，馬上就賺回來了！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/python-machine-learning-bitcoin-feature-engineering/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3520</post-id>	</item>
		<item>
		<title>每天只要15分鐘 &#8211; 超簡單學會 Python 自動化貨投資比特幣</title>
		<link>https://www.finlab.tw/btc-summary/</link>
					<comments>https://www.finlab.tw/btc-summary/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Tue, 21 Jul 2020 04:02:00 +0000</pubDate>
				<category><![CDATA[加密貨幣]]></category>
		<category><![CDATA[BTC]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[比特幣]]></category>
		<category><![CDATA[自動下單]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=1133</guid>

					<description><![CDATA[2017年12月，比特幣曾一天上漲20％！我的朋友說，他投資了加密貨幣，但過了一個禮拜，比特幣的價格開始崩盤，而他卻買在高點，我就在想，有沒有一種投資方法，可以自動化投資加密貨幣，卻不用承受這麼高的風險？於是開始研究基於加密貨幣的量化投資，寫成一系列的文章，共12篇分享給大家！]]></description>
										<content:encoded><![CDATA[
<p>2017年12月，比特幣曾一天上漲20％！<br>我的朋友說，他投資了加密貨幣，<br>但過了一個禮拜，比特幣的價格開始崩盤，而他卻買在高點，</p>



<p>我就在想，有沒有一種投資方法，<br>可以自動化投資加密貨幣，卻不用承受這麼高的風險？<br>於是開始研究基於加密貨幣的量化投資，<br>寫成一系列的文章，共12篇，一篇只需要操作 15 分鐘，<br>分享給大家！<a href="https://www.finlab.tw/btc-summary/summary.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="453" src="http://34.96.136.135/wp-content/uploads/2020/07/summary-1-1024x453.png" alt="summary 1" class="wp-image-1134" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/summary-1-1024x453.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/summary-1-300x133.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/summary-1-768x340.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/summary-1-1536x679.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/summary-1.png 1624w" sizes="(max-width: 1024px) 100vw, 1024px" title="每天只要15分鐘 - 超簡單學會 Python 自動化貨投資比特幣 8"></figure></div>



<h3 id="為什麼要投資加密貨幣">為什麼要投資加密貨幣</h3>



<p>加密貨幣當前是個小眾市場，但是有很大的潛力<br>從貨幣供給、基本面的角度，加密貨幣也是非常有市場的<br>是值得投資的商品</p>



<p>德意志交易所（Deutsche Bórse）<br>這個月發行了 BTC-E<br>是由 100% BTC 支持的<br>代表每個德國人，都可以從股票帳戶購買 BTC！</p>



<p>當初被世界各國禁止，<br>現在反而是逐漸開放，<br>從期貨、現貨等，進入人們的日常，<br>你還覺得加密貨幣沒有未來嗎？</p>



<p><a href="https://www.finlab.tw/python-bitcoin-trading-why-bitcoin/">前導：（Python x Crypto (Part 1)：為什麼是比特幣？）</a></p>



<p>然而投資跟投機往往一線之間，<br>像是比特幣<br>波動就非常大！<br>所以持有時加密貨幣一定要</p>



<ul><li>少部位</li><li>用量化分析降低風險</li></ul>



<h3 id="買入時機：-Miner-Capitulation-指標">買入時機： Miner Capitulation 指標</h3>



<p>長期投資，究竟要怎麼投資比特幣？<br>可以參考一個很有用的指標，<br>不過這個指標的原理，比較複雜，<br>需要兩篇的時間慢慢解說：</p>



<ul><li><a href="https://www.finlab.tw/best-indicator-bitcoin/">用Python投資加密貨幣：比特幣操作最強指標(原理篇)</a></li><li><a href="https://www.finlab.tw/btc-tradingview-intro/">用Python投資加密貨幣：比特幣操作最強指標(技術篇)</a></li></ul>



<p>學完後，你就可以製作出下面這種專業的操盤工具喔！<a href="https://www.finlab.tw/btc-summary/ind.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="485" src="http://34.96.136.135/wp-content/uploads/2020/07/ind-2-1-1024x485.png" alt="ind 2 1" class="wp-image-1136" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/ind-2-1-1024x485.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/ind-2-1-300x142.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/ind-2-1-768x364.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/ind-2-1-1536x728.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/ind-2-1-2048x970.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="每天只要15分鐘 - 超簡單學會 Python 自動化貨投資比特幣 9"></figure></div>



<p>上述指標<br>在歷史上看來很準確<br>但是可以投資的時機真的太少了<br>畢竟比特幣的上漲跟下跌週期非常長</p>



<p>要怎麼樣可以安穩的投資加密貨幣呢？<br>我們可以用量化投資的方式，<br>只要重複做簡單的操作<br>就可以有效控制風險！</p>



<h3 id="用-Python-做量化投資">用 Python 做自動化投資（量化投資）</h3>



<p>要打造一個可用的交易策略，<br>可以參考下方的文章<br>每一步程式碼都可以在&nbsp;<a href="https://colab.research.google.com/" rel="noreferrer noopener" target="_blank">Colab</a>&nbsp;線上執行<br>不需要安裝和設定 Python 環境，<br>你可以現在就跟我們一起<br>來做量化投資的實驗喔！</p>



<ol><li>獲得歷史數據：<a href="https://www.finlab.tw/btc-crawler-py/">加密貨幣爬蟲撰寫</a></li><li>找出交易訊號：<a href="https://www.finlab.tw/btc-trading-signal/">交易策略訊號實做</a></li><li>模擬回測績效：<a href="https://www.finlab.tw/btc-simple-sma-backtesting/">實做回測績效驗證</a></li><li>策略參數優化：<a href="https://www.finlab.tw/btc-backtesting-optimization/">二十倍的策略優化</a></li></ol>



<p>學完上方單元，就能做出歷史績效高達20倍的比特幣交易策略喔！<a href="https://www.finlab.tw/btc-summary/after.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="737" src="http://34.96.136.135/wp-content/uploads/2020/07/after-1-2-1024x737.png" alt="after 1 2" class="wp-image-1138" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/after-1-2-1024x737.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/after-1-2-300x216.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/after-1-2-768x553.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/after-1-2-1536x1105.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/after-1-2.png 1932w" sizes="(max-width: 1024px) 100vw, 1024px" title="每天只要15分鐘 - 超簡單學會 Python 自動化貨投資比特幣 10"></figure></div>



<p>有了以上的研究，<br>再加上你自己的創意，<br>不斷的嘗試，<br>就會有底氣，<br>可以買入人生第一枚加密貨幣了！</p>



<h3 id="加密貨幣入金">加密貨幣入金</h3>



<p>然而，究竟要怎麼買？買多少？這篇文章告訴你：</p>



<ul><li><a href="https://www.finlab.tw/btc-deposit-how/">如何投資加密貨幣</a></li><li><a href="https://www.finlab.tw/btc-deposit-ways/">加密貨幣入金</a></li></ul>



<p>上面的文章總結，<br>我們可以有兩種投資的方法：</p>



<ol><li>小額長線投資</li><li>量化策略投資</li></ol>



<p>其中，量化投資需要有紀律的操作，<br>但是，萬一訊號出現在午夜，<br>難道我們要熬夜操做嗎？<br>也太累了吧？！</p>



<p>所以我們也額外教大家<br>怎麼做一個全自動化的策略<br>我們是利用&nbsp;<a href="https://aws.amazon.com/" rel="noreferrer noopener" target="_blank">Amazon Web Service （AWS）</a><br>裡面的 Lambda 功能<br>來自動監控策略，<br>決定買入賣出的喔！</p>



<h3 id="策略雲端交易">策略雲端交易</h3>



<p>使用 AWS Lambda 的好處<br>就是在每個月提供 400,000 GB-seconds 的額度<br>照著下方的教學，基本上不太會超額<br>讓你雲端<strong>免費</strong>自動下單交易！</p>



<ul><li><a href="https://www.finlab.tw/aws-lambda-initial-setup/">基本功能：AWS 簡易架設</a></li><li><a href="https://www.finlab.tw/btc-aws-lambda-signal-update/">用 AWS 算出策略多空</a></li><li><a href="https://www.finlab.tw/btc-aws-signal-trigger-condition/">AWS 手機監控與雲端下單</a></li></ul>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="978" height="636" src="http://34.96.136.135/wp-content/uploads/2020/07/thumbnail-6-8.png" alt="thumbnail 6 8" class="wp-image-1140" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-6-8.png 978w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-6-8-300x195.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-6-8-768x499.png 768w" sizes="(max-width: 978px) 100vw, 978px" title="每天只要15分鐘 - 超簡單學會 Python 自動化貨投資比特幣 11"></figure></div>



<p><a href="https://www.finlab.tw/btc-summary/cloud.png"></a></p>



<p>有了雲端的自動執行策略，<br>就可以讓你 忘記交易<br>直到某一天 突然想起<br>打開手機，發現帳戶資產多了個零！（為了押韻，純屬效果XD）</p>



<h3 id="用最科學的方式，投資最先進的貨幣">用最科學的方式，投資最先進的貨幣</h3>



<p>加密貨幣是體制上的顛覆，<br>加密貨幣之於傳統貨幣，就像是Uber之於計程車行一樣，<br>引入新的科技，必然會有一些配套措施來不及因應（詐騙、價格波動），<br>也會引來舊有制度的既得利益者反感。</p>



<p>加密貨幣的發展有些顛頗，<br>但長期來說，整個世代會朝著先進、便利的方向發展。<br>或許一百年後的未來，大家會嘲笑現在的金融體制怎麼這麼不方便呢！</p>



<p>FinLab 的目標，就是<br>希望可以在量化投資的路上，當大家的「武器製造商」！<br>就讓我們一起用 Python 勇闖未來吧！</p>



<p>如果喜歡我們的文章，也歡迎參考我們最新募資的線上課程「<a rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank">用 Python 理財：打造加密貨幣實戰策略</a>」，在線上課程中，我們會更有系統、更完整地教您如何從無到有，打造10種加密貨幣實戰策略，並且能夠自動化雲端交易！有興趣的話，可以<a rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank">點此觀看課程介紹影片</a>喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/btc-summary/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1133</post-id>	</item>
		<item>
		<title>用Python投資加密貨幣：為什麼是比特幣？ (Part 1)</title>
		<link>https://www.finlab.tw/python-bitcoin-trading-why-bitcoin/</link>
					<comments>https://www.finlab.tw/python-bitcoin-trading-why-bitcoin/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Mon, 20 Jul 2020 12:02:49 +0000</pubDate>
				<category><![CDATA[加密貨幣]]></category>
		<category><![CDATA[BTC]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[比特幣]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=1014</guid>

					<description><![CDATA[原本想說開一個比特幣的相關課程，介紹加密貨幣做portfolio selection，不過因為種種因素決定還是寫成免費一系列的文章，介紹用 Python 建置比特幣交易系統。加密貨幣，會不會就是30年前的筆電呢？可能會，可能不會。但是這些都不是我說了算...]]></description>
										<content:encoded><![CDATA[
<p>原本想說開一個課程，介紹加密貨幣做portfolio selection，不過因為種種因素，決定還是寫成免費一系列的文章，介紹用 Python 建置 比特幣 交易系統。</p>



<p>2020年註：因為後來有很多研究成果，所以綜合所學，系統性的量化分析、程式碼整裡放在Hahow 的課程中，文章部分維持免費不做刪減，你可以先參考這12篇文章，再來決定是不是值得更深入學習加密貨幣的量化交易喔！</p>



<p>新科技，如 machine learning、blockchain，或許可以說「有缺點」、「不成熟」、「尚未完善」，但同時也是<strong>充滿機會</strong>的地方！不論這是投資還是投機，我都會想要用量化交易的角度參與，這可以說是我對於<strong>程式和科技的執著</strong>吧！</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="769" src="https://www.finlab.tw/wp-content/uploads/2020/08/pexels-pixabay-315788-1024x769.jpg" alt="pexels pixabay 315788" class="wp-image-2090" srcset="https://www.finlab.tw/wp-content/uploads/2020/08/pexels-pixabay-315788-1024x769.jpg 1024w, https://www.finlab.tw/wp-content/uploads/2020/08/pexels-pixabay-315788-300x225.jpg 300w, https://www.finlab.tw/wp-content/uploads/2020/08/pexels-pixabay-315788-768x577.jpg 768w, https://www.finlab.tw/wp-content/uploads/2020/08/pexels-pixabay-315788-1536x1153.jpg 1536w, https://www.finlab.tw/wp-content/uploads/2020/08/pexels-pixabay-315788-2048x1538.jpg 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：為什麼是比特幣？ (Part 1) 12"><figcaption>就在今年2020年，美國聯邦法院裁定：比特幣（BTC）是一種 “金錢”</figcaption></figure>



<p>研究<strong>加密貨幣</strong> 主要有以下的原因：</p>



<h3 id="1-隨著時間推移">時間推移 &#8211; 科技的進步很快</h3>



<p>你絕對沒辦法想像，30年前，大家對個人電腦嗤之以鼻：<br>「翻書1秒鐘，開機卻要3分鐘！」<br>「書 比 電腦 要方便太多了！」<br>「沒有理由大家需要電腦呀！」</p>



<p>今天，每個人口袋都有一台電腦：手機</p>



<p><strong>加密貨幣，會不會就是30年前的</strong>筆電，雖然大家現在不看好，但未來都在用？<br>可能會，可能不會。這些都不是我說了算，但有一些跡象：</p>



<p>就在今年2020年初，德國最大銀行“德意志銀行”，做了一份對於2030年的展望報告，報告中指出： 「十年後(2030年)，加密貨幣會成為主流」，報告從供需的角度出發，列出加密貨幣成為主流的三個條件，首先就是加密貨幣在政府的眼中，必須是合法的貨幣，這可以從最近美國聯邦法院的宣判中（裁定比特幣是一種“金錢”），和近期中國、印度兩大人口密度大國對於加密貨幣的態度轉變看見。再來就是價格的波動不能太大，因為要成為交易的工具，就需要具備一定的穩定性，讓使用者有保障。最後一個條件是需要科技巨頭們，對於現行科技的整合，這可以從近期Visa、MasterCard 都即將推出自己的加密貨幣相關服務看見趨勢。</p>



<p>雖然這一切都還只是預測，但我們還是可以將持有比特幣，當作是買保險，因為人類的歷史，充滿戰爭，很多人因此顛沛流離，這80年以來，是世界上最和平的一段日子，究竟是人類越來越文明？未來不會有任何戰爭，還是說世界的動盪 就像是經濟一樣會循環，我們剛好處在和平的週期？</p>



<p>設想一個最糟糕的狀況：房子被強制徵收、國家貨幣大幅貶值、臨時離開住所，輕裝逃往其他國家，要是這些事情都發生了，你可以什麼都沒有、什麼都不帶，<strong>只要有比特幣的公鑰私鑰(帳號密碼)，一切都能卷土重來</strong>！</p>



<p>這是個真實存在的例子，就在2018年，南美洲盛產石油的國家“委內瑞拉”，因為油價的崩盤，委內瑞拉政府選擇了印更多的鈔票來解決債務問題，而導致了通貨膨脹率單一年就來到了2,688,670%，委內瑞拉人民的解套方式就是換購比特幣，以比特幣做匯款、交易的媒介，或是只有在交易的當下瞬間用比特幣換當地的貨幣做買賣交易！</p>



<h3 id="3-比特幣的特性">3. 比特幣價值正反方分析</h3>



<h3>正方</h3>



<ol><li><strong>比特幣具有稀缺性</strong>，總發行量為2100萬枚，不同於傳統的法定貨幣，可以無限制的膨脹和發行，比特幣具有定量的限制，相較於法定貨幣，有隨著時間推移不斷升值的趨勢，由於這個特質，比特幣也被稱為「人造黃金」。</li><li><strong>可分割性</strong>，可以分為一億個中本聰單位，在交易過程中更加便利和靈活。</li><li><strong>可移植性</strong>，比特幣的產生和交易都是通過網路，為最高可移植性的貨幣。</li><li><strong>可代替性</strong>，就像一克純金始終等於另一克司純金一樣。無論發生什麽情況，一個比特幣仍然是與另一個比特幣可互換的價值象徵。</li><li><strong>耐用性</strong>。任何比特幣或中本聰都可以無數次重覆使用而不會降低性能。</li></ol>



<p>當然，不能一直說比特幣的優點，避而不談缺點，比特幣也受到很多挑戰，遭反方批評為缺乏價值的根據：</p>



<h3>反方</h3>



<ol><li>任何人都可以複製區塊鏈的程式碼，發起 ICO 募資，造成詐騙的氾濫，影響加密貨幣的價值。</li><li>目前大部分的國家並不採用加密貨幣作為法定貨幣，甚至不承認加密貨幣交易的合法性，所以貨幣安全得不到保障，詐騙頻傳。民眾質疑加密貨幣的價值。</li><li>波動大，除了穩定幣外，不適合拿來做日常生活用品之交易</li></ol>



<h3>綜合優缺點</h3>



<p>前五個優點是貨幣性質，而後三點挑戰，是屬於法律、管制的問題。隨著時間，前五點優勢不會改變，而後三個缺點會慢慢被克服。</p>



<p>另外，因為比特幣難監管，導致各國剛開始時非常排斥（但最近變成是愛恨交織就是了XD），加密貨幣存在的意義，就是要等時間來慢慢證明了。</p>



<h3 id="究竟時間要等多久？">所以綜合以上的結論</h3>



<p>在或近或遠的未來，比特幣應該存在著某種地位。所以我看好此產業的前景，但是也有看錯的可能！好在這個世界，不是非善即惡、非黑及白，不用全面的樂觀或悲觀，梭哈或戒慎恐懼。<br>　<br>而是要設計一套邏輯<br>假如對了，可以多賺一點<br>假如錯了，只好小虧一點<br>這就是交易！</p>



<p>要怎麼知道資金要投入多少呢？假如是 buy &amp; hold 的話，風險滿大的，簡單的方式：想像，你「單一天」可以承受最大虧損？差不多就投資這麼多吧！因為比特幣下跌個70％ 80％都是有發生過的！</p>



<p>假如是研究量化交易，有效控制風險的話，就可以將部位再提高一點，接下來就來建置 Python 交易系統，讓我們投資的風險可防可控！在<a href="https://www.finlab.tw/btc-crawler-py/" class="rank-math-link">下個單元中</a>，我們會教大家如何爬取比特幣的歷史價格，好讓我們實作投資加密貨幣的交易策略喔！歡迎追蹤我們的<a rel="noreferrer noopener" href="https://www.facebook.com/finlab.python/" target="_blank" class="rank-math-link">粉絲專頁</a>，來訂閱最新的教學分享喔！</p>



<p>如果喜歡我們的文章，也歡迎參考我們最新募資的線上課程「<a aria-label="用 Python 理財：打造加密貨幣實戰策略 (opens in a new tab)" rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank" class="rank-math-link">用 Python 理財：打造加密貨幣實戰策略</a>」，在線上課程中，我們會更有系統、更完整地教您如何從無到有，打造10種加密貨幣實戰策略，並且能夠自動化雲端交易！有興趣的話，可以<a aria-label="點此觀看課程介紹影片 (opens in a new tab)" rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank" class="rank-math-link">點此觀看課程介紹影片</a>喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/python-bitcoin-trading-why-bitcoin/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1014</post-id>	</item>
		<item>
		<title>用Python投資加密貨幣：爬蟲下載歷史數據 (Part 2)</title>
		<link>https://www.finlab.tw/btc-crawler-py/</link>
					<comments>https://www.finlab.tw/btc-crawler-py/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Mon, 20 Jul 2020 12:02:49 +0000</pubDate>
				<category><![CDATA[加密貨幣]]></category>
		<category><![CDATA[BTC]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[比特幣]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=1016</guid>

					<description><![CDATA[這個單元，分享如何用爬蟲獲取比特幣歷史價格，可以打開colab線上編輯python跟我們一起做實驗吧！colab 是 google 提供，線上運行 python 的平台，打開後，新增一個notebook直接一步步貼上下面的代碼，程式就會順利運行了！]]></description>
										<content:encoded><![CDATA[
<p>這個單元，我們分享如何用爬蟲獲取比特幣歷史價格！</p>



<p>可以打開<a rel="noreferrer noopener" href="https://colab.research.google.com/" target="_blank">colab</a>線上編輯python，跟著我們一起做實驗吧！<br>colab 是 google 提供，線上運行 python 的平台，打開後，新增一個notebook<br>直接一步步貼上下面的代碼，程式就會順利運行了！<a href="https://www.finlab.tw/btc-crawler-py/thumbnail.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="790" height="546" src="http://34.96.136.135/wp-content/uploads/2020/07/thumbnail-5-6.png" alt="thumbnail 5 6" class="wp-image-1018" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-5-6.png 790w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-5-6-300x207.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-5-6-768x531.png 768w" sizes="(max-width: 790px) 100vw, 790px" title="用Python投資加密貨幣：爬蟲下載歷史數據 (Part 2) 13"></figure></div>



<h3 id="獲取-python-函式庫">獲取 python 函式庫</h3>



<p>首先，我們要先獲取幫大家寫好的 package，可以到github上下載：</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">!git clone https://github.com/koreal6803/crypto_backtrader.git
%cd crypto_backtrader</code></pre>



<p>上面的指令，會先將預先寫好的程式從 github 上下載下來，並且將目錄切換到 crypto_backtrader，也就是下載下來的資料夾中。</p>



<h3 id="安裝一些必要的packages">安裝一些必要的packages</h3>



<p>接下來我們來安裝一些必要的 dependencies，這樣等會才能順利執行程式：</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash line-numbers">!pip install python-binance
!pip install bitmex
!pip install Backtesting
!pip install backtrader</code></pre>



<h3 id="加密貨幣命名方法">加密貨幣命名方法</h3>



<p>這篇文章中，我們爬取&nbsp;<code>BTCUSDT</code>&nbsp;的價格，<code>BTCUSDT</code>&nbsp;這個 symbol 可以拆逞兩個部分：一個是&nbsp;<code>BTC</code>，另一個是&nbsp;<code>USDT</code>。<code>BTCUSDT</code>&nbsp;代表：<code>BTC</code>&nbsp;的價格，以&nbsp;<code>USDT</code>&nbsp;為單位，這邊為什麼我們要用&nbsp;<code>USDT</code>&nbsp;呢？因為他是跟&nbsp;<code>USD</code>&nbsp;是美元是表兄弟，<code>USDT</code>&nbsp;是一種跟&nbsp;<code>USD</code>&nbsp;約略 1:1 兌換的穩定虛擬貨幣，<code>USDT</code>&nbsp;的好處是：</p>



<p>在交易時，假如用 加密貨幣 和 法定貨幣（美元）來回交易，這種方式交易，手續費會非常高昂，例如我們以 Maicoin 買入跟賣出手續費約高達 1%。</p>



<p>今天我們假如使用&nbsp;<code>BTCUSDT</code>&nbsp;pair 來交易，由於同樣是加密貨幣，所以手續費算是大幅的降低，目前手續費在各平台，一般的標準是0.1%，根據平台的優惠、交易量可以打折，成本算是低很多！</p>



<p><a href="http://blog.udn.com/mashmoro980727/121661372" rel="noreferrer noopener" target="_blank">交易對(trading pair)的相關介紹</a></p>



<p>那廢話不多說，趕快來下載歷史資料吧！</p>



<h3 id="使用幫大家寫好的函式庫">使用幫大家寫好的加密貨幣爬蟲函式庫</h3>



<p>我們可以使用：<br><code>from finlab import crypto</code><br>將一些好用的 function 給叫進來！</p>



<p>然後用：<br><code>crypto.get_all_binance</code>&nbsp;這個 function，<br>來獲取交易對(trading pair)。</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">from finlab import crypto
df = crypto.get_all_binance('BTCUSDT', '4h')
df.head()</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="288" src="http://34.96.136.135/wp-content/uploads/2020/07/df-3-1024x288.png" alt="df 3" class="wp-image-1019" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/df-3-1024x288.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/df-3-300x84.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/df-3-768x216.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/df-3-1536x432.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/df-3-2048x576.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：爬蟲下載歷史數據 (Part 2) 14"></figure></div>



<p><a href="https://www.finlab.tw/btc-crawler-py/df.png"></a>上述這個&nbsp;<code>get_all_binance</code>，除了幫你整理好下載資料外，還會將這些資料資料，存在&nbsp;<code>crypto_backtrader/history/crypto/</code>&nbsp;當中，以&nbsp;<code>csv</code>&nbsp;的方式存起來，方便你用&nbsp;<code>excel</code>、<code>multicharts</code>&nbsp;等程式來打開。</p>



<p>你也可以輸入不同的 trading pair 名稱，可以<a rel="noreferrer noopener" href="https://www.binance.com/tw/markets" target="_blank">binance官網</a>查找！</p>



<p>下一步，我們會分享：<br>怎麼用&nbsp;<a href="https://www.finlab.tw/btc-simple-sma-backtesting/">Python 回測一個簡單的交易策略</a>！</p>



<p>如果喜歡我們的文章，也歡迎參考我們最新募資的線上課程「<a rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank">用 Python 理財：打造加密貨幣實戰策略</a>」，在線上課程中，我們會更有系統、更完整地教您如何從無到有，打造10種加密貨幣實戰策略，並且能夠自動化雲端交易！有興趣的話，可以<a rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank">點此觀看課程介紹影片</a>喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/btc-crawler-py/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1016</post-id>	</item>
		<item>
		<title>用Python投資加密貨幣：交易策略訊號實做 (Part 3)</title>
		<link>https://www.finlab.tw/btc-trading-signal/</link>
					<comments>https://www.finlab.tw/btc-trading-signal/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Mon, 20 Jul 2020 12:02:49 +0000</pubDate>
				<category><![CDATA[加密貨幣]]></category>
		<category><![CDATA[BTC]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[比特幣]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=1021</guid>

					<description><![CDATA[這篇文章中，我們將用 pandas 來做一個簡易的加密貨幣交易訊號！Pandas 是一個資料處理用的 Package，專門用來做資料處理，你可以想像它是 python 裡面的 excel，可以產生並且處理各式各樣的表格！]]></description>
										<content:encoded><![CDATA[
<p>這篇文章中，我們將用 pandas 來做一個簡易的加密貨幣交易訊號！</p>



<p>Pandas 是一個資料處理用的 Package，專門用來做資料處理，你可以想像它是 python 裡面的 excel，可以產生並且處理各式各樣的表格！</p>



<h3 id="Pandas-操作介紹">Pandas 操作介紹</h3>



<p>承接著<a href="https://www.finlab.tw/btc-crawler-py/">上一篇文章</a>，我們繼續在&nbsp;<a rel="noreferrer noopener" href="https://colab.research.google.com/" target="_blank">google colab</a>&nbsp;上進行程式的實驗此時的&nbsp;<code>df</code>&nbsp;已經是歷史資料：<a href="https://www.finlab.tw/btc-trading-signal/df.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="276" src="http://34.96.136.135/wp-content/uploads/2020/07/df-1-1-1024x276.png" alt="df 1 1" class="wp-image-1022" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/df-1-1-1024x276.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/df-1-1-300x81.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/df-1-1-768x207.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/df-1-1-1536x414.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/df-1-1.png 1936w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：交易策略訊號實做 (Part 3) 15"></figure></div>



<p>就是一個&nbsp;<code>pandas.DataFrame</code>&nbsp;物件，這個物件就像是 excel 表格一樣，有很多的行跟列，每一個列都可以簡單的呼叫出來。以我們的例子，每一列都是一個時間序列：</p>



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



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="174" src="http://34.96.136.135/wp-content/uploads/2020/07/series-1-1024x174.png" alt="series 1" class="wp-image-1023" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/series-1-1024x174.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/series-1-300x51.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/series-1-768x130.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/series-1-1536x261.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/series-1-2048x348.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：交易策略訊號實做 (Part 3) 16"></figure></div>



<p><a href="https://www.finlab.tw/btc-trading-signal/series.png"></a>由上圖可知，每一列也是一種物件，叫做&nbsp;<code>pd.Series</code>，這種物件，就是一條序列，可以想像是excel的單一一列的意思。</p>



<h3 id="製作簡易的均線策略">製作簡易的加密貨幣均線策略</h3>



<p><code>pd.Series</code>有很多特別的功能，例如計算移動窗格，我們可以用：<br><code>pd.Series.rolling()</code><br>來產生移動窗格，並且用：<br><code>pd.Series.rolling().mean()</code><br>來產生這個移動窗格的平均數，從時間序列的角度，這個就是「均線」！</p>



<pre class="wp-block-code"><code class="">sma1 = df.Close.rolling(20).mean()
sma2 = df.Close.rolling(60).mean()

df.Close.plot()
sma1.plot()
sma2.plot()</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="425" src="http://34.96.136.135/wp-content/uploads/2020/07/sma_plot-1024x425.png" alt="sma plot" class="wp-image-1025" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/sma_plot-1024x425.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/sma_plot-300x125.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/sma_plot-768x319.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/sma_plot-1536x638.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/sma_plot.png 1984w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：交易策略訊號實做 (Part 3) 17"></figure></div>



<p><a href="https://www.finlab.tw/btc-trading-signal/sma_plot.png"></a></p>



<p>上圖中，我們將<code>BTCUSDT</code>的歷史紀錄 與兩條均線畫出來，會發現，時間跨度太大，導致價格跟均線看不清楚，我們可以額外 zoom in 選取「某年」來觀察，可以使用中括號來選取時間範圍：</p>



<pre class="wp-block-code"><code class="">df.Close['2020'].plot()
sma1['2020'].plot()
sma2['2020'].plot()</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="397" src="http://34.96.136.135/wp-content/uploads/2020/07/sma_plot2019-1024x397.png" alt="sma plot2019" class="wp-image-1026" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/sma_plot2019-1024x397.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/sma_plot2019-300x116.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/sma_plot2019-768x297.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/sma_plot2019-1536x595.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/sma_plot2019.png 1988w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：交易策略訊號實做 (Part 3) 18"></figure></div>



<p><a href="https://www.finlab.tw/btc-trading-signal/sma_plot2019.png"></a>接下來，我們來設計交易訊號，我們希望做一個簡單的均線策略：</p>



<p>假如短週期均線&nbsp;<code>sma1</code>&nbsp;超過 長週期&nbsp;<code>sma2</code>&nbsp;-&gt; 做多，反之做空。</p>



<p>要怎麼做出這樣的訊號呢？我們可以用不等式來進行！</p>



<h3 id="不等式條件">不等式條件</h3>



<p>不等式，就是所謂的「大於等於小於」，我們假如將兩條時間序列做不等式運算，在這兩條時間序列中，每一個元素會被一一拿出來比對，並且產生出新的「布林」時間序列：</p>



<pre class="wp-block-code"><code class="">condition = sma1 > sma2
condition</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="256" src="http://34.96.136.135/wp-content/uploads/2020/07/condition-1024x256.png" alt="condition" class="wp-image-1027" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/condition-1024x256.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/condition-300x75.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/condition-768x192.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/condition-1536x384.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/condition.png 1986w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：交易策略訊號實做 (Part 3) 19"></figure></div>



<p><a href="https://www.finlab.tw/btc-trading-signal/condition.png"></a>上圖中就是布林時間序列，每個時間點對映到「Ture」或是「False」，假如今天條件成立，也就是「sma1 &gt; sma2」的話，該時間點對映到的就會是 True，反之則是 False。</p>



<p>因為我們是均線突破策略，要怎麼結合不等式，來產生均線突破條件呢？我們還需要：<code>pd.Series.shift</code>，這個功能。</p>



<h3 id="調用「昨天」的價格-pd-Series-shift">調用「昨天」的價格 pd.Series.shift</h3>



<p><code>pd.Series.shift</code>是一個好用的function，可以將時間序列全部都往後延遲一天，例如以下的例子：</p>



<pre class="wp-block-code"><code class="">print(df.Close)
print(df.Close.shift(1))</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="278" src="http://34.96.136.135/wp-content/uploads/2020/07/shift-1024x278.png" alt="shift" class="wp-image-1028" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/shift-1024x278.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/shift-300x81.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/shift-768x208.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/shift-1536x417.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/shift.png 2004w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：交易策略訊號實做 (Part 3) 20"></figure></div>



<p><a href="https://www.finlab.tw/btc-trading-signal/shift.png"></a>你會發現兩者相差一天，所以在做策略時，我會傾向於，將<code>pd.Series.shift(n)</code>，當作是「n個時間單位前的價格」，這邊我們用的是 ‘4h’ 4小時的歷史價格，所以<code>pd.Series.shift(1)</code>，就是4小時前，而<code>pd.Series.shift(2)</code>，就是8小時前，以此類推。</p>



<p>假如我們只使用：<code>pd.Series.shift()</code>，n 不設定參數的話，pandas 會預設&nbsp;<code>n=1</code>&nbsp;喔！</p>



<h3 id="結合上述的範例，產生策略訊號">結合上述的範例，產生策略訊號</h3>



<p>我們希望的做出來的邏輯：<br>做多: 當(今天短週期均線 &gt; 今天長週期均線) 且 (昨天短週期均線 &lt; 昨天長週期均線)<br>做空: 當(今天短週期均線 &lt; 今天長週期均線) 且 (昨天短週期均線 &gt; 昨天長週期均線)</p>



<p>我們可以將上述中文，對映到以下的程式碼：</p>



<pre class="wp-block-code"><code class="">signal_long = (sma1 > sma2) &amp; (sma1.shift() &lt; sma2.shift())
signal_short = (sma1 &lt; sma2) &amp; (sma1.shift() > sma2.shift())</code></pre>



<p>上述程式碼中的&nbsp;<code>&amp;</code>&nbsp;就是「且」的意思。</p>



<p>我們可以將訊號繪製出來：</p>



<pre class="wp-block-code"><code class="">signal_long.astype(int).plot()
(-signal_short.astype(int)).plot()</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/signal-1024x396.png" alt="signal" class="wp-image-1029" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/signal-1024x396.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/signal-300x116.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/signal-768x297.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/signal-1536x594.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/signal.png 1992w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：交易策略訊號實做 (Part 3) 21"></figure></div>



<p><a href="https://www.finlab.tw/btc-trading-signal/signal.png"></a></p>



<p>以上這張圖我用 -1 顯示：賣出訊號，而 1 是買進訊號！當我們將 True False 轉換成 int 時，會轉換成「1」跟「0」的數值。</p>



<h3 id="製作策略">製作策略</h3>



<p>然而我們怎麼知道，照著這個交易訊號操作，實際的績效是怎麼樣呢？<a href="https://www.finlab.tw/btc-simple-sma-backtesting/">下一個單元中：回測</a>，會教大家怎麼用&nbsp;<a rel="noreferrer noopener" href="https://github.com/kernc/backtesting.py" target="_blank">backtesting</a>&nbsp;這個 package，來實做回測，模擬這個策略的績效，敬請期待！</p>



<p>如果喜歡我們的文章，也歡迎參考我們最新募資的線上課程「<a rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank">用 Python 理財：打造加密貨幣實戰策略</a>」，在線上課程中，我們會更有系統、更完整地教您如何從無到有，打造10種加密貨幣實戰策略，並且能夠自動化雲端交易！有興趣的話，可以<a rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank">點此觀看課程介紹影片</a>喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/btc-trading-signal/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1021</post-id>	</item>
		<item>
		<title>用Python投資加密貨幣：實做回測策略 (Part 4)</title>
		<link>https://www.finlab.tw/btc-simple-sma-backtesting/</link>
					<comments>https://www.finlab.tw/btc-simple-sma-backtesting/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Mon, 20 Jul 2020 12:02:48 +0000</pubDate>
				<category><![CDATA[加密貨幣]]></category>
		<category><![CDATA[BTC]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[比特幣]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=1031</guid>

					<description><![CDATA[接下來我們廢話不多說，結合前一篇的買賣訊號，來建構一個加密貨幣的策略吧！這篇文章，將接續著之前的單元，假如還沒看過前面的部分，可以參考以下的連結喔！]]></description>
										<content:encoded><![CDATA[
<p>接下來我們廢話不多說，結合前一篇的買賣訊號，來建構一個加密貨幣的策略吧！<a href="https://www.finlab.tw/btc-simple-sma-backtesting/thumbnail.jpeg"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="729" src="http://34.96.136.135/wp-content/uploads/2020/07/thumbnail-1-4-1024x729.jpeg" alt="thumbnail 1 4" class="wp-image-1032" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-1-4-1024x729.jpeg 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-1-4-300x214.jpeg 300w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-1-4-768x547.jpeg 768w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-1-4-1536x1094.jpeg 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-1-4.jpeg 1602w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：實做回測策略 (Part 4) 22"></figure></div>



<h3 id="複習前幾篇的知識">複習前幾篇用Python投資加密貨幣相關的知識</h3>



<p>這篇文章，將接續著之前的單元，假如還沒看過前面的部分，可以參考以下的連結喔！</p>



<ol><li><a href="https://www.finlab.tw/python-bitcoin-trading-why-bitcoin/">為什麼要投資加密貨幣</a></li><li><a href="https://www.finlab.tw/btc-crawler-py/">加密貨幣爬蟲</a></li><li><a href="https://www.finlab.tw/btc-trading-signal/">策略訊號建立</a></li></ol>



<p>這篇我寫的比較仔細一點，所以文章稍長，但程式碼很短，先給大家聞香一下</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="702" src="http://34.96.136.135/wp-content/uploads/2020/07/result-1-2-1024x702.png" alt="result 1 2" class="wp-image-1034" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/result-1-2-1024x702.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/result-1-2-300x206.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/result-1-2-768x527.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/result-1-2-1536x1053.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/result-1-2.png 2036w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：實做回測策略 (Part 4) 23"></figure></div>



<p><a href="https://www.finlab.tw/btc-simple-sma-backtesting/result.png"></a><br>想知道怎麼做出來，要看到最後喔！</p>



<p>將上一篇的程式碼統整，我們可以得到：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">signal_long = (sma1 > sma2) &amp; (sma1.shift() &lt; sma2.shift())
signal_short = (sma1 &lt; sma2) &amp; (sma1.shift() > sma2.shift())</code></pre>



<p>接下來，我們將&nbsp;<code>signal_long</code>&nbsp;跟&nbsp;<code>signal_short</code>&nbsp;整合在一起，這邊的&nbsp;<code>signal_long</code>&nbsp;跟&nbsp;<code>signal_short</code>，是進場訊號，一個做多、一個是做空時間序列，當訊號為 True 時代表入場。</p>



<p><strong>多空訊號結合</strong></p>



<p>接下來為了配合 backtesting 函式庫，我們想將&nbsp;<code>signal_long</code>&nbsp;跟&nbsp;<code>signal_short</code>&nbsp;合併起來，產生一個翻轉策略：<br>當&nbsp;<code>signal_long</code>&nbsp;為 True 時，不論目前有什麼部位，都翻多<br>當&nbsp;<code>signal_short</code>&nbsp;為 True 時，不論目前什麼部位，一律翻空<br>我們想要做出一個新的訊號 叫做&nbsp;<code>signal</code>，其做多訊號為 1，做空訊號為 -1 ，維持不變則為0。</p>



<p>可以用以下的寫法，首先copy&nbsp;<code>signal_long</code>&nbsp;序列，並且將&nbsp;<code>signal_short</code>&nbsp;為 True 的部分改成&nbsp;<code>-1</code>，這樣就可以了！</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers"># combine long and short signal
signal = signal_long.copy()
signal[signal_short] = -1</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="345" src="http://34.96.136.135/wp-content/uploads/2020/07/signal-1-1-1024x345.png" alt="signal 1 1" class="wp-image-1036" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/signal-1-1-1024x345.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/signal-1-1-300x101.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/signal-1-1-768x259.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/signal-1-1-1536x518.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/signal-1-1-2048x691.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：實做回測策略 (Part 4) 24"></figure></div>



<p><a href="https://www.finlab.tw/btc-simple-sma-backtesting/signal.png"></a></p>



<p>完整總和來說，我們目前已經有以下的程式碼：</p>



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

# geth the historical price
df = crypto.get_all_binance('BTCUSDT', '4h')

# calculate moving averages
sma1 = df.Close.rolling(20).mean()
sma2 = df.Close.rolling(60).mean()

# create long and short signal
signal_long = (sma1 > sma2) &amp; (sma1.shift() &lt; sma2.shift())
signal_short = (sma1 &lt; sma2) &amp; (sma1.shift() > sma2.shift())

# combine long and short signal
signal = signal_long.copy()
signal[signal_short] = -1</code></pre>



<p>接下來我們直接比對一下，回測的程式碼，橘色部分比較特別，會逐一介紹。</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="906" src="http://34.96.136.135/wp-content/uploads/2020/07/code-1-1024x906.png" alt="code 1" class="wp-image-1038" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/code-1-1024x906.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/code-1-300x265.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/code-1-768x679.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/code-1-1536x1359.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/code-1.png 1800w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：實做回測策略 (Part 4) 25"></figure></div>



<p><a href="https://www.finlab.tw/btc-simple-sma-backtesting/code.png"></a><br>(先不急著抄寫，文末會附上完整代碼)</p>



<p>首先，上圖中第一二行，我們將 Backtest 和 SignalStrategy 匯入，Backtest 是一個幫我們回測的 interface，而&nbsp;<code>SignalStrategy</code>&nbsp;是一個 class，我們可以繼承&nbsp;<code>SignalStrategy</code>&nbsp;(第5行)，就能把剛剛的訊號&nbsp;<code>signal</code>&nbsp;匯入來回測，這邊會用到物件導向的概念，可以參考：<br><a rel="noreferrer noopener" href="https://www.w3schools.com/python/python_classes.asp" target="_blank">w3c提供的簡單 python 物件導向教學</a></p>



<p>有了一個strategy空殼，接下來就可以實做內部功能了！</p>



<p>第7行中，我們覆寫一個parent 方法，叫做&nbsp;<code>init</code>，在&nbsp;<code>init</code>&nbsp;這個方法中，我們可以計算回測要用的訊號，這個方法會在<strong>回測開始前執行一次</strong>，所以當我們先把訊號計算好，這樣回測的時候就不用計算，速度上會比較快！</p>



<p><code>init</code>中大部分的程式碼，跟我們開頭所述的非常雷同，有幾點不一樣而已：</p>



<p>首先，在第8行中，parent class 會先執行他的&nbsp;<code>init</code>，你可以想像，父母先吃飯，小孩再吃飯的道理！</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">super().init()</code></pre>



<p>然後，第11行，也做了一點修正，從原本的：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers"># 原本的
df = crypto.get_all_binance('BTCUSDT', '4h')</code></pre>



<p>變成：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers"># 新的
close = pd.Series(self.data.Close)</code></pre>



<p>我們可以用&nbsp;<code>self.data.Close</code>&nbsp;，來獲取「開高低收」的歷史價格，這是繼承&nbsp;<code>SignalStrategy</code>&nbsp;附加的功能，可以讓程式碼中的「策略」跟「價格」解耦，讓策略不只交易&nbsp;<code>BTCUSDT</code>，還能交易其他加密貨幣，甚至是股票！</p>



<p>最後12～21行，都跟之前一樣，所以就略過囉！</p>



<p>最後的24行，就是將我們產生的&nbsp;<code>signal</code>&nbsp;給匯入：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">elf.set_signal(signal)</code></pre>



<p>這樣子&nbsp;<code>SignalStrategy</code>&nbsp;裡面就會根據&nbsp;<code>signal</code>，來進行翻多翻空的交易囉！</p>



<p>上述 1～26 行，都是一個策略藍圖，我們只是規劃，並沒有真正執行這些程式碼，所以我們還要額外家三行，建構出規劃好的策略，並且回測、統計回測結果：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">bt = Backtest(df, Strategy)
bt.run()
bt.plot()</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="702" src="http://34.96.136.135/wp-content/uploads/2020/07/result-2-2-1024x702.png" alt="result 2 2" class="wp-image-1040" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/result-2-2-1024x702.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/result-2-2-300x206.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/result-2-2-768x527.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/result-2-2-1536x1053.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/result-2-2.png 2036w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：實做回測策略 (Part 4) 26"></figure></div>



<p><a href="https://www.finlab.tw/btc-simple-sma-backtesting/result.png"></a></p>



<p>執行後會顯示出非常詳細的買賣點，這個就是所謂&nbsp;<del>窮人版</del>&nbsp;python 版的 multicharts 了吧！不過看起來策略的&nbsp;<code>performnace</code>&nbsp;不太好，賺不到什麼 $$，所以下一個單元，我們就來使用內建的 optimize 方法，找尋最優的均線交叉策略！優化後的績效，先給大家聞香一下！<a href="https://www.finlab.tw/btc-simple-sma-backtesting/opt.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="129" src="http://34.96.136.135/wp-content/uploads/2020/07/opt-1024x129.png" alt="opt" class="wp-image-1041" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/opt-1024x129.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/opt-300x38.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/opt-768x97.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/opt-1536x193.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/opt.png 1858w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：實做回測策略 (Part 4) 27"></figure></div>



<p><a href="https://www.finlab.tw/btc-backtesting-optimization/">點我進入下一個單元：策略優化</a></p>



<p>以下是完整的程式碼：<br>另外也可以參考完整的&nbsp;<a href="https://colab.research.google.com/drive/1ZUst2gJfBSxrdhw2aBdr_OJn6uMdDabi" rel="noreferrer noopener" target="_blank">colab notebook 範例</a></p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">from finlab import crypto
from backtesting import Backtest
from backtesting.lib import SignalStrategy
import pandas as pd

df = crypto.get_all_binance('BTCUSDT', '4h')

class Strategy(SignalStrategy):
    
    def init(self):
        super().init()
        
        # Precompute the two moving averages
        close = pd.Series(self.data.Close)
        sma1 = close.rolling(20).mean()
        sma2 = close.rolling(60).mean()
        
        # Precompute signal
        signal_long = (sma1 > sma2) &amp; (sma1.shift() &lt; sma2.shift())
        signal_short = (sma1 &lt; sma2) &amp; (sma1.shift() > sma2.shift())
        
        signal = signal_long
        signal[signal_short] = -1
        
        self.set_signal(signal)
        
        
    def next(self):
        super().next()

bt = Backtest(df, Strategy)
bt.run()
bt.plot()</code></pre>



<p>如果喜歡我們的文章，也歡迎參考我們最新募資的線上課程「<a rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank">用 Python 理財：打造加密貨幣實戰策略</a>」，在線上課程中，我們會更有系統、更完整地教您如何從無到有，打造10種加密貨幣實戰策略，並且能夠自動化雲端交易！有興趣的話，可以<a rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank">點此觀看課程介紹影片</a>喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/btc-simple-sma-backtesting/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1031</post-id>	</item>
		<item>
		<title>用Python投資加密貨幣：比特幣操作最強指標(原理篇) (Part 5)</title>
		<link>https://www.finlab.tw/best-indicator-bitcoin/</link>
					<comments>https://www.finlab.tw/best-indicator-bitcoin/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Mon, 20 Jul 2020 12:02:48 +0000</pubDate>
				<category><![CDATA[加密貨幣]]></category>
		<category><![CDATA[BTC]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[比特幣]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=1043</guid>

					<description><![CDATA[這是臨時加開的一篇文章，主要是因為就在今天，有個非常準的比特幣上漲指標“Hash Ribbons 指標”，發生了罕見的重磅訊號！近三年，只要這個最強指標產生買入訊號，平均來說，比特幣上漲幅度為 5000％，這個指標的原理是什麼呢？]]></description>
										<content:encoded><![CDATA[
<p>這是臨時加開的一篇文章，主要是因為，<strong>就在今天</strong>，有個非常準的比特幣上漲指標，發生了罕見的重磅訊號！<a href="https://www.finlab.tw/best-indicator-bitcoin/thumbnail.jpeg"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="683" src="http://34.96.136.135/wp-content/uploads/2020/07/thumbnail-2-2-1024x683.jpeg" alt="thumbnail 2 2" class="wp-image-1044" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-2-2-1024x683.jpeg 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-2-2-300x200.jpeg 300w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-2-2-768x512.jpeg 768w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-2-2-1536x1024.jpeg 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-2-2.jpeg 1950w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：比特幣操作最強指標(原理篇) (Part 5) 28"></figure></div>



<p>近三年，只要這個最強指標產生買入訊號，平均來說，<strong>比特幣上漲幅度為 5000％</strong>！</p>



<h2>比特幣最強指摽：<strong>Hash Ribbons 指標</strong></h2>



<p>這個指標的原理是什麼呢？首先我們要介紹幾個名詞：</p>



<h3 id="1-Miner-挖礦機">1. Miner 挖礦機</h3>



<p>比特幣的運作機制，是讓所有的電腦互相競爭，看誰最快產生一串隨機字串 s，使得以下公式：<br><code>hash = sha256(phash + leger + s)</code><br>中 hash 的開頭「 n 個 0 」，其中&nbsp;<code>phash</code>&nbsp;就是前一個 block（區塊）的 hash，<code>leger</code>&nbsp;是待驗證的 BTC 交易帳本，<code>sha256</code>&nbsp;是一個<strong>不可逆的加密函數</strong>。</p>



<p>不可逆函數意味著，我們不可能反推s是多少，而是必需要用暴力法，硬猜 s 是多少，一個個嘗試，直到成功為止，專門在嘗試暴力法枚舉的電腦，我們就稱為「挖礦機」！</p>



<h3 id="2-為何要找-s-？-感覺很沒意義">2. 為何要找 s ？ 感覺很沒意義</h3>



<p>因為這樣子，我們就可以驗證此帳本是真的，這種驗證機智叫做&nbsp;<strong>proof-of-work</strong>，也就是用電腦的勞力，來確保紀錄的資料不受串改。</p>



<p>舉個例子，假如今天某駭客想上傳一個假的block，這個時候，他必須先解出上述&nbsp;<code>s</code>&nbsp;是多少，還必須將下一個block的&nbsp;<code>s</code>&nbsp;也算出來，和下下個 block 的&nbsp;<code>s</code>，和下下下個 block 的&nbsp;<code>s</code>…等，直到其他電腦承認他的那條「假區塊鏈」為止。</p>



<p>也就是這個駭客的電腦算力，必須跟其他正規礦機的算力總和披敵，並且持續非常長的一段時間都能戰勝<strong>正規礦機的總和</strong>，才有辦法將假的block驗證成功。</p>



<h3 id="3-Miner-Capitulation-礦機的投降">3. Miner Capitulation 礦機的投降</h3>



<p>為什麼會有人想挖礦？因為辛苦挖礦，可以獲得新發行的比特幣！</p>



<p>但當今天比特幣價格下降，導致挖礦獲利減少時，礦工挖礦成本 大於 挖到的比特幣價值，有些礦工乾脆就不運轉，或是賣掉BTC去添購新的挖礦機型，也就是 Miner Capitulation。</p>



<h3 id="4-Miner-Capitulation-是好的買入機會">4. Miner Capitulation 是好的買入機會</h3>



<p>Miner Capitulation，通常發生在 BTC 價格下跌時，BTC 的價格跌破了挖礦成本開始，很多的礦機持有者，在這個時候：</p>



<ol><li>賣掉已經挖到的 BTC 來購買新的礦機</li><li>乾脆機器收一收，BTC賣一賣了結出場</li></ol>



<p>就會引發一系列超賣！</p>



<h3 id="5-如何判斷-Miner-Capitulation？">5. 如何判斷 Miner Capitulation？</h3>



<p>我們可以從BTC調整「挖礦的困難程度」，來當成 Miner Capitulation 的延遲指標，因為這個「挖礦難易程度」會動態調整的：</p>



<p>根據<a href="https://bitcoin.org/bitcoin.pdf" class="rank-math-link" target="_blank" rel="noopener">比特幣白皮書</a>，一個 block 的出產時間，必須在約10分鐘左右。</p>



<p>所以當礦機很多時，算力上升，這樣用暴力法找&nbsp;<code>s</code>&nbsp;的速度就會變快，所以找&nbsp;<code>s</code>&nbsp;難度也必須提升才行。</p>



<p>還記得 hash 開頭必須包含 n 個 0 嗎？這個 n 就可以用來控制難度，當 n 越大，代表要產生越多開頭為 0 的 hash，而難度也會跟著加大！</p>



<h3 id="6-我們可以藉由-n-來推算-hash-rate">6. 我們可以藉由 n 來推算 hash rate</h3>



<p>hash rate 就是比特幣網路的算力，每秒可以暴力解 x 次，這個 hash rate 降低，也代表著礦工的退出，礦工退出，就會將 BTC 兌現，BTC 就會有比較大的跌幅。</p>



<p>而當 hash rate 反轉升高時，就代表礦機更新完畢、礦場被整併，新礦機上線，近三年，這樣子的狀況，比特幣都有不錯的報酬，如今這個訊號也發生了，就不知道接下來歷史會不會重演呢？</p>



<p><a href="https://www.finlab.tw/btc-tradingview-intro/" class="rank-math-link">下一集</a>將分享怎麼用 trading view 來開啟hash rate 訊號買賣點！</p>



<p>如果喜歡我們的文章，也歡迎參考我們最新募資的線上課程「<a rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank">用 Python 理財：打造加密貨幣實戰策略</a>」，在線上課程中，我們會更有系統、更完整地教您如何從無到有，打造10種加密貨幣實戰策略，並且能夠自動化雲端交易！有興趣的話，可以<a rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank">點此觀看課程介紹影片</a>喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/best-indicator-bitcoin/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1043</post-id>	</item>
		<item>
		<title>用Python投資加密貨幣：比特幣操作最強指標(看盤篇) (Part 6)</title>
		<link>https://www.finlab.tw/btc-tradingview-intro/</link>
					<comments>https://www.finlab.tw/btc-tradingview-intro/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Mon, 20 Jul 2020 12:02:48 +0000</pubDate>
				<category><![CDATA[加密貨幣]]></category>
		<category><![CDATA[BTC]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[比特幣]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=1046</guid>

					<description><![CDATA[我們當然可以用 Python 來幫我們做分析
但是人都是懶惰的，假如有好用的看盤工具，即使不是 Python 也沒關係！這篇文章接續前一篇，將來一探究竟，究竟這個最強指標怎麼看！]]></description>
										<content:encoded><![CDATA[
<p>我們當然可以用 Python 來幫我們做分析，但是人都是懶惰的，假如有好用的看盤工具，即使不是 Python 也沒關係！</p>



<p>這篇文章接續前一篇，將來一探究竟，究竟這個最強指標怎麼看！<a href="https://www.finlab.tw/btc-tradingview-intro/ind.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="485" src="http://34.96.136.135/wp-content/uploads/2020/07/ind-1-1024x485.png" alt="ind 1" class="wp-image-1048" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/ind-1-1024x485.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/ind-1-300x142.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/ind-1-768x364.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/ind-1-1536x728.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/ind-1-2048x970.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：比特幣操作最強指標(看盤篇) (Part 6) 29"></figure></div>



<h3 id="TradingView">TradingView</h3>



<p>介紹一款我覺得很好用的平台，<a rel="noreferrer noopener" href="https://tw.tradingview.com/" target="_blank">TradingView</a>，這並不是業配，只是真的滿好用的<br>以加密貨幣來說，我都會用它來看盤，可以在商品代碼中，輸入「BTCUSDT」來搜尋比特幣的價格！</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/search-1-1024x403.png" alt="search 1" class="wp-image-1050" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/search-1-1024x403.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/search-1-300x118.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/search-1-768x302.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/search-1-1536x604.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/search-1-2048x806.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：比特幣操作最強指標(看盤篇) (Part 6) 30"></figure></div>



<p>並且按一下全功能圖表：<br><a href="https://www.finlab.tw/btc-tradingview-intro/panel.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="347" src="http://34.96.136.135/wp-content/uploads/2020/07/panel-1024x347.png" alt="panel" class="wp-image-1051" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/panel-1024x347.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/panel-300x102.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/panel-768x260.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/panel-1536x520.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/panel.png 2032w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：比特幣操作最強指標(看盤篇) (Part 6) 31"></figure></div>



<p>這時候就會跳出這檔商品的技術分析圖表，然後我們再上方功能列表，可以點選「fx」來添加技術指標：</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="940" height="68" src="http://34.96.136.135/wp-content/uploads/2020/07/bar.png" alt="bar" class="wp-image-1052" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/bar.png 940w, https://www.finlab.tw/wp-content/uploads/2020/07/bar-300x22.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/bar-768x56.png 768w" sizes="(max-width: 940px) 100vw, 940px" title="用Python投資加密貨幣：比特幣操作最強指標(看盤篇) (Part 6) 32"></figure></div>



<p><a href="https://www.finlab.tw/btc-tradingview-intro/bar.png"></a><br>這些是別人已經寫好，並且開源的技術指標，可以直接拿來用！</p>



<h3>非常推薦的比特幣指標</h3>



<p>#&nbsp;<strong>Hash Ribbons 指標</strong></p>



<p>接下來，搜尋並點選「Hash Ribbon」就可以看到這個指標了！<br>你應該會看到以下的圖表：<br><a href="https://www.finlab.tw/btc-tradingview-intro/ind.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="485" src="http://34.96.136.135/wp-content/uploads/2020/07/ind-1-2-1024x485.png" alt="ind 1 2" class="wp-image-1054" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/ind-1-2-1024x485.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/ind-1-2-300x142.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/ind-1-2-768x364.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/ind-1-2-1536x728.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/ind-1-2-2048x970.png 2048w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：比特幣操作最強指標(看盤篇) (Part 6) 33"></figure></div>



<p>可以看到「Hash Ribbon」這張圖表中，綠色像是階梯狀的數值，就是「Hash rate」，也就是「所有的挖礦機」的算力總和，也就是每秒可以暴力解多少次，可以參考<a href="https://www.finlab.tw/btc-tradingview-intro/">之前的文章</a>，瞭解更多原理的部分。</p>



<p>另外有兩條均線，分別是淺綠色跟灰色，分別是30日和60日均線，這些數字我們不用調整，用它預設的即可。</p>



<p>另外有紅色的區域，從均線的死亡交叉開始出現，代表 Miner Capitulation 發生的時刻，此時比特幣會進入超跌的狀態。最後當紅色區域的末稍，也就是均線黃金交叉時，代表礦工恢復運作，通常在這個時候買入，近三年的平均來說，會有約5000％的報酬！</p>



<p>當然歷史不代表未來，不論部落格提供怎麼樣的訊息，你還是得自己做決定！比特幣波動是非常大的，起床發現突然下跌 30％都是可能的。以長期投資而言，注重風險的讀者，真的不能下注太大呀！</p>



<p>看完了主觀交易的部分，讓我們回到正題，<a href="https://www.finlab.tw/btc-backtesting-optimization/">來做量化投資吧！</a></p>



<p>注：<br>另外假如要看 BTC 的長期價格，可以用 tradingview 搜尋 「BLX」，就可以找到了！</p>



<p>如果喜歡我們的文章，也歡迎參考我們最新募資的線上課程「<a rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank">用 Python 理財：打造加密貨幣實戰策略</a>」，在線上課程中，我們會更有系統、更完整地教您如何從無到有，打造10種加密貨幣實戰策略，並且能夠自動化雲端交易！有興趣的話，可以<a rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank">點此觀看課程介紹影片</a>喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/btc-tradingview-intro/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1046</post-id>	</item>
		<item>
		<title>用Python投資加密貨幣：三年20倍的策略參數最佳化 (Part 7)</title>
		<link>https://www.finlab.tw/btc-backtesting-optimization/</link>
					<comments>https://www.finlab.tw/btc-backtesting-optimization/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Mon, 20 Jul 2020 12:02:48 +0000</pubDate>
				<category><![CDATA[加密貨幣]]></category>
		<category><![CDATA[BTC]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[比特幣]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=1056</guid>

					<description><![CDATA[這篇文章中，我們將承接著之前的單元，來教大家怎麼做策略參數最佳化，我們將上次的回測程式改成以下的樣子，請大家來比較一下有什麼不同！]]></description>
										<content:encoded><![CDATA[
<p>這篇文章中，我們將承接著之前的單元，來教大家怎麼做策略參數最佳化！<a href="https://www.finlab.tw/btc-backtesting-optimization/thumbnail.jpeg"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="683" src="http://34.96.136.135/wp-content/uploads/2020/07/thumbnail-3-2-1024x683.jpeg" alt="thumbnail 3 2" class="wp-image-1057" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-3-2-1024x683.jpeg 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-3-2-300x200.jpeg 300w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-3-2-768x512.jpeg 768w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-3-2-1536x1024.jpeg 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-3-2.jpeg 1950w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：三年20倍的策略參數最佳化 (Part 7) 34"></figure></div>



<p>必備的單元提要：</p>



<ol><li>環境設定：<a href="https://www.finlab.tw/btc-crawler-py/">使用 colab 並且安裝相關 packages</a></li><li>簡單回測：<a href="https://www.finlab.tw/btc-simple-sma-backtesting/">利用均線相交產生買賣訊號回測</a></li></ol>



<p>要執行完上述兩個單元的程式碼，才能繼續接下來的單元喔！</p>



<p>我們將上次的回測程式改成以下的樣子，請大家來比較一下有什麼不同：</p>



<pre class="wp-block-code"><code lang="python" class="language-python">from backtesting import Backtest
from backtesting.lib import SignalStrategy
import pandas as pd

class Strategy(SignalStrategy):
    
    n1 = 20
    n2 = 60
    
    def init(self):
        super().init()
        
        # Precompute the two moving averages
        close = pd.Series(self.data.Close)
        sma1 = close.rolling(self.n1).mean()
        sma2 = close.rolling(self.n2).mean()
        
        # Precompute signal
        signal_long = (sma1 > sma2) &amp; (sma1.shift() &lt; sma2.shift())
        signal_short = (sma1 &lt; sma2) &amp; (sma1.shift() > sma2.shift())
        
        # combine signal
        signal = signal_long
        signal[signal_short] = -1
        
        # add signal
        self.set_signal(signal)

bt = Backtest(df, Strategy)
result1 = bt.run()
bt.plot()</code></pre>



<p>沒錯，我們新增了7、8行的物件參數，分別代表兩條均線的參數，並且在15、16行，製作均線時，使用該參數來製作均線。</p>



<p>另外我們也在倒數第二行，將回測結果存到&nbsp;<code>result1</code>，等等可以做比較。</p>



<p>你應該會看到跟上次一樣的結果：<a href="https://www.finlab.tw/btc-backtesting-optimization/before.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="729" src="http://34.96.136.135/wp-content/uploads/2020/07/before-1-1024x729.png" alt="before 1" class="wp-image-1059" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/before-1-1024x729.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/before-1-300x214.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/before-1-768x547.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/before-1-1536x1094.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/before-1.png 1932w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：三年20倍的策略參數最佳化 (Part 7) 35"></figure></div>



<p>接下來就可以自動最佳化了！</p>



<h3 id="暴力枚舉">暴力枚舉</h3>



<p>你可能以為要寫for迴圈，但其實 backtesting 已經幫你寫好了，我們只要將參數範圍傳入&nbsp;<code>bt.optimize</code>，就可以了，非常方便：</p>



<pre class="wp-block-code"><code lang="python" class="language-python line-numbers">result2 = bt.optimize(n1=range(5, 100, 5),
                      n2=range(5, 100, 5))</code></pre>



<h3 id="優化後的結果">策略參數最佳化的結果</h3>



<p>由於策略優化完後，參數會自動更新，所以我們可以用：</p>



<pre class="wp-block-code"><code class="">bt.plot()</code></pre>



<p>來看優化後的績效就可以了！<a href="https://www.finlab.tw/btc-backtesting-optimization/after.png"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="737" src="http://34.96.136.135/wp-content/uploads/2020/07/after-1-1024x737.png" alt="after 1" class="wp-image-1061" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/after-1-1024x737.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/after-1-300x216.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/after-1-768x553.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/after-1-1536x1105.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/after-1.png 1932w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：三年20倍的策略參數最佳化 (Part 7) 36"></figure></div>



<p>三年半 20 倍，是不是很夢幻呀！而且還多空都賺，拿量化交易的方式交易比特幣，就像是拿大砲對付刀劍一樣，我們可以將優化前後的績效比對一下，真的差很多呢！</p>



<pre class="wp-block-code"><code lang="python" class="language-python">result1._trade_data.Equity.plot()
result2._trade_data.Equity.plot()</code></pre>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="354" src="http://34.96.136.135/wp-content/uploads/2020/07/compare-1-1-1024x354.png" alt="compare 1 1" class="wp-image-1062" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/compare-1-1-1024x354.png 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/compare-1-1-300x104.png 300w, https://www.finlab.tw/wp-content/uploads/2020/07/compare-1-1-768x265.png 768w, https://www.finlab.tw/wp-content/uploads/2020/07/compare-1-1-1536x531.png 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/compare-1-1.png 1986w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：三年20倍的策略參數最佳化 (Part 7) 37"></figure></div>



<p><a href="https://www.finlab.tw/btc-backtesting-optimization/compare.png"></a></p>



<p>但隨著期貨市場的開放，這樣的績效，或許沒辦法重現，或許市場已經慢慢走向效率化，可以看到2019年以後，賺得比較少，但是加密貨幣又不是只有 BTC，一定有很多未開發的地帶，等著量化交易去開拓的，所以也不用太擔心！</p>



<p>這些單元的用意，就是在你在開江闢土時，提供你豐富的資源，讓你在開發策略事半功倍！</p>



<p>更新：很多人都躍躍欲試呢！我幫大家寫好完整的代碼，可以在線上直接運行喔！<br><a rel="noreferrer noopener" href="https://colab.research.google.com/drive/1ESztR0DvBGQNRml_hpPWMkgXNJ2dmdUa?usp=sharing" target="_blank">請點此</a></p>



<p>下個階段，我們就可以來真的<a href="https://www.finlab.tw/btc-deposit-how/">入金交易囉</a>！</p>



<p>你可以到<a rel="noreferrer noopener" href="https://www.facebook.com/finlab.python/" target="_blank">FinLab粉專</a>，點選追蹤，或點讚，就可以收到我們的新單元囉！</p>



<p>如果喜歡我們的文章，也歡迎參考我們最新募資的線上課程「<a rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank">用 Python 理財：打造加密貨幣實戰策略</a>」，在線上課程中，我們會更有系統、更完整地教您如何從無到有，打造10種加密貨幣實戰策略，並且能夠自動化雲端交易！有興趣的話，可以<a rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank">點此觀看課程介紹影片</a>喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/btc-backtesting-optimization/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1056</post-id>	</item>
		<item>
		<title>用Python投資加密貨幣：如何投資加密貨幣 (Part 8)</title>
		<link>https://www.finlab.tw/btc-deposit-how/</link>
					<comments>https://www.finlab.tw/btc-deposit-how/#respond</comments>
		
		<dc:creator><![CDATA[FinLab - 韓承佑]]></dc:creator>
		<pubDate>Mon, 20 Jul 2020 12:02:48 +0000</pubDate>
				<category><![CDATA[加密貨幣]]></category>
		<category><![CDATA[BTC]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[比特幣]]></category>
		<guid isPermaLink="false">http://34.96.136.135/?p=1064</guid>

					<description><![CDATA[自從本blog開始介紹如何 "用Python投資加密貨幣" 以來，BTC已經上漲了約25％！我是有稍微選一下發文時機的，很想說自己未卜先知，但世界上沒有這種事情，只能說是個美麗的巧合吧！]]></description>
										<content:encoded><![CDATA[
<p>自從本 blog 開始介紹如何 &#8220;用 Python 投資加密貨幣&#8221;以來，<a href="https://tw.tradingview.com/symbols/BTCUSD/" class="rank-math-link" target="_blank" rel="noopener">BTC</a> 已經上漲了約25％！我是有稍微選一下發文時機的，很想說自己未卜先知，但世界上沒有這種事情，只能說是個美麗的巧合吧！<a href="https://www.finlab.tw/btc-deposit-how/thumbnail.jpeg"></a></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="684" src="http://34.96.136.135/wp-content/uploads/2020/07/thumbnail-4-1-1024x684.jpeg" alt="thumbnail 4 1" class="wp-image-1065" srcset="https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-4-1-1024x684.jpeg 1024w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-4-1-300x200.jpeg 300w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-4-1-768x513.jpeg 768w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-4-1-1536x1026.jpeg 1536w, https://www.finlab.tw/wp-content/uploads/2020/07/thumbnail-4-1.jpeg 1949w" sizes="(max-width: 1024px) 100vw, 1024px" title="用Python投資加密貨幣：如何投資加密貨幣 (Part 8) 38"></figure></div>



<p>畢竟所有的指標都是參考用，我們處在瞬息萬變的世界，別想要預測市場，而是以最機械的方式來投資，才不會無所適從、舉棋不定。</p>



<p>這個單元中，要來介紹，我用哪些方法來投資比特幣，最主要是兩種，只是分享，非建議喔！</p>



<h2 id="1-長線投資">1. 長線投資</h2>



<p>記得在2013年的時候，有一個大學生問：<br>「我現在有1萬元，要投資什麼比較好？」</p>



<p>有人回答：<br>「買入比特幣，不要管它，等你畢業了再換成現金」</p>



<p>要是當時真的照這個方法操作，畢業後，基本上就已經財富自由了！</p>



<p>這個故事告訴我們，有時候，挑好商品，買了放著，不要亂動，其實也滿好的！</p>



<h3 id="買入的原因">買入的原因</h3>



<p>買 BTC，一定是有價格以外的原因，就像是去菜市場買菜，為什麼買這顆蘋果？因為它顏色鮮豔、比較大顆、看起來比較甜&#8230;等，而不是因為這顆蘋果最近上漲（沒人這樣買蘋果吧？）</p>



<p>買 BTC 一樣要有理由，而不是覺得大家都在買，就跟著買，不然就是大家都再賣，就跟著賣，很容易就賠錢了。</p>



<h3 id="我的買入原因">我的買入原因</h3>



<p>我的買入理由，就是：BTC市值當時跟黃金比，不到1/50，BTC 有著優越的貨幣的特性，理論上應該是很有潛力的！</p>



<p>設定一個出場條件，然後嚴格執行，</p>



<h3 id="出場條件">出場條件</h3>



<p>例如我的出場條件就是：<br>BTC 到達跟黃金市值平起平坐，不過世界上哪有一定準確的預言？</p>



<p>所以保險起見可以設定：<br>「比特幣：黃金」<br>「市值 1：10」<br>「市值 1：5」<br>「市值 1：2」<br>「市值 1：1」<br>分別出場，這並不是投資建議，只是我自己的規劃而已，一定要做賣出條件，因為<br>「不要愛上任何投資的標的」<br>「沒有永遠都上漲的商品」</p>



<p>達成這個條件之前，我是分批慢慢買入。</p>



<h3 id="買入條件">買入條件</h3>



<p>直到金額到達自己投資「單項商品的上限」為止，不要壓身家，不要壓身家，不要壓身家！</p>



<p>畢竟這種超長線，最怕的就是買在高點！而很少人可以準確預測未來股價，所以平均分攤風險，是比較建議的。</p>



<p>用以上的方法，價格高高低低，心情也會受影響，所以為何不用「量化投資」來幫助我們獲利呢？</p>



<h2 id="2-量化投資">2. 量化投資</h2>



<p>量化投資，也就是利用程式機械式的操作，來避免不必要的風險！</p>



<p>例如<a href="https://www.finlab.tw/btc-backtesting-optimization/">前一篇文章所介紹的策略</a></p>



<p>回測跑得好，策略得開始運轉吧？</p>



<p>但架設server，還是有一定的難度，為了幫助大家做一個簡單的自動化交易系統，接下來的文章，首先我們會介紹&nbsp;<a href="https://www.finlab.tw/btc-deposit-ways/">BTC 如何入金</a>，也就是正式開始投資 BTC，然後呢，我們會用AWS，也就是Amazon推出的雲端伺服器，將<a href="https://www.finlab.tw/btc-backtesting-optimization/">前一篇文章所介紹的策略</a>真實上線使用，重點是：成本為0，完全免費！<br><a href="https://www.finlab.tw/aws-lambda-initial-setup/">詳情請看：雲端建置交易信號</a></p>



<p>如果喜歡我們的文章，也歡迎參考我們最新募資的線上課程「<a rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank">用 Python 理財：打造加密貨幣實戰策略</a>」，在線上課程中，我們會更有系統、更完整地教您如何從無到有，打造10種加密貨幣實戰策略，並且能夠自動化雲端交易！有興趣的話，可以<a rel="noreferrer noopener" href="https://hahow.in/cr/crypto-python" target="_blank">點此觀看課程介紹影片</a>喔！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.finlab.tw/btc-deposit-how/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1064</post-id>	</item>
	</channel>
</rss>
