# 用 Python 投資加密貨幣：用 pandas 實作均線交易策略訊號 (Part 3)

台股研究 2020年7月20日 約 3 分鐘閱讀

用 pandas 三步驟做出 BTCUSDT 均線交易訊號：rolling().mean() 算 20 與 60 期均線、不等式產生布林條件、shift(1) 取昨天值組出黃金交叉與死亡交叉，附 Google Colab 完整範例。

承接 BTC 爬蟲教學，用 pandas 的 rolling、不等式與 shift，三步驟做出加密貨幣均線交易訊號。

這篇文章中，我們將用 pandas 來做一個簡易的加密貨幣交易訊號！

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

## Pandas 操作介紹

承接著[上一篇文章](https://finlab.finance/blog/python-crypto-bitcoin-historical-data-crawler)，我們繼續在 [google colab](https://colab.research.google.com/) 上進行程式的實驗此時的 `df` 已經是歷史資料：

[![BTCUSDT 加密貨幣歷史資料 DataFrame 表格](https://r2.finlab.finance/blog/btc-trading-signal/df-1-1-1024x276.png)](https://r2.finlab.finance/blog/btc-trading-signal/df-1-1-1024x276.png)

依本文重跑

## 執行這個策略

複製提示詞，讓 AI 依照上方證據的資料、條件與風險檢查重跑一次。

告訴你的AI：

幫我設定 FinLab，重現這篇文章，請讀：https\://finlab.finance/setup?relatedUrl=/blog/crypto-trading-signal-python-pandas

[免安裝，開啟 FinLab Studio](https://studio.finlab.finance/chat?lang=zh\&research_context=%7B%22v%22%3A1%2C%22source_url%22%3A%22https%3A%2F%2Ffinlab.finance%2Fblog%2Fcrypto-trading-signal-python-pandas%22%7D)

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

顯示程式碼

```
df.Close
```

[![呼叫 df.Close 取得收盤價時間序列 pd.Series](https://r2.finlab.finance/blog/btc-trading-signal/series-1-1024x174.png)](https://r2.finlab.finance/blog/btc-trading-signal/series-1-1024x174.png)

由上圖可知，每一列也是一種物件，叫做 `pd.Series`，這種物件，就是一條序列，可以想像是excel的單一一列的意思。

## 製作簡易的加密貨幣均線策略

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

顯示程式碼

```
sma1 = df.Close.rolling(20).mean()
sma2 = df.Close.rolling(60).mean()
 
df.Close.plot()
sma1.plot()
sma2.plot()
```

[![BTCUSDT 收盤價與 20、60 期移動平均線繪圖](https://r2.finlab.finance/blog/btc-trading-signal/sma_plot-1024x425.png)](https://r2.finlab.finance/blog/btc-trading-signal/sma_plot-1024x425.png)

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

顯示程式碼

```
df.Close['2020'].plot()
sma1['2020'].plot()
sma2['2020'].plot()
```

[![選取 2020 年區間放大檢視收盤價與均線走勢圖](https://r2.finlab.finance/blog/btc-trading-signal/sma_plot2019-1024x397.png)](https://r2.finlab.finance/blog/btc-trading-signal/sma_plot2019-1024x397.png)

接下來，我們來設計交易訊號，我們希望做一個簡單的均線策略：

假如短週期均線 `sma1` 超過 長週期 `sma2` -> 做多，反之做空。

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

## 不等式條件

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

顯示程式碼

```
condition = sma1 > sma2
condition
```

[![sma1 大於 sma2 產生的布林 True False 時間序列](https://r2.finlab.finance/blog/btc-trading-signal/condition-1024x256.png)](https://r2.finlab.finance/blog/btc-trading-signal/condition-1024x256.png)

上圖中就是布林時間序列，每個時間點對映到「Ture」或是「False」，假如今天條件成立，也就是「sma1 > sma2」的話，該時間點對映到的就會是 True，反之則是 False。

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

## 調用「昨天」的價格 pd.Series.shift

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

顯示程式碼

```
print(df.Close)
print(df.Close.shift(1))
```

[![df.Close 與 df.Close.shift(1) 相差一個時間單位的比較](https://r2.finlab.finance/blog/btc-trading-signal/shift-1024x278.png)](https://r2.finlab.finance/blog/btc-trading-signal/shift-1024x278.png)

你會發現兩者相差一天，所以在做策略時，我會傾向於，將`pd.Series.shift(n)`，當作是「n個時間單位前的價格」，這邊我們用的是 '4h' 4小時的歷史價格，所以`pd.Series.shift(1)`，就是4小時前，而`pd.Series.shift(2)`，就是8小時前，以此類推。

假如我們只使用：`pd.Series.shift()`，n 不設定參數的話，pandas 會預設 `n=1` 喔！

## 結合上述的範例，產生策略訊號

我們希望的做出來的邏輯： 做多： 當（今天短週期均線 > 今天長週期均線） 且 （昨天短週期均線 < 昨天長週期均線） 做空： 當（今天短週期均線 < 今天長週期均線） 且 （昨天短週期均線 > 昨天長週期均線）

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

顯示程式碼

```
signal_long = (sma1 > sma2) & (sma1.shift() < sma2.shift())
signal_short = (sma1 < sma2) & (sma1.shift() > sma2.shift())
```

上述程式碼中的 `&` 就是「且」的意思。

我們可以將訊號繪製出來：

顯示程式碼

```
signal_long.astype(int).plot()
(-signal_short.astype(int)).plot()
```

[![均線突破策略買進與賣出訊號繪圖，1 為買進 -1 為賣出](https://r2.finlab.finance/blog/btc-trading-signal/signal-1024x396.png)](https://r2.finlab.finance/blog/btc-trading-signal/signal-1024x396.png)

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

## 製作策略

然而我們怎麼知道，照著這個交易訊號操作，實際的績效是怎麼樣呢？[下一個單元中：回測](https://finlab.finance/blog/python-bitcoin-backtesting-sma-strategy)，會教大家怎麼用 [backtesting](https://github.com/kernc/backtesting.py) 這個 package，來實做回測，模擬這個策略的績效，敬請期待！

如果喜歡我們的文章，也歡迎參考我們最新募資的線上課程「[用 Python 理財：打造加密貨幣實戰策略](https://hahow.in/cr/crypto-python)」，在線上課程中，我們會更有系統、更完整地教您如何從無到有，打造10種加密貨幣實戰策略，並且能夠自動化雲端交易！有興趣的話，可以[點此觀看課程介紹影片](https://hahow.in/cr/crypto-python)喔！

***

## 延伸閱讀

* [爬蟲下載比特幣歷史數據（Part 2）](https://finlab.finance/blog/python-crypto-bitcoin-historical-data-crawler)
* [均線交叉回測策略實做（Part 4）](https://finlab.finance/blog/python-bitcoin-backtesting-sma-strategy)
* [程式交易是什麼？完整入門指南](https://finlab.finance/tools/program-trading)

**投資警語：本文僅供教學參考，不構成投資建議。過去績效不代表未來表現，投資有風險。加密貨幣價格波動劇烈，請特別注意風險。**

![韓承佑](https://finlab.finance/people/cheng-yu-han-avatar.jpg)

韓承佑

創辦人 & 量化研究員

韓承佑是 FinLab 創辦人，也是開源 Python 量化套件 finlab 的作者，長年投入台股與美股的量化策略研究、回測與教學。

[在 GitHub 上追蹤 →](https://github.com/koreal6803) [在 LinkedIn 上連結 →](https://www.linkedin.com/in/cheng-yu-han/)

FinLab AI

### 想建立自己的策略？

用自然語言描述你的選股想法，AI 自動驗證、回測、給你答案

[免費開始](https://finlab.finance/#get-started)

## 更多技術指標研究

[查看全部](https://finlab.finance/blog/category/technical)

* [![美股均值回歸策略回測：買進三日落後的槓桿 ETF，十年年化 51.9%](https://r2.finlab.finance/blog/us-mean-reversion-strategy/chart1_strategy_equity-202610b.png) 美股均值回歸策略回測：買進三日落後的槓桿 ETF，十年年化 51.9% 年化報酬 51.9% · 美股](https://finlab.finance/blog/us-mean-reversion-strategy)
* [![技術分析 vs 基本面分析：台股回測的終極對決](https://r2.finlab.finance/blog/technical-vs-fundamental/chart_validation_2026-10-30.png) 技術分析 vs 基本面分析：台股回測的終極對決 年化報酬 36.3% · 台股](https://finlab.finance/blog/technical-vs-fundamental)
* [![Python 台股 API 比較：FinLab、FinMind、yfinance、證交所 OpenAPI 怎麼選](https://r2.finlab.finance/blog/python-get-taiwan-stock-data/thumbnail.png) Python 台股 API 比較：FinLab、FinMind、yfinance、證交所 OpenAPI 怎麼選 年化報酬 30.1% · 台股](https://finlab.finance/blog/python-get-taiwan-stock-data)
* [![突破策略回測：QQQ 創 21 日新高＋200 日均線濾網，槓桿 ETF 趨勢跟隨十年實測](https://r2.finlab.finance/blog/us-breakout-trend-strategy/chart5_strategy_equity-202610b.png) 突破策略回測：QQQ 創 21 日新高＋200 日均線濾網，槓桿 ETF 趨勢跟隨十年實測 年化報酬 29.8% · 美股](https://finlab.finance/blog/us-breakout-trend-strategy)

來源：https://finlab.finance/blog/crypto-trading-signal-python-pandas｜資料日期：依上文各表格與段落標示｜頁面更新：2026-11-25
