PANDAS技術分析( Pandas TA )是一個易於使用的庫,它利用PANDAS包具有130多個指標和實用程序功能以及60多個TA Lib Candlestick模式。包括許多常用指標,例如:蠟燭圖案( CDL_PARTTEN ),簡單移動平均( SMA )移動平均平均收斂差異( MACD ),船體指數移動平均平均值( HMA ), Bollinger帶( BBANDS ),平衡量( OBB) ) , Aroon&Aroon振盪器( Aroon ),擠壓(擠壓)等。
注意:必須安裝ta lib才能使用所有燭台圖案。 pip install TA-Lib
。如果未安裝ta lib ,則只有內置的燭台圖案可用。
talib=False
禁用每個指示器禁用。ta.stdev(df["close"], length=30, talib=False)
。/pandas_ta/custom.py
下的import_dir
文檔。ta.tsignals
方法進行回歸。lookahead=False
to disable。Pandas ta檢查用戶是否安裝了一些常見的交易軟件包,包括但不限於: ta lib , vector bt , yfinance ...其中大部分是實驗性的,並且可能會破裂,直到它穩定更多為止。
help(ta.ticker)
和help(ta.yf)
和下面的示例。pip
版本是最後一個穩定版本。版本: 0.3.14b
$ pip install pandas_ta
最佳選擇!版本: 0.3.14b
$ pip install -U git+https://github.com/twopirllc/pandas-ta
這是可能具有錯誤和其他不希望的副作用的開發版本。自身使用!
$ pip install -U git+https://github.com/twopirllc/pandas-ta.git@development
import pandas as pd
import pandas_ta as ta
df = pd . DataFrame () # Empty DataFrame
# Load data
df = pd . read_csv ( "path/to/symbol.csv" , sep = "," )
# OR if you have yfinance installed
df = df . ta . ticker ( "aapl" )
# VWAP requires the DataFrame index to be a DatetimeIndex.
# Replace "datetime" with the appropriate column from your DataFrame
df . set_index ( pd . DatetimeIndex ( df [ "datetime" ]), inplace = True )
# Calculate Returns and append to the df DataFrame
df . ta . log_return ( cumulative = True , append = True )
df . ta . percent_return ( cumulative = True , append = True )
# New Columns with results
df . columns
# Take a peek
df . tail ()
# vv Continue Post Processing vv
一些指標參數已被重新排序以保持一致性。使用help(ta.indicator_name)
以獲取更多信息或提出拉動請求以改進文檔。
import pandas as pd
import pandas_ta as ta
# Create a DataFrame so 'ta' can be used.
df = pd . DataFrame ()
# Help about this, 'ta', extension
help ( df . ta )
# List of all indicators
df . ta . indicators ()
# Help about an indicator such as bbands
help ( ta . bbands )
感謝您使用Pandas TA !
$ pip install -U git+https://github.com/twopirllc/pandas-ta
謝謝您的貢獻!
Pandas TA有三個主要的“樣式”處理用於您的用例和/或要求的技術指標。它們是:標準,數據幀擴展和熊貓TA策略。每種都有越來越多的抽像水平以易於使用。隨著您對大熊貓TA的熟悉,使用Pandas TA策略的簡單性和速度可能會變得更加明顯。此外,您可以通過鏈接或組成創建自己的指標。最後,每個指示器要么返回大寫下的系列或數據框,無論樣式如何。
您明確定義輸入列並照顧輸出。
sma10 = ta.sma(df["Close"], length=10)
SMA_10
的系列donchiandf = ta.donchian(df["HIGH"], df["low"], lower_length=10, upper_length=15)
DC_10_15
和列名稱的數據框: DCL_10_15, DCM_10_15, DCU_10_15
ema10_ohlc4 = ta.ema(ta.ohlc4(df["Open"], df["High"], df["Low"], df["Close"]), length=10)
EMA_10
的系列。如果需要,您可能需要唯一的命名。呼叫df.ta
將自動將OHLCVA較小為OHLCVA :開放,高,低,關閉,音量, adj_close 。默認情況下, df.ta
將使用OHLCVA進行指示參數,以刪除直接指定輸入列的需要。
sma10 = df.ta.sma(length=10)
SMA_10
的系列ema10_ohlc4 = df.ta.ema(close=df.ta.ohlc4(), length=10, suffix="OHLC4")
EMA_10_OHLC4
close=df.ta.ohlc4()
。donchiandf = df.ta.donchian(lower_length=10, upper_length=15)
DC_10_15
和列名稱的數據框: DCL_10_15, DCM_10_15, DCU_10_15
與最後三個示例相同,但將結果直接附加到DataFrame df
上。
df.ta.sma(length=10, append=True)
df
列名稱: SMA_10
。df.ta.ema(close=df.ta.ohlc4(append=True), length=10, suffix="OHLC4", append=True)
close=df.ta.ohlc4()
。df.ta.donchian(lower_length=10, upper_length=15, append=True)
df
: DCL_10_15, DCM_10_15, DCU_10_15
。熊貓策略是由策略方法運行的一組指標。所有策略都使用MulitProcessing,除非使用col_names
參數(見下文)。下一節中列出了不同類型的策略。
# (1) Create the Strategy
MyStrategy = ta . Strategy (
name = "DCSMA10" ,
ta = [
{ "kind" : "ohlc4" },
{ "kind" : "sma" , "length" : 10 },
{ "kind" : "donchian" , "lower_length" : 10 , "upper_length" : 15 },
{ "kind" : "ema" , "close" : "OHLC4" , "length" : 10 , "suffix" : "OHLC4" },
]
)
# (2) Run the Strategy
df . ta . strategy ( MyStrategy , ** kwargs )
策略類是一種使用數據類命名和分組您喜歡的TA指標的簡單方法。 Pandas Ta提供了兩種預先建立的基本策略,可以幫助您入門: Allstrategy和Commandate 。策略可以像使用組成/鏈接一樣簡單,也可以根據需要盡可能複雜。
df
上。有關指標組成/鏈接在內的示例,請參見pandas ta策略示例筆記本。
{"kind": "indicator name"}
屬性,則在Pandas TA消耗時,策略將失敗。切記檢查您的拼寫。 # Running the Builtin CommonStrategy as mentioned above
df . ta . strategy ( ta . CommonStrategy )
# The Default Strategy is the ta.AllStrategy. The following are equivalent:
df . ta . strategy ()
df . ta . strategy ( "All" )
df . ta . strategy ( ta . AllStrategy )
# List of indicator categories
df . ta . categories
# Running a Categorical Strategy only requires the Category name
df . ta . strategy ( "Momentum" ) # Default values for all Momentum indicators
df . ta . strategy ( "overlap" , length = 42 ) # Override all Overlap 'length' attributes
# Create your own Custom Strategy
CustomStrategy = ta . Strategy (
name = "Momo and Volatility" ,
description = "SMA 50,200, BBANDS, RSI, MACD and Volume SMA 20" ,
ta = [
{ "kind" : "sma" , "length" : 50 },
{ "kind" : "sma" , "length" : 200 },
{ "kind" : "bbands" , "length" : 20 },
{ "kind" : "rsi" },
{ "kind" : "macd" , "fast" : 8 , "slow" : 21 },
{ "kind" : "sma" , "close" : "volume" , "length" : 20 , "prefix" : "VOLUME" },
]
)
# To run your "Custom Strategy"
df . ta . strategy ( CustomStrategy )
Pandas TA策略方法利用多處理來進行所有策略類型的批量處理,但一個例外!當使用col_names
參數重命名結果列時, ta
數組中的指示器將按順序運行。
# VWAP requires the DataFrame index to be a DatetimeIndex.
# * Replace "datetime" with the appropriate column from your DataFrame
df . set_index ( pd . DatetimeIndex ( df [ "datetime" ]), inplace = True )
# Runs and appends all indicators to the current DataFrame by default
# The resultant DataFrame will be large.
df . ta . strategy ()
# Or the string "all"
df . ta . strategy ( "all" )
# Or the ta.AllStrategy
df . ta . strategy ( ta . AllStrategy )
# Use verbose if you want to make sure it is running.
df . ta . strategy ( verbose = True )
# Use timed if you want to see how long it takes to run.
df . ta . strategy ( timed = True )
# Choose the number of cores to use. Default is all available cores.
# For no multiprocessing, set this value to 0.
df . ta . cores = 4
# Maybe you do not want certain indicators.
# Just exclude (a list of) them.
df . ta . strategy ( exclude = [ "bop" , "mom" , "percent_return" , "wcp" , "pvi" ], verbose = True )
# Perhaps you want to use different values for indicators.
# This will run ALL indicators that have fast or slow as parameters.
# Check your results and exclude as necessary.
df . ta . strategy ( fast = 10 , slow = 50 , verbose = True )
# Sanity check. Make sure all the columns are there
df . columns
請記住,這些不會利用多處理
NonMPStrategy = ta . Strategy (
name = "EMAs, BBs, and MACD" ,
description = "Non Multiprocessing Strategy by rename Columns" ,
ta = [
{ "kind" : "ema" , "length" : 8 },
{ "kind" : "ema" , "length" : 21 },
{ "kind" : "bbands" , "length" : 20 , "col_names" : ( "BBL" , "BBM" , "BBU" )},
{ "kind" : "macd" , "fast" : 8 , "slow" : 21 , "col_names" : ( "MACD" , "MACD_H" , "MACD_S" )}
]
)
# Run it
df . ta . strategy ( NonMPStrategy )
# Set ta to default to an adjusted column, 'adj_close', overriding default 'close'.
df . ta . adjusted = "adj_close"
df . ta . sma ( length = 10 , append = True )
# To reset back to 'close', set adjusted back to None.
df . ta . adjusted = None
# List of Pandas TA categories.
df . ta . categories
# Set the number of cores to use for strategy multiprocessing
# Defaults to the number of cpus you have.
df . ta . cores = 4
# Set the number of cores to 0 for no multiprocessing.
df . ta . cores = 0
# Returns the number of cores you set or your default number of cpus.
df . ta . cores
# The 'datetime_ordered' property returns True if the DataFrame
# index is of Pandas datetime64 and df.index[0] < df.index[-1].
# Otherwise it returns False.
df . ta . datetime_ordered
# Sets the Exchange to use when calculating the last_run property. Default: "NYSE"
df . ta . exchange
# Set the Exchange to use.
# Available Exchanges: "ASX", "BMF", "DIFX", "FWB", "HKE", "JSE", "LSE", "NSE", "NYSE", "NZSX", "RTS", "SGX", "SSE", "TSE", "TSX"
df . ta . exchange = "LSE"
# Returns the time Pandas TA was last run as a string.
df . ta . last_run
# The 'reverse' is a helper property that returns the DataFrame
# in reverse order.
df . ta . reverse
# Applying a prefix to the name of an indicator.
prehl2 = df . ta . hl2 ( prefix = "pre" )
print ( prehl2 . name ) # "pre_HL2"
# Applying a suffix to the name of an indicator.
endhl2 = df . ta . hl2 ( suffix = "post" )
print ( endhl2 . name ) # "HL2_post"
# Applying a prefix and suffix to the name of an indicator.
bothhl2 = df . ta . hl2 ( prefix = "pre" , suffix = "post" )
print ( bothhl2 . name ) # "pre_HL2_post"
# Returns the time range of the DataFrame as a float.
# By default, it returns the time in "years"
df . ta . time_range
# Available time_ranges include: "years", "months", "weeks", "days", "hours", "minutes". "seconds"
df . ta . time_range = "days"
df . ta . time_range # prints DataFrame time in "days" as float
# Sets the DataFrame index to UTC format.
df . ta . to_utc
import numpy as np
# Add constant '1' to the DataFrame
df . ta . constants ( True , [ 1 ])
# Remove constant '1' to the DataFrame
df . ta . constants ( False , [ 1 ])
# Adding constants for charting
import numpy as np
chart_lines = np . append ( np . arange ( - 4 , 5 , 1 ), np . arange ( - 100 , 110 , 10 ))
df . ta . constants ( True , chart_lines )
# Removing some constants from the DataFrame
df . ta . constants ( False , np . array ([ - 60 , - 40 , 40 , 60 ]))
# Prints the indicators and utility functions
df . ta . indicators ()
# Returns a list of indicators and utility functions
ind_list = df . ta . indicators ( as_list = True )
# Prints the indicators and utility functions that are not in the excluded list
df . ta . indicators ( exclude = [ "cg" , "pgo" , "ui" ])
# Returns a list of the indicators and utility functions that are not in the excluded list
smaller_list = df . ta . indicators ( exclude = [ "cg" , "pgo" , "ui" ], as_list = True )
# Download Chart history using yfinance. (pip install yfinance) https://github.com/ranaroussi/yfinance
# It uses the same keyword arguments as yfinance (excluding start and end)
df = df . ta . ticker ( "aapl" ) # Default ticker is "SPY"
# Period is used instead of start/end
# Valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max
# Default: "max"
df = df . ta . ticker ( "aapl" , period = "1y" ) # Gets this past year
# History by Interval by interval (including intraday if period < 60 days)
# Valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo
# Default: "1d"
df = df . ta . ticker ( "aapl" , period = "1y" , interval = "1wk" ) # Gets this past year in weeks
df = df . ta . ticker ( "aapl" , period = "1mo" , interval = "1h" ) # Gets this past month in hours
# BUT WAIT!! THERE'S MORE!!
help ( ta . yf )
不大膽的模式,需要安裝ta-lib: pip install TA-Lib
# Get all candle patterns (This is the default behaviour)
df = df . ta . cdl_pattern ( name = "all" )
# Get only one pattern
df = df . ta . cdl_pattern ( name = "doji" )
# Get some patterns
df = df . ta . cdl_pattern ( name = [ "doji" , "inside" ])
ta.linreg(series, r=True)
lazybear=True
df.ta.strategy()
。移動平均收斂差異(MACD) |
---|
help(ta.ichimoku)
。lookahead=False
drops chikou跨度列,以防止潛在的數據洩漏。簡單的移動平均值(SMA)和布林樂隊(Bands) |
---|
使用參數:累積=為累積結果。
返回百分比(累積),簡單移動平均值(SMA) |
---|
Z得分 |
---|
lookahead=False
至“禁用中心”並刪除潛在的數據洩漏。平均方向運動指數(ADX) |
---|
平均真實範圍(ATR) |
---|
平衡體積(OBV) |
---|
性能指標是該軟件包的新補充,因此可能是不可靠的。自行使用。這些指標返回浮點,不屬於數據框架擴展名。它們被稱為標準方式。例如:
import pandas_ta as ta
result = ta . cagr ( df . close )
為了更輕鬆地與vectorbt的from_signals
方法集成在一起,已用ta.trend_return
方法已被ta.tsignals
方法替換,以簡化交易信號的生成。有關全面的示例,請參見示例目錄中的pandas ta的示例jupyter筆記本電腦vectorbt回測。
import pandas as pd
import pandas_ta as ta
import vectorbt as vbt
df = pd . DataFrame (). ta . ticker ( "AAPL" ) # requires 'yfinance' installed
# Create the "Golden Cross"
df [ "GC" ] = df . ta . sma ( 50 , append = True ) > df . ta . sma ( 200 , append = True )
# Create boolean Signals(TS_Entries, TS_Exits) for vectorbt
golden = df . ta . tsignals ( df . GC , asbool = True , append = True )
# Sanity Check (Ensure data exists)
print ( df )
# Create the Signals Portfolio
pf = vbt . Portfolio . from_signals ( df . close , entries = golden . TS_Entries , exits = golden . TS_Exits , freq = "D" , init_cash = 100_000 , fees = 0.0025 , slippage = 0.0025 )
# Print Portfolio Stats and Return Stats
print ( pf . stats ())
print ( pf . returns_stats ())
mamode
kwarg ,並使用移動平均工具函數ta.ma()
進行了更多移動的平均選擇。為簡單起見,所有選擇都是單源移動平均值。這主要是具有mamode
Kwarg的指標使用的內部實用程序。這包括指標: ACCBAND , AMAT , AOBV , ATR , BBANDS , BANG , EFI , HILO , KC , NATR , QQE , RVI和THERMO ;默認的mamode
參數尚未更改。但是,如果需要,用戶也可以使用ta.ma()
。有關更多信息: help(ta.ma)
to_utc
,將數據框架索引轉換為UTC。請參閱: help(ta.to_utc)
現在作為pandas ta dataframe屬性,可以輕鬆將數據框架索引轉換為UTC。 close > sma(close, 50)
之類的趨勢系列時,它會返回該趨勢的趨勢,貿易參賽作品和貿易出口,以使其與VectorBT兼容,以使其與asbool=True
兼容,以獲取Boolean Trade參賽作品和退出。請參閱help(ta.tsignals)
help(ta.alma)
交易帳戶或資金。請參閱help(ta.drawdown)
help(ta.cdl_pattern)
help(ta.cdl_z)
help(ta.cti)
help(ta.xsignals)
help(ta.dm)
help(ta.ebsw)
help(ta.jma)
help(ta.kvo)
進行比較。help(ta.stc)
help(ta.squeeze_pro)
df.ta.strategy()
中脫穎而出。請參閱help(ta.td_seq)
help(ta.tos_stdevall)
help(ta.vhf)
mamode
重命名為mode
。請參閱help(ta.accbands)
。mamode
,並且具有與TradingView相同的mamode
選項。新參數lensig
行為與TradingView的內置ADX指標一樣。請參閱help(ta.adx)
。drift
參數和更多描述性列名。mamode
現在是“ RMA ”,並且具有與TradingView相同的mamode
選項。請參閱help(ta.atr)
。ddoff
控制自由度。還包括BB百分比(BBP)作為最後一列。默認值為0。請參閱help(ta.bbands)
。ln
新論點。默認值為false。請參閱help(ta.chop)
。True
tvmode
。當tvmode=False
時, CKSP實現了具有默認值的“新技術交易者”。請參閱help(ta.cksp)
。talib
將使用TA Lib的版本,如果安裝了TA Lib。默認是正確的。請參閱help(ta.cmo)
。strict
檢查該系列是否隨著更快的計算在周期length
上不斷減小。默認值: False
。默認情況下也添加了percent
參數。請參閱help(ta.decreasing)
。strict
檢查該系列是否在更快的計算中不斷length
。默認值: False
。默認情況下也添加了percent
參數。請參閱help(ta.increasing)
。help(ta.kvo)
。as_strided
方法還是較新的sliding_window_view
方法。這應該解決Google COLAB的問題,並延遲依賴性更新以及Tensorflow的依賴關係,如第285和#329期所討論的。asmode
啟用了MACD版本。默認值為false。請參閱help(ta.macd)
。sar
。新參數af0
初始化加速度因子。請參閱help(ta.psar)
。mamode
作為選項。默認值是與Ta Lib匹配的SMA 。請參閱help(ta.ppo)
。13
和信號MA模式mamode
添加signal
,默認EMA作為參數。請參閱help(ta.tsi)
。help(ta.vp)
。help(ta.vwma)
。anchor
的新參數。默認值:“每日”。有關其他選項,請參見時間表偏移別名。要求DataFrame索引為DateTimeIndex。請參閱help(ta.vwap)
。help(ta.vwma)
。Z_length
更改為ZS_length
。請參閱help(ta.zscore)
。原始ta-lib | TradingView |塞拉圖表| mql5 | FM Labs | Pro真實代碼|用戶42
感覺很慷慨,就像包裝一樣,還是想看到它變得更加成熟?