Logo
AXION

Python SDK Models

Time Series Models

Statistical and machine learning models for time series forecasting and analysis.

linearRegression

FUNCTIONlinearRegression(df, x, target, n_preds=10, scale='D')

Simple linear regression model for time series forecasting using scikit-learn's LinearRegression.

Parameters

ParameterTypeRequiredDescription
dfpandas.DataFrameRequiredDataFrame containing time series data
xstringRequiredColumn name for datetime values
targetstringRequiredColumn name for target variable to predict
n_predsintOptionalNumber of future periods to predict (default: 10)
scalestringOptionalpandas frequency string for future dates (default: 'D' for daily)

Returns

Returns a pandas.DataFrame with two columns: the x column (future dates) and target column (predicted values).

|

Usage Example

Python

from axion import models
import pandas as pd

# Sample data
df = pd.DataFrame({
    'date': pd.date_range('2023-01-01', periods=100, freq='D'),
    'value': range(100)
})

# Make predictions
predictions = models.linearRegression(
    df=df,
    x='date',
    target='value',
    n_preds=5,
    scale='D'
)
print(predictions)

multiLinearRegression

FUNCTIONmultiLinearRegression(df, x, target, features, n_preds=10, scale='D')

Multiple linear regression model that uses additional features for time series forecasting.

Parameters

ParameterTypeRequiredDescription
dfpandas.DataFrameRequiredDataFrame containing time series data
xstringRequiredColumn name for datetime values
targetstringRequiredColumn name for target variable to predict
featureslistRequiredList of feature column names to use for prediction
n_predsintOptionalNumber of future periods to predict (default: 10)
scalestringOptionalpandas frequency string for future dates (default: 'D')

Returns

Returns a pandas.DataFrame with 'time' and target columns containing future predictions.

|

Usage Example

Python

from axion import models
import pandas as pd

# Sample data with features
df = pd.DataFrame({
    'date': pd.date_range('2023-01-01', periods=100, freq='D'),
    'value': range(100),
    'feature1': [i * 1.5 for i in range(100)],
    'feature2': [i * 0.5 for i in range(100)]
})

# Make predictions using multiple features
predictions = models.multiLinearRegression(
    df=df,
    x='date',
    target='value',
    features=['feature1', 'feature2'],
    n_preds=5,
    scale='D'
)
print(predictions)

beta

FUNCTIONbeta(df, x, y)

Calculates the beta coefficient (slope) between two time series using linear regression.

Parameters

ParameterTypeRequiredDescription
dfpandas.DataFrameRequiredDataFrame containing both time series
xstringRequiredColumn name for dependent variable
ystringRequiredColumn name for independent variable

Returns

Returns a float representing the beta coefficient (regression slope) of x on y.

|

Usage Example

Python

from axion import models
import pandas as pd

# Sample data
df = pd.DataFrame({
    'stock_returns': [0.01, 0.02, -0.01, 0.03, 0.01],
    'market_returns': [0.005, 0.015, -0.005, 0.025, 0.01]
})

# Calculate beta coefficient
beta_value = models.beta(
    df=df,
    x='stock_returns',
    y='market_returns'
)
print(f"Beta: {beta_value}")

lstm

FUNCTIONlstm(df, x, target, features=[], n_preds=10, scale='D')

LSTM (Long Short-Term Memory) neural network for time series forecasting using TensorFlow/Keras.

Parameters

ParameterTypeRequiredDescription
dfpandas.DataFrameRequiredDataFrame containing time series data
xstringRequiredColumn name for datetime values
targetstringRequiredColumn name for target variable to predict
featureslistOptionalList of additional feature columns (default: empty list)
n_predsintOptionalNumber of future periods to predict (default: 10)
scalestringOptionalpandas frequency string for future dates (default: 'D')

Returns

Returns a pandas.DataFrame with 'time' and target columns containing future predictions.

Helper Function

create_sequences(data, sequence_length, n_preds) - Creates sequences for LSTM training.

|

Usage Example

Python

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

# Sample data
df = pd.DataFrame({
    'date': pd.date_range('2023-01-01', periods=200, freq='D'),
    'value': [i + 10 * (i % 7) for i in range(200)],
    'feature': [i * 0.5 for i in range(200)]
})

# Make predictions using LSTM
predictions = models.lstm(
    df=df,
    x='date',
    target='value',
    features=['feature'],
    n_preds=5,
    scale='D'
)
print(predictions)

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