今天在重讀 "Python 金融市場大賺錢聖經" 這本書 (我的是第一版, 目前已出至第三版) 第三章時看到作者介紹 Ta-Lib 之外的另一個技術分析套件 ta, 它最棒的一個特色是提供了一些可一次計算出全部指標的快捷函式, 例如呼叫 add_all_ta_features() 即可一次計算出所有它支援的 80 種技術指標, 非常好用.
關於 ta 的發展與特性摘要說明如下 :
- 最早是由巴西開發者 David Cañadas Gonzalo 所創建, 於 2018 年以 MIT 授權開放原始碼.
- 底層基於 Numpy 與 Pandas, 主要用來進行金融時間序列的高效運算.
- 最新版本支援 80 種以上股票與外匯市場技術指標, 涵蓋趨勢, 動能, 與波動性.
教學文件參考 :
關於 Ta-lib 套件參考 :
一. 安裝 ta 套件 :
與 Ta-Lib 安裝方式不同 (在 Windows 下需要用 whl 檔安裝; 在 Linux 下要自行從原始碼編譯), ta 套件可直接用 pip 指令安裝, 先用 pip show 檢查是否有安裝過此套件 :
D:\python\test>pip show ta
Name: ta
Version: 0.5.25
Summary: Technical Analysis Library in Python
Home-page: https://github.com/bukosabino/ta
Author: Dario Lopez Padial (Bukosabino)
Author-email: Bukosabino@gmail.com
License: The MIT License (MIT)
Location: c:\users\tony1\appdata\local\programs\thonny\lib\site-packages
Requires: numpy, pandas
Required-by: FinMind
原來之前安裝 FinMind 時就已經因為相依套件原因被安裝了, 版本是 0.5.25, 所以用 -U 更新到最新版本 (不知會不會影響 FinMind, 後面再測試看看) :
D:\python\test>pip install ta -U
Requirement already satisfied: ta in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (0.5.25)
Collecting ta
Downloading ta-0.11.0.tar.gz (25 kB)
Preparing metadata (setup.py) ... done
Requirement already satisfied: numpy in c:\users\tony1\appdata\roaming\python\python310\site-packages (from ta) (1.24.3)
Requirement already satisfied: pandas in c:\users\tony1\appdata\roaming\python\python310\site-packages (from ta) (2.0.3)
Requirement already satisfied: python-dateutil>=2.8.2 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from pandas->ta) (2.8.2)
Requirement already satisfied: pytz>=2020.1 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from pandas->ta) (2023.3)
Requirement already satisfied: tzdata>=2022.1 in c:\users\tony1\appdata\roaming\python\python310\site-packages (from pandas->ta) (2023.3)
Requirement already satisfied: six>=1.5 in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (from python-dateutil>=2.8.2->pandas->ta) (1.16.0)
Building wheels for collected packages: ta
Building wheel for ta (setup.py) ... done
Created wheel for ta: filename=ta-0.11.0-py3-none-any.whl size=29422 sha256=058b68e1473a19f6c12c845769f870b008f4c7d3970a7989ebfe7636970457cd
Stored in directory: c:\users\tony1\appdata\local\pip\cache\wheels\5f\67\4f\8a9f252836e053e532c6587a3230bc72a4deb16b03a829610b
Successfully built ta
Installing collected packages: ta
Attempting uninstall: ta
Found existing installation: ta 0.5.25
Uninstalling ta-0.5.25:
Successfully uninstalled ta-0.5.25
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
finmind 1.6.9 requires ta~=0.5.25, but you have ta 0.11.0 which is incompatible.
Successfully installed ta-0.11.0
用 dir() 檢視套件內容 :
>>> import ta
>>> dir(ta)
['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'add_all_ta_features', 'add_momentum_ta', 'add_others_ta', 'add_trend_ta', 'add_volatility_ta', 'add_volume_ta', 'momentum', 'others', 'trend', 'utils', 'volatility', 'volume', 'wrapper']
用自訂模組 members.py 的 list_members() 函式檢視套件內容 :
>>> from members import list_members
>>> list_members(ta)
add_all_ta_features <class 'function'>
add_momentum_ta <class 'function'>
add_others_ta <class 'function'>
add_trend_ta <class 'function'>
add_volatility_ta <class 'function'>
add_volume_ta <class 'function'>
momentum <class 'module'>
others <class 'module'>
trend <class 'module'>
utils <class 'module'>
volatility <class 'module'>
volume <class 'module'>
wrapper <class 'module'>
ta 套件內的模組整理如下表 :
ta 的模組 | 說明 |
momentum | 包含所有動能類指標 (例如 RSI, MACD, KD 等) 的模組 |
others | 包含其他類技術指標 (例如每日報酬率與波動率等) 的模組 |
trend | 包含趨勢類技術指標 (例如 SMA, EMA, ADX, CCI 等) 的模組 |
utils | 提供實用工具 (例如處理空值, 標準化數據等) 的模組 |
volatility | 包含波動性類指標 (例如布林通道, ATR 等) 的模組 |
volume | 包含成交量類指標 (例如 OBV, ADI, Chaikin 等) 的模組 |
wrapper | 提供封裝的類別與函式, 用於更高層級的應用 |
ta 目前支援總共 80 種技術指標, 區分為如下五種類型 :
ta 支援函數式 (functional) 與物件導向式 (object-oriented) 兩種 API 介面, 因此將這五種類型的指標分別實作為函式與類別, 分別收納於 trend, voatility, volume, momentum, 與 others 模組中. 可以用 dir() 或上面使用的自訂模組 members 來檢視這些模組內收容了哪些指標 (其中全小寫的是指標函式, 首字母大寫的是指標類別) :
趨勢指標模組 :
>>> dir(ta.trend)
['ADXIndicator', 'AroonIndicator', 'CCIIndicator', 'DPOIndicator', 'EMAIndicator', 'IchimokuIndicator', 'IndicatorMixin', 'KSTIndicator', 'MACD', 'MassIndex', 'PSARIndicator', 'SMAIndicator', 'STCIndicator', 'TRIXIndicator', 'VortexIndicator', 'WMAIndicator', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_ema', '_get_min_max', '_sma', 'adx', 'adx_neg', 'adx_pos', 'aroon_down', 'aroon_up', 'cci', 'dpo', 'ema_indicator', 'ichimoku_a', 'ichimoku_b', 'ichimoku_base_line', 'ichimoku_conversion_line', 'kst', 'kst_sig', 'macd', 'macd_diff', 'macd_signal', 'mass_index', 'np', 'pd', 'psar_down', 'psar_down_indicator', 'psar_up', 'psar_up_indicator', 'sma_indicator', 'stc', 'trix', 'vortex_indicator_neg', 'vortex_indicator_pos', 'wma_indicator']
動量指標模組 :
>>> dir(ta.momentum)
['AwesomeOscillatorIndicator', 'IndicatorMixin', 'KAMAIndicator', 'PercentagePriceOscillator', 'PercentageVolumeOscillator', 'ROCIndicator', 'RSIIndicator', 'StochRSIIndicator', 'StochasticOscillator', 'TSIIndicator', 'UltimateOscillator', 'WilliamsRIndicator', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_ema', 'awesome_oscillator', 'kama', 'np', 'pd', 'ppo', 'ppo_hist', 'ppo_signal', 'pvo', 'pvo_hist', 'pvo_signal', 'roc', 'rsi', 'stoch', 'stoch_signal', 'stochrsi', 'stochrsi_d', 'stochrsi_k', 'tsi', 'ultimate_oscillator', 'williams_r']
量能指標模組 :
>>> dir(ta.volume)
['AccDistIndexIndicator', 'ChaikinMoneyFlowIndicator', 'EaseOfMovementIndicator', 'ForceIndexIndicator', 'IndicatorMixin', 'MFIIndicator', 'NegativeVolumeIndexIndicator', 'OnBalanceVolumeIndicator', 'VolumePriceTrendIndicator', 'VolumeWeightedAveragePrice', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_ema', 'acc_dist_index', 'chaikin_money_flow', 'ease_of_movement', 'force_index', 'money_flow_index', 'negative_volume_index', 'np', 'on_balance_volume', 'pd', 'sma_ease_of_movement', 'tp', 'volume_price_trend', 'volume_weighted_average_price']
波動指標模組 :
>>> dir(ta.volatility)
['AverageTrueRange', 'BollingerBands', 'DonchianChannel', 'IndicatorMixin', 'KeltnerChannel', 'UlcerIndex', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'average_true_range', 'bollinger_hband', 'bollinger_hband_indicator', 'bollinger_lband', 'bollinger_lband_indicator', 'bollinger_mavg', 'bollinger_pband', 'bollinger_wband', 'donchian_channel_hband', 'donchian_channel_lband', 'donchian_channel_mband', 'donchian_channel_pband', 'donchian_channel_wband', 'keltner_channel_hband', 'keltner_channel_hband_indicator', 'keltner_channel_lband', 'keltner_channel_lband_indicator', 'keltner_channel_mband', 'keltner_channel_pband', 'keltner_channel_wband', 'np', 'pd', 'ulcer_index']
其他指標模組 :
>>> dir(ta.others)
['CumulativeReturnIndicator', 'DailyLogReturnIndicator', 'DailyReturnIndicator', 'IndicatorMixin', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'cumulative_return', 'daily_log_return', 'daily_return', 'np', 'pd']
others 模組的函式嚴格來說不算是技術指標, 比較像是功能函式, 其中 daily_return() 與 daily_log_return() 分別用來計算日報酬率與對數日報酬率; 而 cumulative_return() 則用來計算累積報酬率, 計算結果都會在 DataFrame 中添加一欄來儲存.
另外, 工具模組 utils 提供了一個很常用 dropna() 函式可用來去除 DataFrame 中的 NaN :
>>> dir(ta.utils)
['IndicatorMixin', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_ema', '_get_min_max', '_sma', 'dropna', 'math', 'np', 'pd']
使用方法例如 :
from ta.utils import dropna
dropna(df)
另外, ta 套件還提供可一次產生全部指標的快捷函式, 如下表所示 :
ta 的快捷函式 | 說明 |
add_all_ta_features() | 計算所有支援的技術指標後添加到 DataFrame 中. 傳入參數 : df (必要之位置參數): 不含 NaN 值的價量 DatFrame open, high, low, close, volume (關鍵字參數) : OHLCV 價量欄位名稱 fillna (關鍵字參數) : 是否以預設值填充 NaN, True/False (預設) 傳回值 : 添加技術指標欄位值後的 DataFrame |
add_momentum_ta() | 添加動能類技術指標 (例如 RSI, MACD 等) 到 DataFrame. 傳入參數 : df (必要之位置參數): 不含 NaN 值的價量 DatFrame close, volume (關鍵字參數) : 收盤價, 成交量欄位名稱 fillna (關鍵字參數) : 是否以預設值填充 NaN, True/False (預設) 傳回值 : 添加動能類技術指標欄位值後的 DataFrame |
add_others_ta() | 添加其他類技術指標 (例如每日報酬率與波動率等) 到 DataFrame. 傳入參數 : df (必要之位置參數): 不含 NaN 值的價量 DatFrame close (關鍵字參數) : 開盤價欄位名稱 fillna (關鍵字參數) : 是否以預設值填充 NaN, True/False (預設) 傳回值 : 添加其他類技術指標欄位值後的 DataFrame |
add_trend_ta() | 添加趨勢類技術指標 (例如移動平均線, ADX) 到 DataFrame. 傳入參數 : df (必要之位置參數): 不含 NaN 值的價量 DatFrame high, low, close (關鍵字參數) : 最高價, 最低價, 收盤價之欄位名稱 fillna (關鍵字參數) : 是否以預設值填充 NaN, True/False (預設) 傳回值 : 添加趨勢類技術指標欄位值後的 DataFrame |
add_volatility_ta() | 添加波動類技術指標 (例如布林通道) 到 DataFrame. 傳入參數 : df (必要之位置參數): 不含 NaN 值的價量 DatFrame high, low, close (關鍵字參數) : 最高價, 最低價, 收盤價之欄位名稱 fillna (關鍵字參數) : 是否以預設值填充 NaN, True/False (預設) 傳回值 : 添加動能類技術指標欄位值後的 DataFrame |
add_volume_ta() | 添加量能類技術指標 (例如 OBV) 到 DataFrame. 傳入參數 : high, low, close, volume (關鍵字參數) : OHLCV 價量欄位名稱 fillna (關鍵字參數) : 是否以預設值填充 NaN, True/False (預設) 傳回值 : 添加技術指標欄位值後的 DataFrame |
這些函式都是快捷函式, 其中 add_all_ta_features() 可一次計算全部 80 種指標並將結果添加到 DataFrame 的欄位中; 其他函式則是僅一次計算出某一類之所有指標並添加到 DataFrame 欄位中.
二. 取得股票資料 :
ta 套件支援直接傳入 Pandas 的 DataFrame 來計算指標, 可利用 yfinance (不需 API key) 或 FinMind 與 FinLab (需先註冊取得 API key) 取得包含 OHLCV 欄位的股票資料, 參考 :
以下測試使用較方便的 yfinance.
以 0050 ETF 為例從 yfinance 取得其盤後資料 :
>>> import yfinance as yf
>>> df=yf.download('0050.TW', start='2024-11-06', end='2025-01-09')
[*********************100%%**********************] 1 of 1 completed
檢視最後 5 筆資料 :
>>> df.tail()
Open High ... Adj Close Volume
Date ...
2024-12-27 197.600006 199.050003 ... 198.899994 6987417
2024-12-30 198.149994 198.649994 ... 197.800003 8677266
2024-12-31 196.699997 196.899994 ... 195.750000 7836534
2025-01-02 195.649994 195.649994 ... 194.050003 12797702
2025-01-03 196.000000 196.949997 ... 196.000000 7113371
[5 rows x 6 columns]
檢視欄位名稱 :
>>> df.columns
Index(['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume'], dtype='object')
ta 套件不會像 Ta-Lib 那樣要求欄位名稱必須小寫, 而是在計算指標時要指定所需之價量欄位名稱, 因此毋須對欄名做任何處理.
三. ta 的兩種用法 :
ta 支援函數式 (functional) 與物件導向式 (object-oriented) API, 由於 ta 與 Pandas 深度結合, 其 API 以物件導向式 API 為主. 不過它的函數式 API 提供了可以一次計算所有指標的六個快捷函式, 這是有別於 Ta-Lib 的一大特色.
1. ta 的函數式 API :
ta 的指標函式有下列三種 :
- 個別指標函式 : ta.xxx_yyy() (xxx 為類型名稱, yyy 為指標函式名稱)
- 類型指標函式 : ta.add_xxx_ta() (xxx 為類型名稱, 計算該類型的所有指標)
- 全部指標函式 : ta.add_all_ta_features() (計算全部 80 種指標)
後兩種為快捷函式 (無參數, 使用預設值計算指標), 可一次計算同類型所有指標或全部 80 個指標, 這些指標函式說明文件參考下列索引 :
(1). 個別指標函式 :
- ta.trend.sma_indicator() : 移動平均指標
- ta.momentum.stoch() : KD 指標
- ta.volume.on_balance_volume() : OBV 能量潮指標
- ta.volume.money_flow_index() : MFI 指標
以移動平均指標 SMA 為例, 可從官網教學文件查得其 API 如下 :
可知 SMA 指標函式有三個參數 : close (必要), window, 與 fillna, 收盤價 close 資料型態為 Pandas 的 Series 物件, window 為移動窗口日數 (預設是 12 天均價), fillna 若社為 True 會自動刪除值為 NaN 之收盤價 :
>>> sma12=ta.trend.sma_indicator(df['Close'])
>>> sma12
Date
2024-11-06 NaN
2024-11-07 NaN
2024-11-08 NaN
2024-11-11 NaN
2024-11-12 NaN
2024-11-13 NaN
2024-11-14 NaN
2024-11-15 NaN
2024-11-18 NaN
2024-11-19 NaN
2024-11-20 NaN
2024-11-21 193.629167
2024-11-22 193.450001
2024-11-25 193.025002
2024-11-26 192.262502
2024-11-27 191.262502
2024-11-28 190.662502
2024-11-29 190.204169
2024-12-02 190.262502
2024-12-03 190.425002
2024-12-04 190.908335
2024-12-05 191.262502
2024-12-06 191.620836
2024-12-09 192.175002
2024-12-10 192.304169
2024-12-11 192.350001
2024-12-12 192.791667
2024-12-13 193.475000
2024-12-16 194.250000
2024-12-17 195.070834
2024-12-18 195.520835
2024-12-19 195.529167
2024-12-20 195.291668
2024-12-23 195.354168
2024-12-24 195.525002
2024-12-25 195.725001
2024-12-26 196.029167
2024-12-27 196.529167
2024-12-30 196.750001
2024-12-31 196.787501
2025-01-02 196.616667
2025-01-03 196.525000
2025-01-06 196.945833
2025-01-07 197.779166
2025-01-08 198.508333
Name: sma_12, dtype: float64
傳入 window 參數可指定移動窗口, 例如 5 日移動均線 :
>>> sma5=ta.trend.sma_indicator(df['Close'], window=5)
>>> sma5
Date
2024-11-06 NaN
2024-11-07 NaN
2024-11-08 NaN
2024-11-11 NaN
2024-11-12 196.950000
2024-11-13 196.460001
2024-11-14 195.170001
2024-11-15 193.840002
2024-11-18 191.950000
2024-11-19 191.600000
2024-11-20 191.339999
2024-11-21 191.010001
2024-11-22 191.150000
2024-11-25 191.690002
2024-11-26 191.210004
2024-11-27 190.340005
2024-11-28 189.830005
2024-11-29 188.670004
2024-12-02 188.540002
2024-12-03 189.430002
2024-12-04 191.100000
2024-12-05 193.039999
2024-12-06 194.739999
2024-12-09 195.600000
2024-12-10 195.660001
2024-12-11 195.150000
2024-12-12 194.879999
2024-12-13 194.789999
2024-12-16 194.810001
2024-12-17 195.310001
2024-12-18 196.150003
2024-12-19 196.000003
2024-12-20 195.460004
2024-12-23 195.690002
2024-12-24 195.830002
2024-12-25 196.089999
2024-12-26 196.860001
2024-12-27 198.119998
2024-12-30 198.229999
2024-12-31 197.819998
2025-01-02 196.950000
2025-01-03 196.500000
2025-01-06 197.150000
2025-01-07 198.469998
2025-01-08 199.589999
Name: sma_5, dtype: float64
可見數值與用 Ta-Lib 的 talib.SMA() 計算出來的是一樣的, 但不同之處為 Ta-Lib 函式的傳回值為 ndarray 物件, 而 ta 函式傳回的是 Series 物件.
OBV 指標函式 ta.volume.on_balance_volume() 的 API 如下所示 :
可見 OBV 指標的必要參數有兩個 : 收盤價 close 與成交量 volume, 資料型態均為 Pandas 的 Series 物件, 因為 OBV 是固定比較前後日之收盤價計算出來的, 所以沒有週期參數 :
>>> obv=ta.volume.on_balance_volume(df['Close'], df['Volume'])
>>> obv
Date
2024-11-06 16706376
2024-11-07 30204928
2024-11-08 43155079
2024-11-11 55519092
2024-11-12 29247005
2024-11-13 20052415
2024-11-14 7905800
2024-11-15 15291381
2024-11-18 1896865
2024-11-19 9515186
2024-11-20 9437186
2024-11-21 -6439431
2024-11-22 1526156
2024-11-25 -6300507
2024-11-26 -17691329
2024-11-27 -31764015
2024-11-28 -44873129
2024-11-29 -36744909
2024-12-02 -26200831
2024-12-03 -16247725
2024-12-04 -9792476
2024-12-05 -2346273
2024-12-06 -9155779
2024-12-09 -4515915
2024-12-10 -8993222
2024-12-11 -15707911
2024-12-12 -10680670
2024-12-13 -6160243
2024-12-16 1183349
2024-12-17 10477578
2024-12-18 17031455
2024-12-19 3986408
2024-12-20 -7136986
2024-12-23 4039080
2024-12-24 12234982
2024-12-25 18141105
2024-12-26 13337544
2024-12-27 20324961
2024-12-30 11647695
2024-12-31 3811161
2025-01-02 -8986541
2025-01-03 -1873170
2025-01-06 22754623
2025-01-07 38698467
2025-01-08 26842750
Name: obv, dtype: int64
MFI 指標函式 ta.volume.money_flow_index() 的 API 如下 :
可見 MFI 指標的必要參數有 4 個 : high, low, close, 與 volume, 資料型態均為 Pandas 的 Series 物件, 週期參數 window 預設為 14 日 (與 Ta-Lib 一樣) :
>>> mfi=ta.volume.money_flow_index(df['High'], df['Low'], df['Close'], df['Volume'])
>>> mfi
Date
2024-11-06 NaN
2024-11-07 NaN
2024-11-08 NaN
2024-11-11 NaN
2024-11-12 NaN
2024-11-13 NaN
2024-11-14 NaN
2024-11-15 NaN
2024-11-18 NaN
2024-11-19 NaN
2024-11-20 NaN
2024-11-21 NaN
2024-11-22 NaN
2024-11-25 39.301682
2024-11-26 36.522781
2024-11-27 27.843909
2024-11-28 19.482690
2024-11-29 25.247484
2024-12-02 35.842102
2024-12-03 42.918545
2024-12-04 49.655030
2024-12-05 49.740230
2024-12-06 52.229974
2024-12-09 51.119383
2024-12-10 49.334007
2024-12-11 53.017548
2024-12-12 51.856243
2024-12-13 46.397760
2024-12-16 54.858813
2024-12-17 66.148226
2024-12-18 70.160985
2024-12-19 59.032024
2024-12-20 48.676280
2024-12-23 49.330576
2024-12-24 50.220182
2024-12-25 43.808475
2024-12-26 49.368843
2024-12-27 50.541067
2024-12-30 48.551503
2024-12-31 48.016515
2025-01-02 40.670406
2025-01-03 45.672339
2025-01-06 52.673952
2025-01-07 55.040936
2025-01-08 52.999103
Name: mfi_14, dtype: float64
# kbar.py
import mplfinance as mpf
class KBar():
def __init__(self, df):
self.df=df
self.addplots=[]
def addplot(self, data, **kwargs):
plot=mpf.make_addplot(data, **kwargs)
self.addplots.append(plot)
def plot(self, embedding=False, **kwargs):
color=mpf.make_marketcolors(up='red', down='green', inherit=True)
font={'font.family': 'Microsoft JhengHei'}
style=mpf.make_mpf_style(base_mpf_style='default',
marketcolors=color,
rc=font)
kwargs['type']='candle'
kwargs['style']=style
kwargs['addplot']=self.addplots
if embedding:
fig, ax=mpf.plot(self.df, returnfig=True, **kwargs)
return fig
else:
mpf.plot(self.df, **kwargs)
匯入上面自訂的 kbar 模組, 呼叫 kbar.KBar() 建構式並傳入價量資料建立一個 KBar 物件, 然後把 SMA 指標畫在 K 線圖上疊圖, 把 OBV 與 MFI 畫在副圖 :
>>> import kbar
>>> kb=kbar.KBar(df)
>>> kb.addplot(sma5, panel=0) # 疊圖
>>> kb.addplot(obv, panel=1, ylabel='OBV') # 副圖 1
>>> kb.addplot(mfi, panel=2, ylabel='MFI') # 副圖 2
>>> kb.plot(title='台灣五十')
結果如下 :
(2). 趨勢指標的快捷函式 ta.add_trend_ta() :
快捷函式中的類型指標函式格式為 ta.add_xxx_ta_(), 其中 xxx 表示五大指標類型 trend, volatility, volume, momentum, 與 others, 呼叫此種函式會一次計算出該類型的所有指標, 結果會儲存在 DataFrame 的新增指標欄位中.
呼叫 ta.add_trend_ta() 會產生趨勢類型之指標數據, 其參數格式如下 :
ta.add_trend_ta(
df: pd.DataFrame, # 價量資料 (必要)
high: str, # 最高價欄名 (必要)
low: str, # 最低價欄名 (必要)
close: str, # 收盤價欄名 (必要)
fillna: bool = False, # 是否在技術指標計算後自動填充缺失值
colprefix: str = "" # 在新增的技術指標攔名前添加前綴以避免欄名衝突
)
此函式會以預設 window 參數值去計算所有趨勢類型之指標, 將結果添加到 DataFrame 中 (一個指標一個欄位) 後傳回 (可以用一個變數來接收傳回值, 但沒必要) :
>>> ta.add_trend_ta(df, high='High', low='Low', close='Close')
檢視傳回的 DataFrame 欄位 :
>>> df.columns
Index(['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume', 'trend_macd',
'trend_macd_signal', 'trend_macd_diff', 'trend_sma_fast',
'trend_sma_slow', 'trend_ema_fast', 'trend_ema_slow',
'trend_vortex_ind_pos', 'trend_vortex_ind_neg', 'trend_vortex_ind_diff',
'trend_trix', 'trend_mass_index', 'trend_dpo', 'trend_kst',
'trend_kst_sig', 'trend_kst_diff', 'trend_ichimoku_conv',
'trend_ichimoku_base', 'trend_ichimoku_a', 'trend_ichimoku_b',
'trend_stc', 'trend_adx', 'trend_adx_pos', 'trend_adx_neg', 'trend_cci',
'trend_visual_ichimoku_a', 'trend_visual_ichimoku_b', 'trend_aroon_up',
'trend_aroon_down', 'trend_aroon_ind', 'trend_psar_up',
'trend_psar_down', 'trend_psar_up_indicator',
'trend_psar_down_indicator'],
dtype='object')
可見 df 除了原來的價量欄位外, 後面新增了所有支援之趨勢指標欄位 :
趨勢指標 | df 指標欄位名稱 |
MACD (Moving Average Convergence Divergence) | trend_macd, trend_macd_signal, trend_macd_diff |
SMA (Simple Moving Average) | trend_sma_fast, trend_sma_slow |
EMA (Exponential Moving Average) | trend_ema_fast, trend_ema_slow |
Vortex Indicator | trend_vortex_ind_pos, trend_vortex_ind_neg, trend_vortex_ind_diff |
TRIX (Triple Exponential Average) | trend_trix |
Mass Index | trend_mass_index |
DPO (Detrended Price Oscillator) | trend_dpo |
KST (Know Sure Thing) | trend_kst, trend_kst_sig, trend_kst_diff |
Ichimoku Cloud | trend_ichimoku_conv, trend_ichimoku_base, trend_ichimoku_a, trend_ichimoku_b |
STC (Schaff Trend Cycle) | trend_stc |
ADX (Average Directional Index) | trend_adx, trend_adx_pos, trend_adx_neg |
CCI (Commodity Channel Index) | trend_cci |
Visual Ichimoku | trend_visual_ichimoku_a, trend_visual_ichimoku_b |
Aroon Indicator | trend_aroon_up, trend_aroon_down, trend_aroon_ind |
Parabolic SAR | trend_psar_up, trend_psar_down, trend_psar_up_indicator, trend_psar_down_indicator |
檢視其中的 trend_sma_fast 欄位可知它就是預設 window=12 的 SMA 指標 :
>>> df['trend_sma_fast']
Date
2024-11-06 NaN
2024-11-07 NaN
2024-11-08 NaN
2024-11-11 NaN
2024-11-12 NaN
2024-11-13 NaN
2024-11-14 NaN
2024-11-15 NaN
2024-11-18 NaN
2024-11-19 NaN
2024-11-20 NaN
2024-11-21 193.629167
2024-11-22 193.450001
2024-11-25 193.025002
2024-11-26 192.262502
2024-11-27 191.262502
2024-11-28 190.662502
2024-11-29 190.204169
2024-12-02 190.262502
2024-12-03 190.425002
2024-12-04 190.908335
2024-12-05 191.262502
2024-12-06 191.620836
2024-12-09 192.175002
2024-12-10 192.304169
2024-12-11 192.350001
2024-12-12 192.791667
2024-12-13 193.475000
2024-12-16 194.250000
2024-12-17 195.070834
2024-12-18 195.520835
2024-12-19 195.529167
2024-12-20 195.291668
2024-12-23 195.354168
2024-12-24 195.525002
2024-12-25 195.725001
2024-12-26 196.029167
2024-12-27 196.529167
2024-12-30 196.750001
2024-12-31 196.787501
2025-01-02 196.616667
2025-01-03 196.525000
2025-01-06 196.945833
2025-01-07 197.779166
2025-01-08 198.508333
Name: trend_sma_fast, dtype: float64
(3). 動能指標的快捷函式 ta.add_momentum_ta() :
呼叫 ta.add_momentum_ta() 來產生動能類型之指標數據, 其參數格式如下 :
ta.add_momentum_ta(
df: pd.DataFrame, # 價量資料 (必要)
high: str, # 最高價欄名 (必要)
low: str, # 最低價欄名 (必要)
close: str, # 收盤價欄名 (必要)
volume: str, # 成交量 (必要) fillna: bool = False, # 是否在技術指標計算後自動填充缺失值
colprefix: str = "" # 在新增的技術指標攔名前添加前綴以避免欄名衝突
)
可見量能類型指標多了一個必要參數 volume, 此函式會以預設 window 參數值去計算所有動能類型之指標.
為了清楚看出此函式新增了那些欄位, 重新下載價量資料讓 df 回復為原始欄位 :
>>> df=yf.download('0050.TW', start='2024-11-06', end='2025-01-09')
[*********************100%%**********************] 1 of 1 completed :
ta.add_momentum_ta() 會將指標計算結果添加到 DataFrame 後傳回 (也可以用一個變數來接收傳回值, 但沒必要) :
>>> ta.add_momentum_ta(df, high='High', low='Low', close='Close', volume='Volume')
檢視 DataFrame 欄位 :
>>> df.columns
Index(['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume', 'momentum_rsi',
'momentum_stoch_rsi', 'momentum_stoch_rsi_k', 'momentum_stoch_rsi_d',
'momentum_tsi', 'momentum_uo', 'momentum_stoch',
'momentum_stoch_signal', 'momentum_wr', 'momentum_ao', 'momentum_roc',
'momentum_ppo', 'momentum_ppo_signal', 'momentum_ppo_hist',
'momentum_pvo', 'momentum_pvo_signal', 'momentum_pvo_hist',
'momentum_kama'],
dtype='object')
可見 df 除了原來的價量欄位外, 後面新增了所有支援之動能指標欄位 :
動能指標 | df 指標欄位名稱 |
RSI (Relative Strength Index) | momentum_rsi |
Stochastic RSI | momentum_stoch_rsi, momentum_stoch_rsi_k, momentum_stoch_rsi_d |
TSI (True Strength Index) | momentum_tsi |
UO (Ultimate Oscillator) | momentum_uo |
Stochastic Oscillator | momentum_stoch, momentum_stoch_signal |
Williams %R | momentum_wr |
AO (Awesome Oscillator) | momentum_ao |
ROC (Rate of Change) | momentum_roc |
PPO (Percentage Price Oscillator) | momentum_ppo, momentum_ppo_signal, momentum_ppo_hist |
PVO (Percentage Volume Oscillator) | momentum_pvo, momentum_pvo_signal, momentum_pvo_hist |
KAMA (Kaufman’s Adaptive Moving Average) | momentum_kama |
檢視其中的 RSI 指標 :
>>> df['momentum_rsi']
Date
2024-11-06 NaN
2024-11-07 NaN
2024-11-08 NaN
2024-11-11 NaN
2024-11-12 NaN
2024-11-13 NaN
2024-11-14 NaN
2024-11-15 NaN
2024-11-18 NaN
2024-11-19 NaN
2024-11-20 NaN
2024-11-21 NaN
2024-11-22 NaN
2024-11-25 45.732159
2024-11-26 39.560536
2024-11-27 34.107863
2024-11-28 33.564358
2024-11-29 35.231532
2024-12-02 48.890462
2024-12-03 54.877909
2024-12-04 57.262711
2024-12-05 59.373997
2024-12-06 57.200326
2024-12-09 57.755502
2024-12-10 53.565209
2024-12-11 48.923488
2024-12-12 54.538551
2024-12-13 54.894578
2024-12-16 56.835996
2024-12-17 59.199976
2024-12-18 59.199976
2024-12-19 50.533601
2024-12-20 45.727610
2024-12-23 57.082949
2024-12-24 58.197052
2024-12-25 59.434195
2024-12-26 58.964392
2024-12-27 60.424311
2024-12-30 56.745051
2024-12-31 50.565547
2025-01-02 46.083754
2025-01-03 51.404401
2025-01-06 63.603546
2025-01-07 66.879390
2025-01-08 59.112553
Name: momentum_rsi, dtype: float64
可見這是用預設 window=14 計算出來的 RSI 指標, 可以用上面的 kbar.py 模組將 RSI 繪製到 K 線圖下方的副圖上 :
>>> import kbar
>>> kb=kbar.KBar(df)
>>> kb.addplot(df['momentum_rsi'], panel=2, ylabel='RSI') # 副圖 2
>>> kb.plot(volume=True, mav=5)
此處因為用 volume=True 開啟繪製成交量, 它預設占用 panel=1 的副圖, 故 RSI 要畫在 panel=2 的副圖 (否則會疊在一起), 結果如下 :
(4). 波動指標的快捷函式 ta.add_volatility_ta() :
呼叫 ta.add_volatility_ta() 來產生波動類型之指標數據, 其參數格式如下 (與趨勢類相同) :
ta.add_volatility_ta(
df: pd.DataFrame, # 價量資料 (必要)
high: str, # 最高價欄名 (必要)
low: str, # 最低價欄名 (必要)
close: str, # 收盤價欄名 (必要)
fillna: bool = False, # 是否在技術指標計算後自動填充缺失值
colprefix: str = "" # 在新增的技術指標攔名前添加前綴以避免欄名衝突
)
此函式會以預設 window 參數值去計算所有波動類型之指標.
為了清楚看出此函式新增了那些欄位, 重新下載價量資料讓 df 回復為原始欄位 :
>>> df=yf.download('0050.TW', start='2024-11-06', end='2025-01-09')
[*********************100%%**********************] 1 of 1 completed :
ta.add_volatility_ta() 會將指標計算結果添加到 DataFrame 後傳回 (也可以用一個變數來接收傳回值, 但沒必要) :
>>> ta.add_volatility_ta(df, high='High', low='Low', close='Close')
檢視 DataFrame 欄位 :
>>> df.columns
Index(['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume', 'volatility_bbm',
'volatility_bbh', 'volatility_bbl', 'volatility_bbw', 'volatility_bbp',
'volatility_bbhi', 'volatility_bbli', 'volatility_kcc',
'volatility_kch', 'volatility_kcl', 'volatility_kcw', 'volatility_kcp',
'volatility_kchi', 'volatility_kcli', 'volatility_dcl',
'volatility_dch', 'volatility_dcm', 'volatility_dcw', 'volatility_dcp',
'volatility_atr', 'volatility_ui'],
dtype='object')
可見 df 除了原來的價量欄位外, 後面新增了所有支援之波動指標欄位 :
波動指標 (Volatility) | df 指標欄位名稱 |
Bollinger Bands | volatility_bbm, volatility_bbh, volatility_bbl, volatility_bbw, volatility_bbp, volatility_bbhi, volatility_bbli |
Keltner Channel | volatility_kcc, volatility_kch, volatility_kcl, volatility_kcw, volatility_kcp, volatility_kchi, volatility_kcli |
Donchian Channel | volatility_dcl, volatility_dch, volatility_dcm, volatility_dcw, volatility_dcp |
ATR (Average True Range) | volatility_atr |
UI (Ulcer Index) | volatility_ui |
以布林傑通道 (Bollinger Bands) 指標為例, 它是以上下限與中線來判斷價格的波動範圍和潛在的支撐或壓力區域, 指標欄位如下 :
- volatility_bbm (中線) : 收盤價的移動平均線 (SMA, 預設 20 日)
- volatility_bbh (上限) : 中線加上某個標準差 (預設 2 )
- volatility_bbl (下限) : 中線減掉某個標準差 (預設 2 )
布林傑通道指標上下限與中線 :
>>> df['volatility_bbm'] # 中線 (20 日 SMA)
Date
2024-11-06 NaN
2024-11-07 NaN
2024-11-08 NaN
2024-11-11 NaN
2024-11-12 NaN
2024-11-13 NaN
2024-11-14 NaN
2024-11-15 NaN
2024-11-18 NaN
2024-11-19 NaN
2024-11-20 NaN
2024-11-21 NaN
2024-11-22 NaN
2024-11-25 NaN
2024-11-26 NaN
2024-11-27 NaN
2024-11-28 NaN
2024-11-29 NaN
2024-12-02 NaN
2024-12-03 192.297501
2024-12-04 192.310001
2024-12-05 192.262502
2024-12-06 192.100002
2024-12-09 191.945001
2024-12-10 191.975002
2024-12-11 191.982501
2024-12-12 192.190001
2024-12-13 192.337501
2024-12-16 192.660001
2024-12-17 192.902502
2024-12-18 193.185002
2024-12-19 193.437502
2024-12-20 193.415002
2024-12-23 193.660001
2024-12-24 194.057501
2024-12-25 194.622501
2024-12-26 195.195000
2024-12-27 195.777500
2024-12-30 196.082500
2024-12-31 196.155000
2025-01-02 196.085001
2025-01-03 196.060001
2025-01-06 196.380000
2025-01-07 196.800000
2025-01-08 197.137500
Name: volatility_bbm, dtype: float64
>>> df['volatility_bbh'] # 上限 (2 個標準差)
Date
2024-11-06 NaN
2024-11-07 NaN
2024-11-08 NaN
2024-11-11 NaN
2024-11-12 NaN
2024-11-13 NaN
2024-11-14 NaN
2024-11-15 NaN
2024-11-18 NaN
2024-11-19 NaN
2024-11-20 NaN
2024-11-21 NaN
2024-11-22 NaN
2024-11-25 NaN
2024-11-26 NaN
2024-11-27 NaN
2024-11-28 NaN
2024-11-29 NaN
2024-12-02 NaN
2024-12-03 199.240373
2024-12-04 199.274597
2024-12-05 199.097987
2024-12-06 198.422342
2024-12-09 197.699815
2024-12-10 197.778404
2024-12-11 197.790277
2024-12-12 198.137401
2024-12-13 198.437816
2024-12-16 198.839368
2024-12-17 199.372313
2024-12-18 199.866401
2024-12-19 199.898141
2024-12-20 199.884012
2024-12-23 200.317523
2024-12-24 200.706958
2024-12-25 200.707604
2024-12-26 200.304884
2024-12-27 199.634244
2024-12-30 199.545919
2024-12-31 199.525593
2025-01-02 199.567542
2025-01-03 199.537442
2025-01-06 200.748224
2025-01-07 202.386677
2025-01-08 202.962262
Name: volatility_bbh, dtype: float64
>>> df['volatility_bbl'] # 下限 (2 個標準差)
Date
2024-11-06 NaN
2024-11-07 NaN
2024-11-08 NaN
2024-11-11 NaN
2024-11-12 NaN
2024-11-13 NaN
2024-11-14 NaN
2024-11-15 NaN
2024-11-18 NaN
2024-11-19 NaN
2024-11-20 NaN
2024-11-21 NaN
2024-11-22 NaN
2024-11-25 NaN
2024-11-26 NaN
2024-11-27 NaN
2024-11-28 NaN
2024-11-29 NaN
2024-12-02 NaN
2024-12-03 185.354630
2024-12-04 185.345406
2024-12-05 185.427016
2024-12-06 185.777661
2024-12-09 186.190188
2024-12-10 186.171599
2024-12-11 186.174726
2024-12-12 186.242600
2024-12-13 186.237185
2024-12-16 186.480634
2024-12-17 186.432690
2024-12-18 186.503604
2024-12-19 186.976862
2024-12-20 186.945992
2024-12-23 187.002480
2024-12-24 187.408045
2024-12-25 188.537398
2024-12-26 190.085117
2024-12-27 191.920756
2024-12-30 192.619081
2024-12-31 192.784407
2025-01-02 192.602459
2025-01-03 192.582560
2025-01-06 192.011776
2025-01-07 191.213323
2025-01-08 191.312738
Name: volatility_bbl, dtype: float64
可以用上面的 kbar.py 模組將布林傑通道的中線與上下限以疊圖方式繪製到 K 線圖上 :
>>> import kbar
>>> kb=kbar.KBar(df)
>>> kb.addplot(df['volatility_bbh'], color='red', width=1) # 上限疊圖
>>> kb.addplot(df['volatility_bbm'], color='blue', width=1) # 中線疊圖
>>> kb.addplot(df['volatility_bbl'], color='green', width=1) # 下限疊圖
>>> kb.plot(volume=True)
此處因為要套疊布林傑通道線, 因此不宜傳入 mav 參數以免混淆, 結果如下 :
(5). 量能指標的快捷函式 ta.add_volume_ta() :
呼叫 ta.add_volume_ta() 來產生量能類型之指標數據, 其參數格式如下 (與動能類相同) :
ta.add_volume_ta(
df: pd.DataFrame, # 價量資料 (必要)
high: str, # 最高價欄名 (必要)
low: str, # 最低價欄名 (必要)
close: str, # 收盤價欄名 (必要)
volume: str, # 成交量 (必要) fillna: bool = False, # 是否在技術指標計算後自動填充缺失值
colprefix: str = "" # 在新增的技術指標攔名前添加前綴以避免欄名衝突
)
此函式會以預設 window 參數值去計算所有量能類型之指標數據.
為了清楚看出此函式新增了那些欄位, 重新下載價量資料讓 df 回復為原始欄位 :
>>> df=yf.download('0050.TW', start='2024-11-06', end='2025-01-09')
[*********************100%%**********************] 1 of 1 completed :
ta.add_volume_ta() 會將指標計算結果添加到 DataFrame 後傳回 (也可以用一個變數來接收傳回值, 但沒必要) :
>>> ta.add_volume_ta(df, high='High', low='Low', close='Close', volume='Volume')
檢視 DataFrame 欄位 :
>>> df.columns
Index(['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume', 'volume_adi',
'volume_obv', 'volume_cmf', 'volume_fi', 'volume_em', 'volume_sma_em',
'volume_vpt', 'volume_vwap', 'volume_mfi', 'volume_nvi'],
dtype='object')
可見 df 除了原來的價量欄位外, 後面新增了所有支援之量能指標欄位 :
量能指標 (Volume) | df 指標欄位名稱 |
Accumulation/Distribution Line (ADL) | volume_adi |
On-Balance Volume (OBV) | volume_obv |
Chaikin Money Flow (CMF) | volume_cmf |
Force Index (FI) | volume_fi |
Ease of Movement (EM) | volume_em |
Smoothed Ease of Movement (SMA_EM) | volume_sma_em |
Volume Price Trend (VPT) | volume_vpt |
Volume Weighted Average Price (VWAP) | volume_vwap |
Money Flow Index (MFI) | volume_mfi |
Negative Volume Index (NVI) | volume_nvi |
檢視其中的 OBV 指標 :
>>> df['volume_obv']
Date
2024-11-06 16706376
2024-11-07 30204928
2024-11-08 43155079
2024-11-11 55519092
2024-11-12 29247005
2024-11-13 20052415
2024-11-14 7905800
2024-11-15 15291381
2024-11-18 1896865
2024-11-19 9515186
2024-11-20 9437186
2024-11-21 -6439431
2024-11-22 1526156
2024-11-25 -6300507
2024-11-26 -17691329
2024-11-27 -31764015
2024-11-28 -44873129
2024-11-29 -36744909
2024-12-02 -26200831
2024-12-03 -16247725
2024-12-04 -9792476
2024-12-05 -2346273
2024-12-06 -9155779
2024-12-09 -4515915
2024-12-10 -8993222
2024-12-11 -15707911
2024-12-12 -10680670
2024-12-13 -6160243
2024-12-16 1183349
2024-12-17 10477578
2024-12-18 17031455
2024-12-19 3986408
2024-12-20 -7136986
2024-12-23 4039080
2024-12-24 12234982
2024-12-25 18141105
2024-12-26 13337544
2024-12-27 20324961
2024-12-30 11647695
2024-12-31 3811161
2025-01-02 -8986541
2025-01-03 -1873170
2025-01-06 22754623
2025-01-07 38698467
2025-01-08 26842750
Name: volume_obv, dtype: int64
這與上面呼叫個別指標函式 ta.volume.on_balance_volume() 的結果是一樣的.
檢視 MFI 指標 :
>>> df['volume_mfi']
Date
2024-11-06 NaN
2024-11-07 NaN
2024-11-08 NaN
2024-11-11 NaN
2024-11-12 NaN
2024-11-13 NaN
2024-11-14 NaN
2024-11-15 NaN
2024-11-18 NaN
2024-11-19 NaN
2024-11-20 NaN
2024-11-21 NaN
2024-11-22 NaN
2024-11-25 39.301682
2024-11-26 36.522781
2024-11-27 27.843909
2024-11-28 19.482690
2024-11-29 25.247484
2024-12-02 35.842102
2024-12-03 42.918545
2024-12-04 49.655030
2024-12-05 49.740230
2024-12-06 52.229974
2024-12-09 51.119383
2024-12-10 49.334007
2024-12-11 53.017548
2024-12-12 51.856243
2024-12-13 46.397760
2024-12-16 54.858813
2024-12-17 66.148226
2024-12-18 70.160985
2024-12-19 59.032024
2024-12-20 48.676280
2024-12-23 49.330576
2024-12-24 50.220182
2024-12-25 43.808475
2024-12-26 49.368843
2024-12-27 50.541067
2024-12-30 48.551503
2024-12-31 48.016515
2025-01-02 40.670406
2025-01-03 45.672339
2025-01-06 52.673952
2025-01-07 55.040936
2025-01-08 52.999103
Name: volume_mfi, dtype: float64
這與上面呼叫個別指標函式 ta.volume.money_flow_index() 的結果是一樣的.
用上面的 kbar.py 模組將 OBV 與 MFI 分別繪製在 K 線圖下方的副圖 2 與副圖 3 :
>>> import kbar
>>> kb=kbar.KBar(df)
>>> kb.addplot(df['volume_obv'] , panel=2, ylabel='OBV') # 副圖 2
>>> kb.addplot(df['volume_mfi'] , panel=3, ylabel='MFI') # 副圖 3
>>> kb.plot(volume=True, mav=5)
結果如下 :
(6). 其它指標的快捷函式 ta.add_others_ta() :
呼叫 ta.others_ta() 來產生其它類型之指標數據 (報酬率), 其參數格式如下 :
ta.add_volume_ta(
df: pd.DataFrame, # 價量資料 (必要)
close: str, # 收盤價欄名 (必要)
fillna: bool = False, # 是否在技術指標計算後自動填充缺失值
colprefix: str = "" # 在新增的技術指標攔名前添加前綴以避免欄名衝突
)
可見此函式只需要指定收盤價欄位即可, 用來計算三種報酬率數據.
為了清楚看出此函式新增了那些欄位, 重新下載價量資料讓 df 回復為原始欄位 :
>>> df=yf.download('0050.TW', start='2024-11-06', end='2025-01-09')
[*********************100%%**********************] 1 of 1 completed :
ta.add_others_ta() 會將指標計算結果添加到 DataFrame 後傳回 (也可以用一個變數來接收傳回值, 但沒必要) :
>>> ta.add_others_ta(df, close='Close')
檢視 DataFrame 欄位 :
>>> df.columns
Index(['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume', 'others_dr',
'others_dlr', 'others_cr'],
dtype='object')
可見 df 除了原來的價量欄位外, 後面新增了三個指標欄位 :
其它指標 (Others) | df 指標欄位名稱 |
Daily Return (dr) 每日報酬率 | others_dr |
Daily Log Return (dlr) 每日對數報酬率 | others_dlr |
Cumulative Return (cr) 累積報酬率 | others_cr |
檢視此三種報酬率欄位 :
>>> df['others_dr'] # 日報酬率
Date
2024-11-06 NaN
2024-11-07 1.152664
2024-11-08 0.785010
2024-11-11 0.050254
2024-11-12 -2.561530
2024-11-13 -0.644330
2024-11-14 -0.907912
2024-11-15 0.706809
2024-11-18 -1.403697
2024-11-19 1.370950
2024-11-20 -0.416126
2024-11-21 -1.096887
2024-11-22 1.954052
2024-11-25 -0.362599
2024-11-26 -1.299714
2024-11-27 -1.448512
2024-11-28 -0.160344
2024-11-29 0.240898
2024-12-02 2.376500
2024-12-03 1.356289
2024-12-04 0.591865
2024-12-05 0.537223
2024-12-06 -0.381679
2024-12-09 0.127714
2024-12-10 -0.714283
2024-12-11 -0.873593
2024-12-12 1.166408
2024-12-13 0.076869
2024-12-16 0.409628
2024-12-17 0.509944
2024-12-18 0.000000
2024-12-19 -1.369869
2024-12-20 -0.925920
2024-12-23 2.414327
2024-12-24 0.278836
2024-12-25 0.303332
2024-12-26 -0.075602
2024-12-27 0.327866
2024-12-30 -0.553037
2024-12-31 -1.036402
2025-01-02 -0.868453
2025-01-03 1.004894
2025-01-06 3.137752
2025-01-07 1.113035
2025-01-08 -1.492166
Name: others_dr, dtype: float64
>>> df['others_dlr'] # 對數報酬率
Date
2024-11-06 NaN
2024-11-07 1.146071
2024-11-08 0.781945
2024-11-11 0.050242
2024-11-12 -2.594908
2024-11-13 -0.646415
2024-11-14 -0.912058
2024-11-15 0.704323
2024-11-18 -1.413642
2024-11-19 1.361637
2024-11-20 -0.416995
2024-11-21 -1.102948
2024-11-22 1.935205
2024-11-25 -0.363258
2024-11-26 -1.308234
2024-11-27 -1.459105
2024-11-28 -0.160472
2024-11-29 0.240608
2024-12-02 2.348701
2024-12-03 1.347174
2024-12-04 0.590120
2024-12-05 0.535785
2024-12-06 -0.382410
2024-12-09 0.127632
2024-12-10 -0.716846
2024-12-11 -0.877431
2024-12-12 1.159657
2024-12-13 0.076839
2024-12-16 0.408791
2024-12-17 0.508648
2024-12-18 0.000000
2024-12-19 -1.379338
2024-12-20 -0.930233
2024-12-23 2.385643
2024-12-24 0.278447
2024-12-25 0.302873
2024-12-26 -0.075630
2024-12-27 0.327329
2024-12-30 -0.554572
2024-12-31 -1.041810
2025-01-02 -0.872246
2025-01-03 0.999879
2025-01-06 3.089531
2025-01-07 1.106886
2025-01-08 -1.503411
Name: others_dlr, dtype: float64
>>> df['others_cr'] # 累積報酬率
Date
2024-11-06 0.000000
2024-11-07 1.152664
2024-11-08 1.946723
2024-11-11 1.997956
2024-11-12 -0.614753
2024-11-13 -1.255121
2024-11-14 -2.151638
2024-11-15 -1.460036
2024-11-18 -2.843239
2024-11-19 -1.511269
2024-11-20 -1.921107
2024-11-21 -2.996922
2024-11-22 -1.101431
2024-11-25 -1.460036
2024-11-26 -2.740774
2024-11-27 -4.149586
2024-11-28 -4.303276
2024-11-29 -4.072744
2024-12-02 -1.793033
2024-12-03 -0.461062
2024-12-04 0.128074
2024-12-05 0.665985
2024-12-06 0.281764
2024-12-09 0.409838
2024-12-10 -0.307372
2024-12-11 -1.178280
2024-12-12 -0.025616
2024-12-13 0.051233
2024-12-16 0.461070
2024-12-17 0.973365
2024-12-18 0.973365
2024-12-19 -0.409838
2024-12-20 -1.331963
2024-12-23 1.050206
2024-12-24 1.331970
2024-12-25 1.639343
2024-12-26 1.562502
2024-12-27 1.895490
2024-12-30 1.331970
2024-12-31 0.281764
2025-01-02 -0.589136
2025-01-03 0.409838
2025-01-06 3.560449
2025-01-07 4.713113
2025-01-08 3.150619
Name: others_cr, dtype: float64
在使用 pyfolio 等策略風險評估工具時就需要用到 others_dr 欄位的日報酬率數據 (較長期的風險評估則需要使用調整後的收盤價 Adj Close 較精確), 參考 :
(7). 呼叫 add_all_ta_features() 計算全部 80 個指標 :
這個函式可說是 ta 的超級函式, 可一次計算出全部 80 個指標,
其參數格式如下 (與動能類相同) :
ta.add_all_ta_features(
df: pd.DataFrame, # 價量資料 (必要)
open: str, # 開盤價欄名 (必要)
high: str, # 最高價欄名 (必要)
low: str, # 最低價欄名 (必要)
close: str, # 收盤價欄名 (必要)
volume: str, # 成交量 (必要) fillna: bool = False, # 是否在技術指標計算後自動填充缺失值
colprefix: str = "" # 在新增的技術指標攔名前添加前綴以避免欄名衝突
)
可見呼叫此函式時, OHLCV 五個欄位名稱都必須傳入, 它會以預設 window 參數值去計算所有類型之全部 80 個指標數據.
為了清楚看出此函式新增了那些欄位, 重新下載價量資料讓 df 回復為原始欄位 :
>>> df=yf.download('0050.TW', start='2024-11-06', end='2025-01-09')
[*********************100%%**********************] 1 of 1 completed :
ta.add_volume_ta() 會將指標計算結果添加到 DataFrame 後傳回 (也可以用一個變數來接收傳回值, 但沒必要) :
>>> ta.add_all_ta_features(df, open='Open', high='High', low='Low', close='Close', volume='Volume')
檢視 DataFrame 欄位 :
>>> df.columns
Index(['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume', 'volume_adi',
'volume_obv', 'volume_cmf', 'volume_fi', 'volume_em', 'volume_sma_em',
'volume_vpt', 'volume_vwap', 'volume_mfi', 'volume_nvi',
'volatility_bbm', 'volatility_bbh', 'volatility_bbl', 'volatility_bbw',
'volatility_bbp', 'volatility_bbhi', 'volatility_bbli',
'volatility_kcc', 'volatility_kch', 'volatility_kcl', 'volatility_kcw',
'volatility_kcp', 'volatility_kchi', 'volatility_kcli',
'volatility_dcl', 'volatility_dch', 'volatility_dcm', 'volatility_dcw',
'volatility_dcp', 'volatility_atr', 'volatility_ui', 'trend_macd',
'trend_macd_signal', 'trend_macd_diff', 'trend_sma_fast',
'trend_sma_slow', 'trend_ema_fast', 'trend_ema_slow',
'trend_vortex_ind_pos', 'trend_vortex_ind_neg', 'trend_vortex_ind_diff',
'trend_trix', 'trend_mass_index', 'trend_dpo', 'trend_kst',
'trend_kst_sig', 'trend_kst_diff', 'trend_ichimoku_conv',
'trend_ichimoku_base', 'trend_ichimoku_a', 'trend_ichimoku_b',
'trend_stc', 'trend_adx', 'trend_adx_pos', 'trend_adx_neg', 'trend_cci',
'trend_visual_ichimoku_a', 'trend_visual_ichimoku_b', 'trend_aroon_up',
'trend_aroon_down', 'trend_aroon_ind', 'trend_psar_up',
'trend_psar_down', 'trend_psar_up_indicator',
'trend_psar_down_indicator', 'momentum_rsi', 'momentum_stoch_rsi',
'momentum_stoch_rsi_k', 'momentum_stoch_rsi_d', 'momentum_tsi',
'momentum_uo', 'momentum_stoch', 'momentum_stoch_signal', 'momentum_wr',
'momentum_ao', 'momentum_roc', 'momentum_ppo', 'momentum_ppo_signal',
'momentum_ppo_hist', 'momentum_pvo', 'momentum_pvo_signal',
'momentum_pvo_hist', 'momentum_kama', 'others_dr', 'others_dlr',
'others_cr'],
dtype='object')
可見新增的欄位就是上面五種類型的全部指標.
沒有留言 :
張貼留言