交易訊號

Financial Trading in Python

Chelsea Yang

Data Science Instructor

什麼是交易訊號?

  • 依預先設定條件觸發做多或放空資產
  • 可用下列方式建立:

    • 一種技術指標
    • 多種技術指標
    • 市場資料與指標的組合
  • 演算法交易常用

Financial Trading in Python

訊號範例

  • 訊號:Price > SMA(當價格上穿 SMA 時做多)

顯示建議進場訊號的圖。

Financial Trading in Python

如何在 bt 實作訊號

  1. 取得資料並計算指標
  2. 定義以訊號為基礎的策略
    • bt.algos.SelectWhere()
    • bt.algos.WeighTarget()
  3. 建立並執行回測
  4. 檢視回測結果
Financial Trading in Python

建立訊號

# Get price data by the stock ticker
price_data = bt.get('aapl', start='2019-11-1', end='2020-12-1')
# Calculate SMA
sma = price_data.rolling(20).mean()

或使用 talib 計算指標:

# Calculate SMA
import talib
sma =  talib.SMA(price_data['Close'], timeperiod=20)
Financial Trading in Python

定義以訊號為基礎的策略

# Define the signal-based strategy
bt_strategy = bt.Strategy('AboveEMA',
                          [bt.algos.SelectWhere(price_data > sma),
                           bt.algos.WeighEqually(),
                           bt.algos.Rebalance()])
  • 為簡化起見,假設:
    • 一次只交易一檔資產
    • 無滑價與手續費
      • 滑價:預期成交價與實際成交價的差異
      • 手續費:券商執行交易時收取的費用
Financial Trading in Python

回測以訊號為基礎的策略

# Create the backtest and run it
bt_backtest = bt.Backtest(bt_strategy, price_data)
bt_result = bt.run(bt_backtest)
Financial Trading in Python

繪製回測結果

# Plot the backtest result
bt_result.plot(title='Backtest result')

回測結果圖

Financial Trading in Python

一起來練習吧!

Financial Trading in Python

Preparing Video For Download...