Time Series Models
Statistical and machine learning models for time series forecasting and analysis.
linearRegression
linearRegression(df, x, target, n_preds=10, scale='D')Simple linear regression model for time series forecasting using scikit-learn's LinearRegression.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| df | pandas.DataFrame | Required | DataFrame containing time series data |
| x | string | Required | Column name for datetime values |
| target | string | Required | Column name for target variable to predict |
| n_preds | int | Optional | Number of future periods to predict (default: 10) |
| scale | string | Optional | pandas 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
multiLinearRegression(df, x, target, features, n_preds=10, scale='D')Multiple linear regression model that uses additional features for time series forecasting.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| df | pandas.DataFrame | Required | DataFrame containing time series data |
| x | string | Required | Column name for datetime values |
| target | string | Required | Column name for target variable to predict |
| features | list | Required | List of feature column names to use for prediction |
| n_preds | int | Optional | Number of future periods to predict (default: 10) |
| scale | string | Optional | pandas 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
beta(df, x, y)Calculates the beta coefficient (slope) between two time series using linear regression.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| df | pandas.DataFrame | Required | DataFrame containing both time series |
| x | string | Required | Column name for dependent variable |
| y | string | Required | Column 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
lstm(df, x, target, features=[], n_preds=10, scale='D')LSTM (Long Short-Term Memory) neural network for time series forecasting using TensorFlow/Keras.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| df | pandas.DataFrame | Required | DataFrame containing time series data |
| x | string | Required | Column name for datetime values |
| target | string | Required | Column name for target variable to predict |
| features | list | Optional | List of additional feature columns (default: empty list) |
| n_preds | int | Optional | Number of future periods to predict (default: 10) |
| scale | string | Optional | pandas 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)
roc(df, column="close", period=10)Calculates the Rate of Change percentage over a specified period.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 10 | Lookback period for ROC calculation |
Returns
Returns a pandas Series with ROC percentage values.
Formula
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: float64Momentum
mom(df, column="close", period=10)Calculates the difference between current price and price n periods ago.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 10 | Lookback period for momentum calculation |
Returns
Returns a pandas Series with momentum values (price difference).
Formula
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: float64Simple Moving Average
sma(df, column="close", period=14)Calculates the Simple Moving Average over a specified period.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 14 | Lookback period for SMA calculation |
Returns
Returns a pandas Series with Simple Moving Average values.
Formula
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: float64Simple Moving Median
smm(df, column="close", period=14)Calculates the median value over a specified rolling window.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 14 | Lookback period for median calculation |
Returns
Returns a pandas Series with moving median values.
Formula
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: float64Smoothed Simple Moving Average
ssma(df, column="close", period=14)Calculates a smoothed version of the Simple Moving Average using exponential smoothing.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 14 | Lookback period for SSMA calculation |
Returns
Returns a pandas Series with smoothed moving average values.
Formula
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: float64Exponential Moving Average
ema(df, column="close", period=14)Calculates the Exponential Moving Average which gives more weight to recent prices.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 14 | Lookback period for EMA calculation |
Returns
Returns a pandas Series with Exponential Moving Average values.
Formula
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: float64Double Exponential Moving Average
dema(df, column="close", period=14)Calculates the Double EMA, which applies EMA smoothing twice for reduced lag.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 14 | Lookback period for DEMA calculation |
Returns
Returns a pandas Series with Double Exponential Moving Average values.
Formula
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: float64Triangular Moving Average
trima(df, column="close", period=14)Calculates a double-smoothed moving average for reduced noise.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 14 | Lookback period for TRIMA calculation |
Returns
Returns a pandas Series with Triangular Moving Average values.
Formula
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: float64Average True Range
atr(df, period=14)Measures market volatility by calculating the average of true ranges over a period.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
| period | int | 14 | Lookback period for ATR calculation |
Returns
Returns a pandas Series with Average True Range values.
True Range Calculation
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: float64Stochastic Oscillator
stochastic_oscillator(df, k_period=14, d_period=3)Calculates %K and %D stochastic oscillator values to identify overbought/oversold conditions.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
| k_period | int | 14 | Lookback period for %K calculation |
| d_period | int | 3 | Smoothing period for %D |
Returns
Returns two pandas Series: %K (fast stochastic) and %D (slow stochastic).
Formula
%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: float64Chande Momentum Oscillator
cmo(df, column="close", period=20)Measures momentum by comparing sum of gains to sum of losses over a period.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 20 | Lookback period for CMO calculation |
Returns
Returns a pandas Series with CMO values ranging from -100 to +100.
Formula
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: float64On Balance Volume
obv(df)Cumulatively adds or subtracts volume based on price direction to measure buying/selling pressure.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'close' and 'volume' columns |
Returns
Returns a pandas Series with cumulative On Balance Volume values.
Formula
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: int64Volume Price Trend
vpt(df)Measures the relationship between volume and price changes by cumulating volume adjusted by price percentage changes.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'close' and 'volume' columns |
Returns
Returns a pandas Series with cumulative Volume Price Trend values.
Formula
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: float64Volume-Weighted Average Price
vwap(df, period=14)Calculates the average price weighted by volume over a specified period.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close', 'volume' columns |
| period | int | 14 | Rolling period for VWAP calculation |
Returns
Returns a pandas Series with Volume-Weighted Average Price values.
Formula
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: float64Bollinger Bands
bbands(df, column="close", period=20, num_std_dev=2)Calculates upper and lower Bollinger Bands around a simple moving average.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 20 | Lookback period for SMA calculation |
| num_std_dev | int/float | 2 | Number of standard deviations for bands |
Returns
Returns three pandas Series: upper_band, middle_band (SMA), lower_band.
Formula
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: float64Keltner Channels
kc(df, period=20, atr_period=10, multiplier=2)Calculates volatility-based channels using ATR around an exponential moving average.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
| period | int | 20 | EMA period for middle line |
| atr_period | int | 10 | Period for ATR calculation |
| multiplier | int/float | 2 | ATR multiplier for channel width |
Returns
Returns three pandas Series: upper_channel, middle_line, lower_channel.
Formula
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: float64Kaufman's Adaptive Moving Average
kama(df, column="close", period=14, fast=14, slow=30)Adaptive moving average that adjusts its sensitivity based on market volatility.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 14 | Efficiency ratio period |
| fast | int | 14 | Fast EMA constant period |
| slow | int | 30 | Slow EMA constant period |
Returns
Returns a pandas Series with Kaufman's Adaptive Moving Average values.
Formula
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: float64Vortex Indicator
vi(df, period=14)Measures trend direction and strength using positive and negative vortex movements.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
| period | int | 14 | Lookback 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: float64Moving Average Convergence Divergence
macd(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
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| fast_period | int | 12 | Fast EMA period |
| slow_period | int | 26 | Slow EMA period |
| signal_period | int | 9 | Signal line EMA period |
Returns
Returns three pandas Series: macd_line, signal_line, histogram.
Formula
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: float64Williams %R
williams_r(df, period=14)Momentum indicator measuring overbought/oversold levels, similar to stochastic oscillator.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
| period | int | 14 | Lookback period for Williams %R |
Returns
Returns a pandas Series with Williams %R values ranging from -100 to 0.
Formula
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: float64Average Directional Index
adx(df, period=14)Measures trend strength without regard to direction.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
| period | int | 14 | Lookback period for ADX calculation |
Returns
Returns a pandas Series with Average Directional Index values.
Formula
-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: float64Relative Strength Index
rsi(df, column="close", period=14)Measures speed and change of price movements to identify overbought/oversold conditions.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Pandas DataFrame containing price data |
| column | string | "close" | Column name for price data |
| period | int | 14 | Lookback period for RSI calculation |
Returns
Returns a pandas Series with RSI values ranging from 0 to 100.
Formula
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: float64Ichimoku Cloud
ichi(df)Comprehensive indicator that provides support/resistance, trend direction, and momentum.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
Returns
Returns five pandas Series: conversion_line, base_line, leading_span_a, leading_span_b, lagging_span.
Formula
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
sar(df, af=0.02, af_max=0.2)Trend-following indicator that provides potential reversal points.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
| af | float | 0.02 | Acceleration factor increment |
| af_max | float | 0.2 | Maximum acceleration factor |
Returns
Returns a pandas Series with Parabolic SAR values.
Formula
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: float64Fibonacci Pivot Points
fib(df)Calculates Fibonacci-based support and resistance levels using previous period's high, low, and close.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| df | DataFrame | - | Must contain 'high', 'low', 'close' columns |
Returns
Returns seven pandas Series: PP, R1, S1, R2, S2, R3, S3.
Formulas
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: float64Data Requirements
Most functions require specific columns in the DataFrame. Below are the common requirements:
Basic Price Data
close- Closing pricehigh- Highest pricelow- Lowest pricevolume- 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
| Constant | Value | Description |
|---|---|---|
| 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
| Constant | Value | Description |
|---|---|---|
| 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 Truefalse = FalsePython boolean FalseCaching 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 entryfn(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 entryobj(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 processid(str) - Cache identifiercb(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 formatforce(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 -> MondayDataFrame 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 filterdates(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 filtercol(str) - Column name to filter onitems(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 datacols(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 mergecol(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 mergenames(list) - New names for columnsoverwrite(list) - Columns to renamecol(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 factsjoins(list) - Columns to group bycol(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 factsjoins(list) - Fact names to extractcol(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 comparejoins(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 DataFramescol(str) - Column name to compare
Set Overlap Finder
overlap(dfs, col)Finds values that are present in all DataFrames.
Parameters
dfs(list) - List of DataFramescol(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: DataFrameframe(int) - Lookback period in rowscol(str) - Column to analyzelimit(int) - Maximum number of resultsrelative(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: DataFrameframe(int) - Lookback period in rowscol(str) - Column to analyzelimit(int) - Maximum number of resultsrelative(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 processcb(callable) - Callback function that processes each rowref(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 manipulationnumpy- Numerical operationspickle- Object serializationos- File system operations
Additional Libraries
parsedatetime- Natural language date parsingdatetime- Date/time manipulationconcurrent.futures- Thread pool executortqdm- Progress bars