Logo
AXION

Python SDK Technical Analysis

Technical Analysis Indicators

A comprehensive collection of technical analysis indicators for financial data analysis. These functions calculate various market indicators used in technical trading strategies.

Rate of Change (ROC)

FUNCTIONroc(df, column="close", period=10)

Calculates the Rate of Change percentage over a specified period.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Pandas DataFrame containing price data
columnstring"close"Column name for price data
periodint10Lookback period for ROC calculation

Returns

Returns a pandas Series with ROC percentage values.

Formula

ROC = ((current_price / price_n_periods_ago) - 1) * 100
|

ROC Example

Python

from axion import ta
import pandas as pd

# Sample data
df = pd.DataFrame({
    'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})

# Calculate 5-period ROC
roc_series = ta.roc(df, column='close', period=5)
print(roc_series)

Output

0          NaN
1          NaN
2          NaN
3          NaN
4          NaN
5     4.000000
6     3.921569
7     3.883495
8     1.923077
9     3.809524
Name: roc, dtype: float64

Momentum

FUNCTIONmom(df, column="close", period=10)

Calculates the difference between current price and price n periods ago.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Pandas DataFrame containing price data
columnstring"close"Column name for price data
periodint10Lookback period for momentum calculation

Returns

Returns a pandas Series with momentum values (price difference).

Formula

Momentum = current_price - price_n_periods_ago
|

Momentum Example

Python

from axion import ta
import pandas as pd

# Sample data
df = pd.DataFrame({
    'close': [100, 102, 104, 103, 105, 107, 106, 108, 110, 109]
})

# Calculate 5-period momentum
momentum_series = ta.mom(df, column='close', period=5)
print(momentum_series)

Output

0    NaN
1    NaN
2    NaN
3    NaN
4    NaN
5    7.0
6    4.0
7    5.0
8    5.0
9    2.0
Name: mom, dtype: float64

Simple Moving Average

FUNCTIONsma(df, column="close", period=14)

Calculates the Simple Moving Average over a specified period.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Pandas DataFrame containing price data
columnstring"close"Column name for price data
periodint14Lookback period for SMA calculation

Returns

Returns a pandas Series with Simple Moving Average values.

Formula

SMA = (price₁ + price₂ + ... + priceₙ) / n
|

SMA Example

Python

from axion import ta
import pandas as pd

# Sample data
df = pd.DataFrame({
    'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})

# Calculate 5-period SMA
sma_series = ta.sma(df, column='close', period=5)
print(sma_series)

Output

0      NaN
1      NaN
2      NaN
3      NaN
4    102.2
5    103.0
6    103.8
7    105.2
8    106.0
9    106.8
Name: sma, dtype: float64

Simple Moving Median

FUNCTIONsmm(df, column="close", period=14)

Calculates the median value over a specified rolling window.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Pandas DataFrame containing price data
columnstring"close"Column name for price data
periodint14Lookback period for median calculation

Returns

Returns a pandas Series with moving median values.

Formula

SMM = median(price₁, price₂, ..., priceₙ)
|

SMM Example

Python

from axion import ta
import pandas as pd

# Sample data
df = pd.DataFrame({
    'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})

# Calculate 5-period SMM
smm_series = ta.smm(df, column='close', period=5)
print(smm_series)

Output

0      NaN
1      NaN
2      NaN
3      NaN
4    102.0
5    103.0
6    104.0
7    105.0
8    106.0
9    107.0
Name: smm, dtype: float64

Smoothed Simple Moving Average

FUNCTIONssma(df, column="close", period=14)

Calculates a smoothed version of the Simple Moving Average using exponential smoothing.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Pandas DataFrame containing price data
columnstring"close"Column name for price data
periodint14Lookback period for SSMA calculation

Returns

Returns a pandas Series with smoothed moving average values.

Formula

SSMAₜ = EMA(SMA, α=1/period)
|

SSMA Example

Python

from axion import ta
import pandas as pd

# Sample data
df = pd.DataFrame({
    'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})

# Calculate 5-period SSMA
ssma_series = ta.ssma(df, column='close', period=5)
print(ssma_series)

Output

0          NaN
1          NaN
2          NaN
3          NaN
4    102.200000
5    102.533333
6    103.355556
7    104.570370
8    105.046914
9    106.031276
Name: ssma, dtype: float64

Exponential Moving Average

FUNCTIONema(df, column="close", period=14)

Calculates the Exponential Moving Average which gives more weight to recent prices.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Pandas DataFrame containing price data
columnstring"close"Column name for price data
periodint14Lookback period for EMA calculation

Returns

Returns a pandas Series with Exponential Moving Average values.

Formula

EMAₜ = (Priceₜ × k) + (EMAₜ-₁ × (1 - k))
where k = 2/(period + 1)
|

EMA Example

Python

from axion import ta
import pandas as pd

# Sample data
df = pd.DataFrame({
    'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})

# Calculate 5-period EMA
ema_series = ta.ema(df, column='close', period=5)
print(ema_series)

Output

0          NaN
1          NaN
2          NaN
3          NaN
4    102.200000
5    102.800000
6    103.866667
7    105.244444
8    105.829630
9    106.886420
Name: ema, dtype: float64

Double Exponential Moving Average

FUNCTIONdema(df, column="close", period=14)

Calculates the Double EMA, which applies EMA smoothing twice for reduced lag.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Pandas DataFrame containing price data
columnstring"close"Column name for price data
periodint14Lookback period for DEMA calculation

Returns

Returns a pandas Series with Double Exponential Moving Average values.

Formula

DEMA = 2 × EMA - EMA(EMA)
|

DEMA Example

Python

from axion import ta
import pandas as pd

# Sample data
df = pd.DataFrame({
    'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})

# Calculate 5-period DEMA
dema_series = ta.dema(df, column='close', period=5)
print(dema_series)

Output

0          NaN
1          NaN
2          NaN
3          NaN
4    102.200000
5    103.137778
6    105.029630
7    107.159012
8    107.264198
9    109.159538
Name: dema, dtype: float64

Triangular Moving Average

FUNCTIONtrima(df, column="close", period=14)

Calculates a double-smoothed moving average for reduced noise.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Pandas DataFrame containing price data
columnstring"close"Column name for price data
periodint14Lookback period for TRIMA calculation

Returns

Returns a pandas Series with Triangular Moving Average values.

Formula

TRIMA = SMA(SMA(price, period), period)
|

TRIMA Example

Python

from axion import ta
import pandas as pd

# Sample data
df = pd.DataFrame({
    'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})

# Calculate 5-period TRIMA
trima_series = ta.trima(df, column='close', period=5)
print(trima_series)

Output

0      NaN
1      NaN
2      NaN
3      NaN
4      NaN
5      NaN
6      NaN
7      NaN
8    104.2
9    104.8
Name: trima, dtype: float64

Average True Range

FUNCTIONatr(df, period=14)

Measures market volatility by calculating the average of true ranges over a period.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Must contain 'high', 'low', 'close' columns
periodint14Lookback period for ATR calculation

Returns

Returns a pandas Series with Average True Range values.

True Range Calculation

TR = max(high - low, |high - prev_close|, |low - prev_close|)
ATR = SMA(TR, period)
|

ATR Example

Python

from axion import ta
import pandas as pd

# Sample OHLC data
df = pd.DataFrame({
    'high': [105, 107, 106, 108, 110],
    'low': [99, 101, 100, 102, 104],
    'close': [102, 104, 103, 105, 107]
})

# Calculate 3-period ATR
atr_series = ta.atr(df, period=3)
print(atr_series)

Output

0         NaN
1         NaN
2    4.666667
3    4.222222
4    4.148148
Name: atr, dtype: float64

Stochastic Oscillator

FUNCTIONstochastic_oscillator(df, k_period=14, d_period=3)

Calculates %K and %D stochastic oscillator values to identify overbought/oversold conditions.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Must contain 'high', 'low', 'close' columns
k_periodint14Lookback period for %K calculation
d_periodint3Smoothing period for %D

Returns

Returns two pandas Series: %K (fast stochastic) and %D (slow stochastic).

Formula

%K = 100 × ((close - lowest_low) / (highest_high - lowest_low))
%D = SMA(%K, d_period)
|

Stochastic Oscillator Example

Python

from axion import ta
import pandas as pd

# Sample OHLC data
df = pd.DataFrame({
    'high': [105, 107, 106, 108, 110, 109, 111],
    'low': [99, 101, 100, 102, 104, 103, 105],
    'close': [102, 104, 103, 105, 107, 106, 108]
})

# Calculate stochastic oscillator
stoch_k, stoch_d = ta.stochastic_oscillator(df, k_period=5, d_period=3)
print("Stochastic %K:", stoch_k)
print("Stochastic %D:", stoch_d)

Output

Stochastic %K: 0         NaN
1         NaN
2         NaN
3         NaN
4    50.000000
5    66.666667
6    57.142857
Name: stoch_k, dtype: float64

Stochastic %D: 0         NaN
1         NaN
2         NaN
3         NaN
4         NaN
5         NaN
6    57.936508
Name: stoch_d, dtype: float64

Chande Momentum Oscillator

FUNCTIONcmo(df, column="close", period=20)

Measures momentum by comparing sum of gains to sum of losses over a period.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Pandas DataFrame containing price data
columnstring"close"Column name for price data
periodint20Lookback period for CMO calculation

Returns

Returns a pandas Series with CMO values ranging from -100 to +100.

Formula

CMO = 100 × ((sum_gains - sum_losses) / (sum_gains + sum_losses))
|

CMO Example

Python

from axion import ta
import pandas as pd

# Sample data
df = pd.DataFrame({
    'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})

# Calculate 5-period CMO
cmo_series = ta.cmo(df, column='close', period=5)
print(cmo_series)

Output

0         NaN
1         NaN
2         NaN
3         NaN
4         NaN
5   60.000000
6   33.333333
7   60.000000
8   20.000000
9   60.000000
Name: cmo, dtype: float64

On Balance Volume

FUNCTIONobv(df)

Cumulatively adds or subtracts volume based on price direction to measure buying/selling pressure.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Must contain 'close' and 'volume' columns

Returns

Returns a pandas Series with cumulative On Balance Volume values.

Formula

OBVₜ = OBVₜ-₁ +
  volumeₜ if closeₜ > closeₜ-₁
  -volumeₜ if closeₜ > closeₜ-
  0 if closeₜ = closeₜ-₁
|

OBV Example

Python

from axion import ta
import pandas as pd

# Sample OHLCV data
df = pd.DataFrame({
    'close': [100, 102, 101, 103, 105],
    'volume': [1000, 1500, 1200, 1800, 2000]
})

# Calculate OBV
obv_series = ta.obv(df)
print(obv_series)

Output

0    1000
1    2500
2    1300
3    3100
4    5100
Name: obv, dtype: int64

Volume Price Trend

FUNCTIONvpt(df)

Measures the relationship between volume and price changes by cumulating volume adjusted by price percentage changes.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Must contain 'close' and 'volume' columns

Returns

Returns a pandas Series with cumulative Volume Price Trend values.

Formula

VPTₜ = VPTₜ-₁ + (volumeₜ × ((closeₜ - closeₜ-₁) / closeₜ-₁))
|

VPT Example

Python

from axion import ta
import pandas as pd

# Sample data
df = pd.DataFrame({
    'close': [100, 102, 101, 103, 105],
    'volume': [1000, 1500, 1200, 1800, 2000]
})

# Calculate VPT
vpt_series = ta.vpt(df)
print(vpt_series)

Output

0       0.000000
1      30.000000
2      18.235294
3      53.184466
4      91.962275
Name: vpt, dtype: float64

Volume-Weighted Average Price

FUNCTIONvwap(df, period=14)

Calculates the average price weighted by volume over a specified period.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Must contain 'high', 'low', 'close', 'volume' columns
periodint14Rolling period for VWAP calculation

Returns

Returns a pandas Series with Volume-Weighted Average Price values.

Formula

VWAP = (sum(volume × typical_price)) / (sum(volume))
typical_price = (high + low + close) / 3
|

VWAP Example

Python

from axion import ta
import pandas as pd

# Sample OHLCV data
df = pd.DataFrame({
    'high': [105, 107, 106, 108, 110],
    'low': [99, 101, 100, 102, 104],
    'close': [102, 104, 103, 105, 107],
    'volume': [1000, 1500, 1200, 1800, 2000]
})

# Calculate VWAP
vwap_series = ta.vwap(df, period=3)
print(vwap_series)

Output

0           NaN
1           NaN
2    103.175676
3    104.557377
4    105.595745
Name: vwap, dtype: float64

Bollinger Bands

FUNCTIONbbands(df, column="close", period=20, num_std_dev=2)

Calculates upper and lower Bollinger Bands around a simple moving average.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Pandas DataFrame containing price data
columnstring"close"Column name for price data
periodint20Lookback period for SMA calculation
num_std_devint/float2Number of standard deviations for bands

Returns

Returns three pandas Series: upper_band, middle_band (SMA), lower_band.

Formula

middle_band = SMA(close, period)
upper_band = middle_band + (std_dev × num_std_dev)
lower_band = middle_band - (std_dev × num_std_dev)
|

Bollinger Bands Example

Python

from axion import ta
import pandas as pd

# Sample data
df = pd.DataFrame({
    'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})

# Calculate Bollinger Bands
upper, middle, lower = ta.bbands(df, period=5, num_std_dev=2)
print("Upper Band:", upper)
print("Middle Band:", middle)
print("Lower Band:", lower)

Output

Upper Band: 4        106.549742
5        107.303261
6        109.063901
7        111.133918
8        111.207841
9        112.456119
Name: bbands_upper, dtype: float64

Middle Band: 4    102.2
5    103.0
6    103.8
7    105.2
8    106.0
9    106.8
Name: bbands_middle, dtype: float64

Lower Band: 4     97.850258
5     98.696739
6     98.536099
7     99.266082
8    100.792159
9    101.143881
Name: bbands_lower, dtype: float64

Keltner Channels

FUNCTIONkc(df, period=20, atr_period=10, multiplier=2)

Calculates volatility-based channels using ATR around an exponential moving average.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Must contain 'high', 'low', 'close' columns
periodint20EMA period for middle line
atr_periodint10Period for ATR calculation
multiplierint/float2ATR multiplier for channel width

Returns

Returns three pandas Series: upper_channel, middle_line, lower_channel.

Formula

middle_line = EMA(close, period)
upper_channel = middle_line + (ATR × multiplier)
lower_channel = middle_line - (ATR × multiplier)
|

Keltner Channels Example

Python

from axion import ta
import pandas as pd

# Sample OHLC data
df = pd.DataFrame({
    'high': [105, 107, 106, 108, 110],
    'low': [99, 101, 100, 102, 104],
    'close': [102, 104, 103, 105, 107]
})

# Calculate Keltner Channels
upper, middle, lower = ta.kc(df, period=3, atr_period=3, multiplier=2)
print("Upper Channel:", upper)
print("Middle Line:", middle)
print("Lower Channel:", lower)

Output

Upper Channel: 0           NaN
1           NaN
2    109.888889
3    110.666667
4    112.296296
Name: kc_upper, dtype: float64

Middle Line: 0           NaN
1           NaN
2    103.000000
3    104.000000
4    105.666667
Name: kc_middle, dtype: float64

Lower Channel: 0           NaN
1           NaN
2     96.111111
3     97.333333
4     99.037037
Name: kc_lower, dtype: float64

Kaufman's Adaptive Moving Average

FUNCTIONkama(df, column="close", period=14, fast=14, slow=30)

Adaptive moving average that adjusts its sensitivity based on market volatility.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Pandas DataFrame containing price data
columnstring"close"Column name for price data
periodint14Efficiency ratio period
fastint14Fast EMA constant period
slowint30Slow EMA constant period

Returns

Returns a pandas Series with Kaufman's Adaptive Moving Average values.

Formula

ER = direction / volatility
SC = [ER × (fastest - slowest) + slowest]²
KAMAₜ = KAMAₜ-₁ + SC × (price - KAMAₜ-₁)
|

KAMA Example

Python

from axion import ta
import pandas as pd

# Sample data
df = pd.DataFrame({
    'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})

# Calculate KAMA
kama_series = ta.kama(df, column='close', period=5)
print(kama_series)

Output

0          NaN
1          NaN
2          NaN
3          NaN
4    102.200000
5    103.103252
6    104.383699
7    106.149310
8    106.431297
9    107.774876
Name: kama, dtype: float64

Vortex Indicator

FUNCTIONvi(df, period=14)

Measures trend direction and strength using positive and negative vortex movements.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Must contain 'high', 'low', 'close' columns
periodint14Lookback period for VI calculation

Returns

Returns two pandas Series: VI_plus (positive vortex) and VI_minus (negative vortex).

|

Vortex Indicator Example

Python

from axion import ta
import pandas as pd

# Sample OHLC data
df = pd.DataFrame({
    'high': [105, 107, 106, 108, 110, 109, 111],
    'low': [99, 101, 100, 102, 104, 103, 105],
    'close': [102, 104, 103, 105, 107, 106, 108]
})

# Calculate Vortex Indicator
vi_plus, vi_minus = ta.vi(df, period=5)
print("VI+:", vi_plus)
print("VI-:", vi_minus)

Output

VI+: 0         NaN
1         NaN
2         NaN
3         NaN
4    1.245192
5    1.183790
6    1.193062
Name: vi_plus, dtype: float64

VI-: 0         NaN
1         NaN
2         NaN
3         NaN
4    0.832453
5    0.822703
6    0.844121
Name: vi_minus, dtype: float64

Moving Average Convergence Divergence

FUNCTIONmacd(df, column="close", fast_period=12, slow_period=26, signal_period=9)

Calculates MACD line, signal line, and histogram for trend-following momentum indicator.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Pandas DataFrame containing price data
columnstring"close"Column name for price data
fast_periodint12Fast EMA period
slow_periodint26Slow EMA period
signal_periodint9Signal line EMA period

Returns

Returns three pandas Series: macd_line, signal_line, histogram.

Formula

MACD = EMA(fast_period) - EMA(slow_period)
Signal = EMA(MACD, signal_period)
Histogram = MACD - Signal
|

MACD Example

Python

from axion import ta
import pandas as pd

# Sample data
df = pd.DataFrame({
    'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})

# Calculate MACD
macd_line, signal_line, histogram = ta.macd(df, fast_period=5, slow_period=8, signal_period=3)
print("MACD Line:", macd_line)
print("Signal Line:", signal_line)
print("Histogram:", histogram)

Output

MACD Line: 0         NaN
1         NaN
2         NaN
3         NaN
4         NaN
5         NaN
6         NaN
7    0.881433
8    0.495703
9    1.079230
Name: macd, dtype: float64

Signal Line: 0         NaN
1         NaN
2         NaN
3         NaN
4         NaN
5         NaN
6         NaN
7    0.881433
8    0.688568
9    0.883899
Name: signal, dtype: float64

Histogram: 0         NaN
1         NaN
2         NaN
3         NaN
4         NaN
5         NaN
6         NaN
7    0.000000
8   -0.192865
9    0.195331
Name: histogram, dtype: float64

Williams %R

FUNCTIONwilliams_r(df, period=14)

Momentum indicator measuring overbought/oversold levels, similar to stochastic oscillator.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Must contain 'high', 'low', 'close' columns
periodint14Lookback period for Williams %R

Returns

Returns a pandas Series with Williams %R values ranging from -100 to 0.

Formula

Williams %R = -100 × ((highest_high - close) / (highest_high - lowest_low))
|

Williams %R Example

Python

from axion import ta
import pandas as pd

# Sample OHLC data
df = pd.DataFrame({
    'high': [105, 107, 106, 108, 110],
    'low': [99, 101, 100, 102, 104],
    'close': [102, 104, 103, 105, 107]
})

# Calculate Williams %R
williams_r_series = ta.williams_r(df, period=5)
print(williams_r_series)

Output

0          NaN
1          NaN
2          NaN
3          NaN
4   -50.000000
Name: williams_r, dtype: float64

Average Directional Index

FUNCTIONadx(df, period=14)

Measures trend strength without regard to direction.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Must contain 'high', 'low', 'close' columns
periodint14Lookback period for ADX calculation

Returns

Returns a pandas Series with Average Directional Index values.

Formula

+DI = 100 × SMA(+DM) / ATR
-DI = 100 × SMA(-DM) / ATR
DX = 100 × |+DI - -DI| / (+DI + -DI)
ADX = SMA(DX, period)
|

ADX Example

Python

from axion import ta
import pandas as pd

# Sample OHLC data
df = pd.DataFrame({
    'high': [105, 107, 106, 108, 110, 109, 111],
    'low': [99, 101, 100, 102, 104, 103, 105],
    'close': [102, 104, 103, 105, 107, 106, 108]
})

# Calculate ADX
adx_series = ta.adx(df, period=5)
print(adx_series)

Output

0          NaN
1          NaN
2          NaN
3          NaN
4          NaN
5          NaN
6          NaN
7          NaN
8    32.495897
Name: adx, dtype: float64

Relative Strength Index

FUNCTIONrsi(df, column="close", period=14)

Measures speed and change of price movements to identify overbought/oversold conditions.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Pandas DataFrame containing price data
columnstring"close"Column name for price data
periodint14Lookback period for RSI calculation

Returns

Returns a pandas Series with RSI values ranging from 0 to 100.

Formula

RSI = 100 - (100 / (1 + RS))
RS = average_gain / average_loss
|

RSI Example

Python

from axion import ta
import pandas as pd

# Sample data
df = pd.DataFrame({
    'close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109]
})

# Calculate 5-period RSI
rsi_series = ta.rsi(df, column='close', period=5)
print(rsi_series)

Output

0          NaN
1          NaN
2          NaN
3          NaN
4          NaN
5    61.904762
6    55.555556
7    70.000000
8    57.142857
9    70.000000
Name: rsi, dtype: float64

Ichimoku Cloud

FUNCTIONichi(df)

Comprehensive indicator that provides support/resistance, trend direction, and momentum.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Must contain 'high', 'low', 'close' columns

Returns

Returns five pandas Series: conversion_line, base_line, leading_span_a, leading_span_b, lagging_span.

Formula

Conversion Line = (9-period high + 9-period low) / 2
Base Line = (26-period high + 26-period low) / 2
Leading Span A = (Conversion Line + Base Line) / 2 (shifted forward 26 periods)
Leading Span B = (52-period high + 52-period low) / 2 (shifted forward 26 periods)
Lagging Span = Close (shifted back 26 periods)
|

Ichimoku Cloud Example

Python

from axion import ta
import pandas as pd

# Sample OHLC data (typically requires more data points)
df = pd.DataFrame({
    'high': [105, 107, 106, 108, 110, 109, 111, 112, 113, 114],
    'low': [99, 101, 100, 102, 104, 103, 105, 106, 107, 108],
    'close': [102, 104, 103, 105, 107, 106, 108, 109, 110, 111]
})

# Calculate Ichimoku Cloud
conversion, base, span_a, span_b, lag = ta.ichi(df)
print("Conversion Line:", conversion)
print("Base Line:", base)
print("Leading Span A:", span_a)
print("Leading Span B:", span_b)
print("Lagging Span:", lag)

Output

Conversion Line: 0         NaN
1         NaN
2         NaN
3         NaN
4         NaN
5         NaN
6         NaN
7         NaN
8    107.5
9    108.5
Name: conversion_line, dtype: float64

Base Line: 0         NaN
1         NaN
2         NaN
3         NaN
4         NaN
5         NaN
6         NaN
7         NaN
8    108.0
9    108.5
Name: base_line, dtype: float64
...

Parabolic SAR

FUNCTIONsar(df, af=0.02, af_max=0.2)

Trend-following indicator that provides potential reversal points.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Must contain 'high', 'low', 'close' columns
affloat0.02Acceleration factor increment
af_maxfloat0.2Maximum acceleration factor

Returns

Returns a pandas Series with Parabolic SAR values.

Formula

SARₜ = SARₜ-₁ + AF × (EP - SARₜ-₁)
where EP is the extreme point (highest high in uptrend, lowest low in downtrend)
|

Parabolic SAR Example

Python

from axion import ta
import pandas as pd

# Sample OHLC data
df = pd.DataFrame({
    'high': [105, 107, 106, 108, 110, 109, 111],
    'low': [99, 101, 100, 102, 104, 103, 105],
    'close': [102, 104, 103, 105, 107, 106, 108]
})

# Calculate Parabolic SAR
sar_series = ta.sar(df, af=0.02, af_max=0.2)
print(sar_series)

Output

0     99.000000
1     99.000000
2     99.000000
3     99.000000
4     99.000000
5     99.000000
6    104.060000
Name: sar, dtype: float64

Fibonacci Pivot Points

FUNCTIONfib(df)

Calculates Fibonacci-based support and resistance levels using previous period's high, low, and close.

Parameters

ParameterTypeDefaultDescription
dfDataFrame-Must contain 'high', 'low', 'close' columns

Returns

Returns seven pandas Series: PP, R1, S1, R2, S2, R3, S3.

Formulas

PP = (high + low + close) / 3
R1 = PP + 0.382 × (high - low)
S1 = PP - 0.382 × (high - low)
R2 = PP + 0.618 × (high - low)
S2 = PP - 0.618 × (high - low)
R3 = PP + 1.000 × (high - low)
S3 = PP - 1.000 × (high - low)
|

Fibonacci Pivot Points Example

Python

from axion import ta
import pandas as pd
import SEOMetadata from '@/components/SEOMetadata';

# Sample OHLC data
df = pd.DataFrame({
    'high': [110, 108, 107],
    'low': [100, 102, 101],
    'close': [105, 106, 104]
})

# Calculate Fibonacci Pivot Points
PP, R1, S1, R2, S2, R3, S3 = ta.fib(df)
print("PP:", PP)
print("R1:", R1)
print("S1:", S1)
print("R2:", R2)
print("S2:", S2)
print("R3:", R3)
print("S3:", S3)

Output

PP: 0    105.0
1    105.0
2    104.0
dtype: float64
R1: 0    108.82
1    107.29
2    106.29
dtype: float64
S1: 0    101.18
1    102.71
2    101.71
dtype: float64
R2: 0    111.18
1    108.71
2    107.71
dtype: float64
S2: 0     98.82
1    101.29
2    100.29
dtype: float64
R3: 0    115.0
1    111.0
2    110.0
dtype: float64
S3: 0     95.0
1     99.0
2     98.0
dtype: float64

Data Requirements

Most functions require specific columns in the DataFrame. Below are the common requirements:

Basic Price Data

  • close - Closing price
  • high - Highest price
  • low - Lowest price
  • volume - Trading volume

Indicator Categories

  • Trend Indicators: SMA, EMA, MACD, ADX
  • Momentum Indicators: RSI, Stochastic, Williams %R
  • Volatility Indicators: Bollinger Bands, ATR, Keltner Channels
  • Volume Indicators: OBV, VPT, VWAP

Utility Functions & Helpers

A collection of utility functions, shortcuts, and helpers for data manipulation, caching, and common operations in financial data analysis.

Import as: from axion import utils as axion_utils

Time Constants

Predefined string constants for natural language date references.

Date Constants

ConstantValueDescription
today'today'Current day reference
now'today'Current time reference
tomorrow'1 day from now'Next day reference
yesterday'1 day ago'Previous day reference
weekago'1 week ago'One week ago reference
weekfrom'1 week from today'One week from now reference
monthago'1 month ago'One month ago reference
monthfrom'1 month from now'One month from now reference
yearago'1 year ago'One year ago reference
yearfrom'1 year from now'One year from now reference

Frequency Constants

ConstantValueDescription
d, day'D'Daily frequency
w, week'W'Weekly frequency
m, month'M'Monthly frequency
y, year'Y'Yearly frequency
h, hour'H'Hourly frequency

Boolean Constants

true = TruePython boolean True
false = FalsePython boolean False

Caching Functions

Functions for persistent caching of data to disk to avoid repeated computation.

cache

cache(id, fn)

Caches the result of a function call. Returns cached result if it exists, otherwise calls the function and caches the result.

Parameters

  • id (str) - Unique identifier for the cache entry
  • fn (callable) - Function to call if cache doesn't exist

save

save(id, obj)

Manually saves an object to the cache directory.

Parameters

  • id (str) - Unique identifier for the cache entry
  • obj (any) - Object to save to cache

read

read(id)

Reads an object from the cache directory.

Parameters

  • id (str) - Unique identifier for the cache entry

scribe

scribe(df, id, cb)

Combines caching with concurrent processing using the work function.

Parameters

  • df (DataFrame) - DataFrame to process
  • id (str) - Cache identifier
  • cb (callable) - Callback function for processing rows
|

Cache Example

def fetch_expensive_data():
    return pd.DataFrame({'AAPL': [150, 151, 152]})

# First call - executes and caches
data = axion_utils.cache('stock_prices', fetch_expensive_data)

# Second call - loads from cache
cached_data = axion_utils.cache('stock_prices', fetch_expensive_data)

# Cache directory: ./.axion_cache/

Save & Read Example

# Manually save data
axion_utils.save('my_portfolio', {'AAPL': 150.25})

# Read it back
saved_data = axion_utils.read('my_portfolio')

Scribe Example

tickers_df = axion_utils.df([
    {'ticker': 'AAPL'}, {'ticker': 'GOOG'}
])

def fetch_data(row):
    return row['ticker'], {'price': 150.25}

results = axion_utils.scribe(tickers_df, 'stock_data', fetch_data)

Date Functions

Functions for parsing, converting, and manipulating dates.

Natural Language Date Parser

d(date_string)

Converts natural language date strings to YYYY-MM-DD format using parsedatetime library.

Parameters

  • date_string (str) - Natural language date

Returns

String in YYYY-MM-DD format or None if parsing fails

Date to Timestamp

to_timestamp(date)

Converts a date string in YYYY-MM-DD format to Unix timestamp.

Parameters

  • date (str) - Date in YYYY-MM-DD format

Nearest Trading Day

nearest_day(date_str, force=False)

Converts a date to the nearest trading day (Monday-Friday).

Parameters

  • date_str (str) - Date in YYYY-MM-DD format
  • force (bool) - If True, returns same date even if weekend

Weekend Handling

  • Saturday → Previous Friday
  • Sunday → Next Monday
  • Weekdays → Same day
|

Date Parsing Examples

today = axion_utils.d("today")
three_days_ago = axion_utils.d("3 days ago")
next_monday = axion_utils.d("next monday")

# With constants
last_month = axion_utils.d(axion_utils.monthago)

Timestamp & Trading Day

# Convert to timestamp
timestamp = axion_utils.to_timestamp("2024-01-15")

# Get nearest trading day
friday = axion_utils.nearest_day("2024-01-13")  # Saturday -> Friday
monday = axion_utils.nearest_day("2024-01-14")  # Sunday -> Monday

DataFrame Creation

Shortcut functions for creating and manipulating DataFrames.

DataFrame Shortcut

df(items)

Creates a pandas DataFrame from a list of dictionaries or other compatible data structures.

Parameters

  • items (list) - List of dictionaries or data to convert to DataFrame

DataFrame List Converter

pds(l)

Converts a 2D list of dictionaries into a 1D list of DataFrames.

Parameters

  • l (list) - 2D list of dictionaries

List Flattener

simmer(arr)

Flattens a 2D list into a 1D list.

Parameters

  • arr (list) - 2D list to flatten
|

Create DataFrame

stock_data = axion_utils.df([
    {'ticker': 'AAPL', 'price': 150.25},
    {'ticker': 'GOOG', 'price': 2815.50}
])

Convert Nested Data

api_data = [
    [{'metric': 'revenue', 'value': 100000}],
    [{'metric': 'revenue', 'value': 200000}]
]
dataframes = axion_utils.pds(api_data)

Flatten Lists

nested = [[1, 2, 3], [4, 5], [6, 7, 8]]
flattened = axion_utils.simmer(nested)
# [1, 2, 3, 4, 5, 6, 7, 8]

DataFrame Operations

Functions for filtering, merging, and transforming DataFrames.

Date Range Filter

resample(df, dates, col='time')

Filters DataFrame rows based on a date range string.

Parameters

  • df (DataFrame) - DataFrame to filter
  • dates (str) - String like "1 week ago 1 month ago"
  • col (str) - Column name containing dates

Column Value Filter

filter(df, col, items)

Filters DataFrame to include only rows where column values are in the specified list.

Parameters

  • df (DataFrame) - DataFrame to filter
  • col (str) - Column name to filter on
  • items (list) - List of values to include

Percentage Change Calculator

relativity(df, cols)

Calculates percentage change for specified columns and adds them as new columns.

Parameters

  • df (DataFrame) - DataFrame with time series data
  • cols (list) - List of column names to calculate percentage change for

Text to Zero Converter

convert_text_to_zero(value)

Converts text values, None, or NaN to zero, otherwise returns the numeric value.

Parameters

  • value (any) - Value to convert

List Deduplicator

dedup(lst)

Removes duplicate values from a list while preserving order.

Parameters

  • lst (list) - List with possible duplicates
|

Filter by Date

filtered = axion_utils.resample(
    data, 
    f"{axion_utils.weekago} {axion_utils.today}"
)

Filter by Values

tech_stocks = axion_utils.filter(
    stocks, 
    'sector', 
    ['Tech']
)

Calculate Returns

with_returns = axion_utils.relativity(
    prices, 
    ['price', 'volume']
)

Clean & Deduplicate

# Convert text to zero
cleaned = axion_utils.convert_text_to_zero('N/A')

# Remove duplicates
unique = axion_utils.dedup(['AAPL', 'GOOG', 'AAPL'])

DataFrame Combination

Functions for combining and merging multiple DataFrames in different ways.

Vertical Concatenation

stack(dfs)

Vertically concatenates multiple DataFrames with the same structure.

Parameters

  • dfs (list) - List of DataFrames to concatenate

Horizontal Merge

stitch(dfs, col='time')

Merges multiple DataFrames horizontally on a common column (inner join).

Parameters

  • dfs (list) - List of DataFrames to merge
  • col (str) - Column name to join on

Smart Merge with Renaming

snap(dfs, names=[], overwrite=[], col='time')

Merges DataFrames with intelligent column renaming and suffix management.

Parameters

  • dfs (list) - List of DataFrames to merge
  • names (list) - New names for columns
  • overwrite (list) - Columns to rename
  • col (str) - Merge column

Price Index Averager

indexed(prices)

Averages multiple price DataFrames (OHLCV) by timestamp to create a composite index.

Parameters

  • prices (dict) - Dictionary of ticker: DataFrame with OHLCV columns

Fact Averager

composite(dfs, joins=['fact', 'label'], col='value')

Combines and averages values from multiple fact/financial DataFrames.

Parameters

  • dfs (list) - List of DataFrames with financial facts
  • joins (list) - Columns to group by
  • col (str) - Column containing values to average

Fact Reshaper

contrast(dfs, joins, col="fact")

Reshapes multiple fact DataFrames into a single indexed DataFrame for graphing.

Parameters

  • dfs (list) - List of DataFrames with financial facts
  • joins (list) - Fact names to extract
  • col (str) - Column containing fact names
|

Vertical Stack

all_data = axion_utils.stack([q1_data, q2_data])

Horizontal Merge

combined = axion_utils.stitch([prices, economic])

Smart Merge

merged = axion_utils.snap(
    [company_a, company_b],
    names=['A', 'B'],
    overwrite=['revenue']
)

Create Index

index = axion_utils.indexed({
    'AAPL': aapl_df,
    'GOOG': goog_df
})

Average Estimates

consensus = axion_utils.composite([est1, est2])

Comparison Functions

Functions for comparing and analyzing differences between DataFrames.

Multi-DataFrame Comparer

compare(dfs, joins=['fact','value'])

Compares values across multiple DataFrames and calculates percentage differences.

Parameters

  • dfs (list) - List of DataFrames to compare
  • joins (list) - Columns to join and compare on

Set Difference Finder

difference(dfs, col)

Finds values in the first DataFrame that are not present in any subsequent DataFrame.

Parameters

  • dfs (list) - List of DataFrames
  • col (str) - Column name to compare

Set Overlap Finder

overlap(dfs, col)

Finds values that are present in all DataFrames.

Parameters

  • dfs (list) - List of DataFrames
  • col (str) - Column name to compare
|

Compare Estimates

comparison = axion_utils.compare([estimates_q1, estimates_q2])

Find Differences

added = axion_utils.difference([new, old], 'ticker')
removed = axion_utils.difference([old, new], 'ticker')

Find Overlap

common = axion_utils.overlap([fund_a, fund_b, fund_c], 'ticker')

Performance Analysis

Functions for analyzing price performance across multiple assets.

Top Gainers Finder

gainers(prices, frame, col='close', limit=500, relative=True, reverse=True)

Identifies assets with the highest price gains over a specified period.

Parameters

  • prices (dict) - Dictionary of ticker: DataFrame
  • frame (int) - Lookback period in rows
  • col (str) - Column to analyze
  • limit (int) - Maximum number of results
  • relative (bool) - Use percentage change or absolute change

Top Losers Finder

losers(prices, frame, col='close', relative=True, limit=500)

Wrapper function that calls gainers with reverse=False to find worst performers.

Parameters

  • prices (dict) - Dictionary of ticker: DataFrame
  • frame (int) - Lookback period in rows
  • col (str) - Column to analyze
  • limit (int) - Maximum number of results
  • relative (bool) - Use percentage change or absolute change
|

Find Gainers

top_gainers = axion_utils.gainers(
    prices, 
    frame=2, 
    limit=3
)

Find Losers

top_losers = axion_utils.losers(
    prices, 
    frame=2, 
    limit=3
)

Concurrency Function

Function for parallel processing of DataFrame rows.

Parallel Data Processor

work(df, cb, ref)

Processes DataFrame rows concurrently using a thread pool executor with progress bar.

Parameters

  • df (DataFrame) - DataFrame to process
  • cb (callable) - Callback function that processes each row
  • ref (dict) - Dictionary to store results (modified in place)
|

Parallel Processing

tickers = axion_utils.df([
    {'ticker': 'AAPL'},
    {'ticker': 'GOOG'},
    {'ticker': 'MSFT'},
])

def fetch_data(row):
    ticker = row['ticker']
    return ticker, {'price': 150.25}

results = {}
axion_utils.work(tickers, fetch_data, results)

Required Dependencies

These utility functions require the following Python packages:

Core Libraries

  • pandas - Data manipulation
  • numpy - Numerical operations
  • pickle - Object serialization
  • os - File system operations

Additional Libraries

  • parsedatetime - Natural language date parsing
  • datetime - Date/time manipulation
  • concurrent.futures - Thread pool executor
  • tqdm - Progress bars

Visualization Methods

A collection of visualization functions for financial and data analysis using Plotly.js. These methods provide interactive charts and graphs for data exploration and presentation.

visualize (Core Helper)

HELPERvisualize.visualize(fig)

Displays a Plotly figure object. This is the core visualization function used internally by all other methods. In Jupyter notebooks, this will render the chart inline. In scripts, it will open the chart in a browser.

Parameters

ParameterTypeRequiredDescription
figplotly.graph_objects.FigureRequiredPlotly figure object to display
|

Example

# Create a simple figure
import plotly.graph_objects as go
fig = go.Figure(data=go.Scatter(x=[1,2,3], y=[4,5,6]))

# Display it
visualize.visualize(fig)

visualize.cov()

FUNCTIONvisualize.cov(df)

Creates a heatmap visualization of the correlation matrix for numeric columns in a DataFrame. Uses the Viridis color scale and automatically handles the correlation calculation.

Parameters

ParameterTypeRequiredDescription
dfpandas.DataFrameRequiredDataFrame containing numeric columns for correlation analysis. Non-numeric columns are automatically ignored.
|

Example

import pandas as pd
from axion import visualize

# Create sample data
df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': [2, 4, 6, 8, 10],
    'C': [5, 4, 3, 2, 1],
    'D': [1, 3, 5, 7, 9]
})

# Display correlation heatmap
visualize.cov(df)

visualize.candles()

FUNCTIONvisualize.candles(df)

Creates an interactive candlestick chart for financial price data with OHLC (Open, High, Low, Close) values. Perfect for stock prices, cryptocurrency data, or any time-series financial data.

Required DataFrame Columns

  • time - Time series data (dates/timestamps)
  • open - Opening price for each period
  • high - Highest price during each period
  • low - Lowest price during each period
  • close - Closing price for each period
|

Example

import pandas as pd
from axion import visualize

# Sample stock data
df = pd.DataFrame({
    'time': ['2024-01-01', '2024-01-02', '2024-01-03'],
    'open': [100, 102, 101],
    'high': [105, 103, 104],
    'low': [99, 101, 100],
    'close': [102, 101, 103]
})

# Display candlestick chart
visualize.candles(df)

visualize.line()

FUNCTIONvisualize.line(df, x, y, log=False)

Creates a line chart for time series or sequential data visualization. Supports logarithmic scaling for the x-axis.

Parameters

ParameterTypeDefaultDescription
dfpandas.DataFrame-DataFrame containing the data to plot
xstring-Column name for x-axis values (typically time/date)
ystring-Column name for y-axis values
logbooleanFalseUse logarithmic scale for x-axis
|

Examples

Basic Line Chart

# Basic line chart
df = pd.DataFrame({
    'date': ['2024-01-01', '2024-01-02', '2024-01-03'],
    'value': [10, 15, 13]
})
visualize.line(df, x='date', y='value')

Logarithmic X-Axis

# Line chart with logarithmic x-axis
df = pd.DataFrame({
    'x': [1, 10, 100, 1000],
    'y': [1, 2, 3, 4]
})
visualize.line(df, x='x', y='y', log=True)

visualize.pie()

FUNCTIONvisualize.pie(df, values, labels)

Creates a pie chart showing proportional distribution of categorical data. Each slice represents a category, and the size corresponds to the numeric values.

Parameters

ParameterTypeRequiredDescription
dfpandas.DataFrameRequiredDataFrame containing the data
valuesstringRequiredColumn name for pie slice sizes (numeric)
labelsstringRequiredColumn name for pie slice labels (categorical)
|

Example

# Market share data
df = pd.DataFrame({
    'company': ['Apple', 'Samsung', 'Google', 'Others'],
    'market_share': [45, 30, 15, 10]
})

visualize.pie(df, values='market_share', labels='company')

visualize.fit()

FUNCTIONvisualize.fit(df, x, y, log=False, hover=[], group=None)

Creates a scatter plot with an Ordinary Least Squares (OLS) trendline for regression analysis. The trendline shows the linear relationship between variables with confidence bands.

Parameters

ParameterTypeDefaultDescription
dfpandas.DataFrame-DataFrame containing the data
xstring-Column name for x-axis values (independent variable)
ystring-Column name for y-axis values (dependent variable)
logbooleanFalseUse logarithmic scale for x-axis
hoverlist[]List of column names to show in hover tooltips
groupstringNoneColumn name for color grouping (creates separate trendlines per group)
|

Examples

With Grouping

# Simple linear regression
df = pd.DataFrame({
    'x': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    'y': [2, 4, 5, 4, 5, 7, 8, 9, 10, 12],
    'category': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B']
})

# With grouping
visualize.fit(df, x='x', y='y', group='category', hover=['category'])

# Without grouping
visualize.fit(df, x='x', y='y')

visualize.scatter()

FUNCTIONvisualize.scatter(df, x, y, log=False, hover=[], group=None)

Creates a standard scatter plot for visualizing relationships between two variables. Supports grouping and hover data for enhanced data exploration.

Parameters

ParameterTypeDefaultDescription
dfpandas.DataFrame-DataFrame containing the data
xstring-Column name for x-axis values
ystring-Column name for y-axis values
logbooleanFalseUse logarithmic scale for x-axis
hoverlist[]List of column names to show in hover tooltips
groupstringNoneColumn name for color grouping
|

Examples

With Grouping

# Scatter plot with grouping and hover data
df = pd.DataFrame({
    'height': [150, 160, 170, 180, 155, 165, 175, 185],
    'weight': [50, 60, 70, 80, 55, 65, 75, 85],
    'gender': ['F', 'F', 'M', 'M', 'F', 'F', 'M', 'M'],
    'age': [25, 30, 35, 40, 28, 33, 38, 43]
})

visualize.scatter(df, x='height', y='weight', 
                  group='gender', hover=['age'])

Simple Scatter

# Simple scatter
visualize.scatter(df, x='height', y='weight')

visualize.bar()

FUNCTIONvisualize.bar(df, x, y)

Creates a vertical bar chart for categorical data comparison. Each bar represents a category, and the height represents the corresponding value.

Parameters

ParameterTypeRequiredDescription
dfpandas.DataFrameRequiredDataFrame containing the data
xstringRequiredColumn name for categories (x-axis)
ystringRequiredColumn name for values (bar heights)
|

Example

# Sales by product
df = pd.DataFrame({
    'product': ['A', 'B', 'C', 'D'],
    'sales': [1500, 2300, 1200, 3100]
})

visualize.bar(df, x='product', y='sales')

visualize.area()

FUNCTIONvisualize.area(df, x, y, group, sub="")

Creates a stacked area chart showing cumulative values over time by category. Great for visualizing composition changes over time.

Parameters

ParameterTypeDefaultDescription
dfpandas.DataFrame-DataFrame containing the data
xstring-Column name for x-axis (typically time/date)
ystring-Column name for y-axis values
groupstring-Column name for grouping/categories
substring""Subgroup identifier (currently unused)
|

Example

# Monthly sales by region
df = pd.DataFrame({
    'month': ['Jan', 'Jan', 'Feb', 'Feb', 'Mar', 'Mar'],
    'sales': [100, 150, 120, 180, 140, 200],
    'region': ['North', 'South', 'North', 'South', 'North', 'South']
})

visualize.area(df, x='month', y='sales', group='region')

visualize.heatmap()

FUNCTIONvisualize.heatmap(df, x, y, hover=[])

Creates a density heatmap showing the distribution of data points across two dimensions. The color intensity represents the density of points in each region.

Parameters

ParameterTypeDefaultDescription
dfpandas.DataFrame-DataFrame containing the data
xstring-Column name for x-axis values
ystring-Column name for y-axis values
hoverlist[]List of column names to show in hover tooltips
|

Example

# Create sample data with clusters
import numpy as np
import SEOMetadata from '@/components/SEOMetadata';
np.random.seed(42)
df = pd.DataFrame({
    'x': np.random.normal(0, 1, 1000),
    'y': np.random.normal(0, 1, 1000),
    'value': np.random.randn(1000)
})

visualize.heatmap(df, x='x', y='y', hover=['value'])

visualize.radar()

FUNCTIONvisualize.radar(df, values, labels)

Creates a radar chart for multivariate data visualization across multiple axes. Each axis represents a different variable, and the area shows the profile.

Parameters

ParameterTypeRequiredDescription
dfpandas.DataFrameRequiredDataFrame containing a single row of data
valuesstringRequiredColumn name containing the numeric values
labelsstringRequiredColumn name containing the axis labels
|

Example

# Product performance metrics
df = pd.DataFrame({
    'metric': ['Speed', 'Reliability', 'Cost', 'Quality', 'Support'],
    'score': [85, 92, 78, 95, 88]
})

visualize.radar(df, values='score', labels='metric')

visualize.barh()

FUNCTIONvisualize.barh(df, x, y)

Creates a horizontal bar chart, useful for comparing categories with long names or when you have many categories. Bars extend horizontally from the y-axis.

Parameters

ParameterTypeRequiredDescription
dfpandas.DataFrameRequiredDataFrame containing the data
xstringRequiredColumn name for values (bar lengths)
ystringRequiredColumn name for categories (y-axis labels)
|

Example

# Long category names
df = pd.DataFrame({
    'product': ['Enterprise License', 'Professional Edition', 
                'Standard Package', 'Basic Subscription'],
    'revenue': [150000, 85000, 45000, 20000]
})

visualize.barh(df, x='revenue', y='product')

visualize.spread()

FUNCTIONvisualize.spread(dfs, x, y)

Creates a composite chart showing two series and their difference (spread) as a bar chart. Perfect for pairs trading analysis or comparing two related time series.

Parameters

ParameterTypeRequiredDescription
dfslist of DataFramesRequiredList containing two DataFrames to compare
xstringRequiredCommon column name for merging and x-axis (usually time/date)
ystringRequiredColumn name for values in both DataFrames
|

Example

# Compare two correlated stocks
df1 = pd.DataFrame({
    'date': ['2024-01-01', '2024-01-02', '2024-01-03'],
    'price': [100, 102, 101]
})

df2 = pd.DataFrame({
    'date': ['2024-01-01', '2024-01-02', '2024-01-03'],
    'price': [98, 101, 103]
})

visualize.spread([df1, df2], x='date', y='price')

visualize.polls()

FUNCTIONvisualize.polls(df)

Creates a multi-line chart where each column in the DataFrame becomes a separate line series. The x-axis uses the DataFrame index, making it ideal for time series with multiple variables.

Parameters

ParameterTypeRequiredDescription
dfpandas.DataFrameRequiredDataFrame where each column becomes a line series. Index is used for x-axis.
|

Example

# Opinion polling over time
df = pd.DataFrame({
    'Candidate A': [45, 47, 46, 48, 50, 49],
    'Candidate B': [42, 41, 43, 42, 41, 43],
    'Undecided': [13, 12, 11, 10, 9, 8]
}, index=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'])

visualize.polls(df)

visualize.tree()

FUNCTIONvisualize.tree(df)

Creates a hierarchical treemap visualization for nested categorical data. Rectangles represent hierarchy levels, with size proportional to marketCap and color indicating pctchange.

Expected DataFrame Columns

  • sector - Top-level category (e.g., Technology, Healthcare)
  • industry - Mid-level category (e.g., Software, Biotech)
  • symbol - Leaf-level identifier (e.g., AAPL, MSFT)
  • marketCap - Size value (determines rectangle area)
  • pctchange - Color/hover data (red-green color scale)
  • lastsale - Additional hover data (last sale price)
|

Example

# Stock market sector visualization
df = pd.DataFrame({
    'sector': ['Tech', 'Tech', 'Tech', 'Health', 'Health'],
    'industry': ['Software', 'Software', 'Hardware', 'Biotech', 'Pharma'],
    'symbol': ['AAPL', 'MSFT', 'NVDA', 'GILD', 'PFE'],
    'marketCap': [2500000, 2100000, 800000, 700000, 180000],
    'pctchange': [2.5, 1.8, -0.5, 3.2, -1.1],
    'lastsale': [175.50, 380.25, 450.75, 85.30, 42.60]
})

visualize.tree(df)

visualize.graph()

FUNCTIONvisualize.graph(df, x, bars=[], lines=[], areas=[], title='', color=None)

Creates a comprehensive composite chart combining bars, lines, and areas on the same plot. Offers maximum flexibility for complex visualizations with multiple series types.

Parameters

ParameterTypeDefaultDescription
dfpandas.DataFrame-DataFrame containing all data
xstring-Column name for x-axis values
barslist[]List of column names for bar series
lineslist[]List of column names for line series
areaslist[]List of column names for area series
titlestring''Chart title
colorstringNoneColumn name for color grouping bars

Color Palette

shades_of_white = [
    'rgb(31, 119, 180)',  // blue
    'rgb(255, 127, 14)',  // orange
    'rgb(44, 160, 44)',   // green
    'rgb(214, 39, 40)',   // red
    'rgb(148, 103, 189)', // purple
    'rgb(140, 86, 75)',   // brown
    'rgb(255, 255, 255)',
    'rgb(245, 245, 245)',
    'rgb(235, 235, 235)',
    'rgb(235, 225, 225)',
    'rgb(235, 215, 215)',
    'rgb(235, 205, 205)',
]
|

Examples

Composite Chart

# Composite chart with bars and lines
df = pd.DataFrame({
    'date': ['2024-01-01', '2024-01-02', '2024-01-03'],
    'revenue': [1000, 1200, 1100],
    'profit': [200, 250, 230],
    'users': [500, 600, 650],
    'region': ['North', 'South', 'North']
})

visualize.graph(df, x='date', 
                bars=['revenue'], 
                lines=['profit', 'users'],
                title='Company Performance')

With Color Grouping

# With color grouping for bars
visualize.graph(df, x='date', 
                bars=['revenue'], 
                lines=['profit'],
                color='region',
                title='Performance by Region')