230 lines
10 KiB
Markdown
230 lines
10 KiB
Markdown
# pandas-ta Reference for Research Scripts
|
||
|
||
This catalog applies to both research scripts and custom indicators. For usage in research scripts see [`usage-examples.md`](usage-examples.md). For writing custom indicator scripts (with metadata for the TradingView plotter) see [`indicators/indicator-development.md`](indicators/indicator-development.md).
|
||
|
||
The sandbox environment uses **pandas-ta** as the standard indicator library. Always use it for technical indicator calculations; do not write manual rolling/ewm implementations.
|
||
|
||
```python
|
||
import pandas_ta as ta
|
||
```
|
||
|
||
## Calling Convention
|
||
|
||
pandas-ta functions accept a Series (or OHLCV columns) plus keyword parameters that match pandas-ta's documented argument names:
|
||
|
||
```python
|
||
# Single-series indicator
|
||
rsi = ta.rsi(df['close'], length=14) # returns Series
|
||
|
||
# OHLCV indicator
|
||
atr = ta.atr(df['high'], df['low'], df['close'], length=14)
|
||
|
||
# Multi-output indicator (returns DataFrame)
|
||
macd_df = ta.macd(df['close'], fast=12, slow=26, signal=9)
|
||
# columns: MACD_12_26_9, MACDh_12_26_9, MACDs_12_26_9
|
||
|
||
bbands_df = ta.bbands(df['close'], length=20, std=2.0)
|
||
# columns: BBL_20_2.0, BBM_20_2.0, BBU_20_2.0, BBB_20_2.0, BBP_20_2.0
|
||
```
|
||
|
||
## Default Parameters
|
||
|
||
Key defaults to keep in mind:
|
||
- Most period/length indicators: `length=14` (use `length=` not `timeperiod=`)
|
||
- `bbands`: `length=20, std=2.0` (note: single `std`, not separate upper/lower)
|
||
- `macd`: `fast=12, slow=26, signal=9`
|
||
- `stoch`: `k=14, d=3, smooth_k=3`
|
||
- `psar`: `af0=0.02, af=0.02, max_af=0.2`
|
||
- `vwap`: `anchor='D'` (requires DatetimeIndex)
|
||
- `ichimoku`: `tenkan=9, kijun=26, senkou=52`
|
||
|
||
## Available Indicators
|
||
|
||
These match the indicators supported by the TradingView web client. Use the pandas-ta function name shown here (lowercase):
|
||
|
||
### Overlap / Moving Averages — plotted on the price pane
|
||
|
||
| Function | Description |
|
||
|----------|-------------|
|
||
| `sma` | Simple Moving Average — plain arithmetic mean over `length` periods |
|
||
| `ema` | Exponential Moving Average — more weight on recent prices |
|
||
| `wma` | Weighted Moving Average — linearly increasing weights |
|
||
| `dema` | Double EMA — two layers of EMA to reduce lag |
|
||
| `tema` | Triple EMA — three layers of EMA, even less lag than DEMA |
|
||
| `trima` | Triangular MA — double-smoothed SMA, very smooth |
|
||
| `kama` | Kaufman Adaptive MA — adapts speed to market noise/trending conditions |
|
||
| `t3` | T3 Moving Average — Tillson's smooth, low-lag MA using six EMAs |
|
||
| `hma` | Hull MA — very low-lag MA using WMAs |
|
||
| `alma` | Arnaud Legoux MA — Gaussian-weighted MA with reduced lag and noise |
|
||
| `midpoint` | Midpoint of close over `length` periods: (highest + lowest) / 2 |
|
||
| `midprice` | Midpoint of high/low over `length` periods |
|
||
| `supertrend` | Trend-following band (ATR-based) that flips above/below price |
|
||
| `ichimoku` | Ichimoku Cloud — multi-line Japanese trend/support/resistance system |
|
||
| `vwap` | Volume-Weighted Average Price — average price weighted by volume, resets on `anchor` |
|
||
| `vwma` | Volume-Weighted MA — like SMA but candles weighted by volume |
|
||
| `bbands` | Bollinger Bands — SMA ± N standard deviations; returns upper, mid, lower bands |
|
||
|
||
### Momentum — typically plotted in a separate pane
|
||
|
||
| Function | Description |
|
||
|----------|-------------|
|
||
| `rsi` | Relative Strength Index — 0–100 oscillator measuring speed of price changes |
|
||
| `macd` | MACD — difference of two EMAs plus signal line and histogram |
|
||
| `stoch` | Stochastic Oscillator — %K/%D, measures close vs recent high/low range |
|
||
| `stochrsi` | Stochastic RSI — applies stochastic formula to RSI values |
|
||
| `cci` | Commodity Channel Index — deviation of price from its statistical mean |
|
||
| `willr` | Williams %R — inverse stochastic, −100 to 0 oscillator |
|
||
| `mom` | Momentum — raw price change over `length` periods |
|
||
| `roc` | Rate of Change — percentage price change over `length` periods |
|
||
| `trix` | TRIX — 1-period % change of a triple-smoothed EMA |
|
||
| `cmo` | Chande Momentum Oscillator — ratio of up/down momentum, −100 to 100 |
|
||
| `adx` | Average Directional Index — strength of trend (0–100, direction-agnostic) |
|
||
| `aroon` | Aroon — measures how recently the highest/lowest price occurred; returns Up, Down, Oscillator |
|
||
| `ao` | Awesome Oscillator — difference of 5- and 34-period simple MAs of midprice |
|
||
| `bop` | Balance of Power — measures buying vs selling pressure: (close−open)/(high−low) |
|
||
| `uo` | Ultimate Oscillator — weighted combo of three period (fast/medium/slow) buying pressure ratios |
|
||
| `apo` | Absolute Price Oscillator — difference between two EMAs (like MACD without signal line) |
|
||
| `mfi` | Money Flow Index — RSI-like oscillator using price × volume |
|
||
| `coppock` | Coppock Curve — long-term momentum oscillator based on rate-of-change |
|
||
| `dpo` | Detrended Price Oscillator — removes trend to show cycle oscillations |
|
||
| `fisher` | Fisher Transform — converts price into a Gaussian normal distribution |
|
||
| `rvgi` | Relative Vigor Index — compares close−open to high−low to measure trend vigor |
|
||
| `kst` | Know Sure Thing — momentum oscillator from four ROC periods, smoothed |
|
||
|
||
### Volatility — plotted on price pane or separate
|
||
|
||
| Function | Description |
|
||
|----------|-------------|
|
||
| `atr` | Average True Range — average of true range (greatest of H−L, H−prevC, L−prevC) |
|
||
| `kc` | Keltner Channels — EMA ± N × ATR bands around price |
|
||
| `donchian` | Donchian Channels — highest high / lowest low over `length` periods |
|
||
|
||
### Volume — plotted in separate pane
|
||
|
||
| Function | Description |
|
||
|----------|-------------|
|
||
| `obv` | On Balance Volume — cumulative volume, added on up days, subtracted on down days |
|
||
| `ad` | Accumulation/Distribution — running total of the money flow multiplier × volume |
|
||
| `adosc` | Chaikin Oscillator — EMA difference of the A/D line |
|
||
| `cmf` | Chaikin Money Flow — sum of (money flow volume) / sum of volume over `length` |
|
||
| `eom` | Ease of Movement — relates price change to volume; high = price moves easily |
|
||
| `efi` | Elder's Force Index — combines price change direction with volume magnitude |
|
||
| `kvo` | Klinger Volume Oscillator — EMA difference of volume force |
|
||
| `pvt` | Price Volume Trend — cumulative: volume × percentage price change |
|
||
|
||
### Statistics / Price Transforms
|
||
|
||
| Function | Description |
|
||
|----------|-------------|
|
||
| `stdev` | Standard Deviation of close over `length` periods |
|
||
| `linreg` | Linear Regression Curve — least-squares line endpoint value over `length` periods |
|
||
| `slope` | Linear Regression Slope — gradient of the regression line |
|
||
| `hl2` | Median Price — (high + low) / 2 |
|
||
| `hlc3` | Typical Price — (high + low + close) / 3 |
|
||
| `ohlc4` | Average Price — (open + high + low + close) / 4 |
|
||
|
||
### Trend
|
||
|
||
| Function | Description |
|
||
|----------|-------------|
|
||
| `psar` | Parabolic SAR — trailing stop-and-reverse dots that follow price |
|
||
| `vortex` | Vortex Indicator — VI+ / VI− lines measuring upward vs downward trend movement |
|
||
| `chop` | Choppiness Index — 0–100, high = choppy/sideways, low = strong trend |
|
||
|
||
## Usage Examples
|
||
|
||
### Single-output indicators
|
||
|
||
```python
|
||
import pandas_ta as ta
|
||
|
||
df['rsi'] = ta.rsi(df['close'], length=14)
|
||
df['ema_20'] = ta.ema(df['close'], length=20)
|
||
df['sma_50'] = ta.sma(df['close'], length=50)
|
||
df['atr'] = ta.atr(df['high'], df['low'], df['close'], length=14)
|
||
df['obv'] = ta.obv(df['close'], df['volume'])
|
||
df['adx'] = ta.adx(df['high'], df['low'], df['close'], length=14)['ADX_14']
|
||
```
|
||
|
||
### Multi-output indicators — extract columns by position
|
||
|
||
```python
|
||
# MACD → MACD_12_26_9, MACDh_12_26_9, MACDs_12_26_9
|
||
macd_df = ta.macd(df['close'], fast=12, slow=26, signal=9)
|
||
df['macd'] = macd_df.iloc[:, 0] # MACD line
|
||
df['macd_hist'] = macd_df.iloc[:, 1] # Histogram
|
||
df['macd_signal'] = macd_df.iloc[:, 2] # Signal line
|
||
|
||
# Bollinger Bands → BBL, BBM, BBU, BBB, BBP
|
||
bb_df = ta.bbands(df['close'], length=20, std=2.0)
|
||
df['bb_lower'] = bb_df.iloc[:, 0] # BBL
|
||
df['bb_mid'] = bb_df.iloc[:, 1] # BBM
|
||
df['bb_upper'] = bb_df.iloc[:, 2] # BBU
|
||
|
||
# Stochastic → STOCHk, STOCHd
|
||
stoch_df = ta.stoch(df['high'], df['low'], df['close'], k=14, d=3, smooth_k=3)
|
||
df['stoch_k'] = stoch_df.iloc[:, 0]
|
||
df['stoch_d'] = stoch_df.iloc[:, 1]
|
||
|
||
# Keltner Channels → KCLe, KCBe, KCUe
|
||
kc_df = ta.kc(df['high'], df['low'], df['close'], length=20)
|
||
df['kc_lower'] = kc_df.iloc[:, 0]
|
||
df['kc_mid'] = kc_df.iloc[:, 1]
|
||
df['kc_upper'] = kc_df.iloc[:, 2]
|
||
|
||
# ADX → ADX_14, DMP_14, DMN_14
|
||
adx_df = ta.adx(df['high'], df['low'], df['close'], length=14)
|
||
df['adx'] = adx_df.iloc[:, 0] # ADX strength
|
||
df['dmp'] = adx_df.iloc[:, 1] # +DI
|
||
df['dmn'] = adx_df.iloc[:, 2] # -DI
|
||
|
||
# Aroon → AROOND_14, AROONU_14, AROONOSC_14
|
||
aroon_df = ta.aroon(df['high'], df['low'], length=14)
|
||
df['aroon_down'] = aroon_df.iloc[:, 0]
|
||
df['aroon_up'] = aroon_df.iloc[:, 1]
|
||
|
||
# Donchian Channels → DCL, DCM, DCU
|
||
dc_df = ta.donchian(df['high'], df['low'], lower_length=20, upper_length=20)
|
||
df['dc_lower'] = dc_df.iloc[:, 0]
|
||
df['dc_mid'] = dc_df.iloc[:, 1]
|
||
df['dc_upper'] = dc_df.iloc[:, 2]
|
||
```
|
||
|
||
### Charting with indicators
|
||
|
||
```python
|
||
import pandas_ta as ta
|
||
from dexorder.api import get_api
|
||
import asyncio
|
||
|
||
api = get_api()
|
||
|
||
df = asyncio.run(api.data.historical_ohlc(
|
||
ticker="BTC/USDT.BINANCE",
|
||
period_seconds=3600,
|
||
start_time="2024-01-01",
|
||
end_time="2024-01-08",
|
||
extra_columns=["volume"]
|
||
))
|
||
|
||
# Compute indicators
|
||
df['ema_20'] = ta.ema(df['close'], length=20)
|
||
df['rsi'] = ta.rsi(df['close'], length=14)
|
||
macd_df = ta.macd(df['close'])
|
||
df['macd'] = macd_df.iloc[:, 0]
|
||
df['macd_signal'] = macd_df.iloc[:, 2]
|
||
|
||
# Main price chart with EMA overlay
|
||
fig, ax = api.charting.plot_ohlc(df, title="BTC/USDT 1H", volume=True)
|
||
ax.plot(range(len(df)), df['ema_20'], label="EMA 20", color="orange", linewidth=1.5) # range(len(df)), not df.index
|
||
ax.legend()
|
||
|
||
# RSI panel
|
||
rsi_ax = api.charting.add_indicator_panel(fig, df, columns=["rsi"], ylabel="RSI", ylim=(0, 100))
|
||
rsi_ax.axhline(70, color='red', linestyle='--', alpha=0.5)
|
||
rsi_ax.axhline(30, color='green', linestyle='--', alpha=0.5)
|
||
|
||
# MACD panel
|
||
api.charting.add_indicator_panel(fig, df, columns=["macd", "macd_signal"], ylabel="MACD")
|
||
```
|