To prepare your DataFrame for training a transformer model, you'll need to ensure all features are numerical. This involves converting any categorical string columns into numerical representations while preserving their informational content. Here's how you can achieve this:
-
Identify Categorical Columns:
- Ordinal Categories: These have a meaningful order (e.g.,
'Low', 'Medium', 'High').
- Nominal Categories: These do not have an inherent order (e.g.,
'Bullish', 'Bearish', 'Neutral').
-
Choose Appropriate Encoding Techniques:
- Ordinal Encoding: For ordinal categories where the order matters.
- One-Hot Encoding: For nominal categories where no order exists.
-
Implement Encoding in Your Data Processing Pipeline:
- After adding technical indicators and classifying market environments, apply encoding to categorical columns.
Below is the modified code with detailed steps and explanations:
import numpy as np
import pandas as pd
from ta.momentum import RSIIndicator
from ta.trend import MACD, ADXIndicator
from ta.volatility import AverageTrueRange, BollingerBands
from sklearn.preprocessing import OrdinalEncoder, OneHotEncoder
def add_technical_indicators(df):
"""
Add technical indicators to the DataFrame.
"""
# RSI
rsi = RSIIndicator(close=df['close'], window=14)
df['RSI'] = rsi.rsi()
# MACD
macd = MACD(close=df['close'], window_slow=26, window_fast=12, window_sign=9)
df['MACD'] = macd.macd()
df['MACD_signal'] = macd.macd_signal()
df['MACD_diff'] = macd.macd_diff()
# ATR
atr = AverageTrueRange(high=df['high'], low=df['low'], close=df['close'], window=14)
df['ATR'] = atr.average_true_range()
# Bollinger Bands Width
bollinger = BollingerBands(close=df['close'], window=20, window_dev=2)
df['BB_upper'] = bollinger.bollinger_hband()
df['BB_lower'] = bollinger.bollinger_lband()
df['BB_width'] = (df['BB_upper'] - df['BB_lower']) / df['close']
# ADX
adx = ADXIndicator(high=df['high'], low=df['low'], close=df['close'], window=14)
df['ADX'] = adx.adx()
# Drop initial rows with NaN values
df.dropna(inplace=True)
return df
def classify_market_environments(df):
"""
Classify market environments into nine categories based on volatility and trend.
"""
# Volatility Classification
# ATR
df['ATR_mavg'] = df['ATR'].rolling(window=14).mean()
df['ATR_vol'] = np.where(df['ATR'] > 1.2 * df['ATR_mavg'], 'High',
np.where(df['ATR'] < 0.8 * df['ATR_mavg'], 'Low', 'Medium'))
# Bollinger Bands Width Classification
df['BB_mavg'] = df['BB_width'].rolling(window=20).mean()
df['BB_vol'] = np.where(df['BB_width'] > 1.2 * df['BB_mavg'], 'High',
np.where(df['BB_width'] < 0.8 * df['BB_mavg'], 'Low', 'Medium'))
# Realized Volatility Classification
df['daily_return'] = df['close'].pct_change()
df['RV'] = df['daily_return'].rolling(window=20).std() * np.sqrt(252)
rv_80 = df['RV'].quantile(0.8)
rv_20 = df['RV'].quantile(0.2)
df['RV_vol'] = np.where(df['RV'] > rv_80, 'High',
np.where(df['RV'] < rv_20, 'Low', 'Medium'))
# Voting Mechanism for Volatility
df['Volatility'] = df[['ATR_vol', 'BB_vol', 'RV_vol']].mode(axis=1)[0]
# Trend Classification
df['Trend'] = np.where((df['MACD'] > df['MACD_signal']) & (df['MACD'] > 0), 'Bullish',
np.where((df['MACD'] < df['MACD_signal']) & (df['MACD'] < 0), 'Bearish', 'Neutral'))
# ADX Classification
df['Trend_strength'] = np.where(df['ADX'] > 25, 'Strong', 'Weak')
# Final Market Environment
df['Market_Environment'] = df.apply(
lambda row: f"{row['Volatility']} Vol/{row['Trend']}" if row['Trend_strength'] == 'Strong'
else f"{row['Volatility']} Vol/Neutral", axis=1
)
return df
def encode_categorical_features(df):
"""
Convert categorical string columns to numerical values using appropriate encoding techniques.
"""
# Define the ordinal and nominal columns
ordinal_columns = {
'ATR_vol': {'Low': 0, 'Medium': 1, 'High': 2},
'BB_vol': {'Low': 0, 'Medium': 1, 'High': 2},
'RV_vol': {'Low': 0, 'Medium': 1, 'High': 2},
'Volatility': {'Low Vol': 0, 'Medium Vol': 1, 'High Vol': 2}, # Adjust keys as per actual labels
}
nominal_columns = ['Trend', 'Market_Environment']
# Encode Ordinal Columns
for col, mapping in ordinal_columns.items():
df[col] = df[col].map(mapping)
# One-Hot Encode Nominal Columns
df = pd.get_dummies(df, columns=nominal_columns, drop_first=True)
# Drop unnecessary columns (optional)
# If you have multi-level encoded features or combinations you don't need, drop them here.
return df
def preprocess_dataframe(df):
"""
Complete preprocessing pipeline: add indicators, classify environments, and encode categorical features.
"""
df = add_technical_indicators(df)
df = classify_market_environments(df)
df = encode_categorical_features(df)
return df
# Example usage:
# Assuming `df` is your initial DataFrame with 'close', 'high', 'low' columns
# df = preprocess_dataframe(df)
Detailed Explanation:
-
Adding Technical Indicators:
- The
add_technical_indicators function computes various technical indicators like RSI, MACD, ATR, Bollinger Bands Width, and ADX. It also drops any initial rows with NaN values resulting from indicator calculations.
-
Classifying Market Environments:
- The
classify_market_environments function categorizes volatility based on ATR, Bollinger Bands Width, and Realized Volatility (RV). It also assesses the trend as Bullish, Bearish, or Neutral based on MACD and determines trend strength using ADX.
- Finally, it consolidates these classifications into a
Market_Environment column.
-
Encoding Categorical Features:
-
Ordinal Encoding:
- For columns like
'ATR_vol', 'BB_vol', 'RV_vol', and 'Volatility', which have an inherent order ('Low' < 'Medium' < 'High'), we map their string values to integers.
- Update the
ordinal_columns dictionary if the label names differ. Ensure that the keys in the mapping correspond exactly to the actual category labels in your DataFrame.
-
One-Hot Encoding:
- For nominal columns like
'Trend' and 'Market_Environment', which do not have an inherent order, we use one-hot encoding. This creates separate binary columns for each category, excluding the first to avoid multicollinearity (drop_first=True).
-
Flexibility:
- If you have more nominal or ordinal columns, extend the
ordinal_columns and nominal_columns lists accordingly.
- If
'Market_Environment' creates a large number of unique categories, consider whether all of them are necessary or if dimensionality reduction techniques are needed.
-
Preprocessing Pipeline:
- The
preprocess_dataframe function ties everything together, ensuring that your DataFrame is fully prepared with both numerical and encoded categorical features, making it suitable for training transformer models.
-
Handling Market_Environment:
- The
Market_Environment column is a combination of Volatility and Trend. Depending on the number of unique combinations, one-hot encoding might significantly increase dimensionality. Ensure your model can handle this or consider alternative encoding strategies like embedding layers if using neural networks.
Additional Recommendations:
-
Scaling Numerical Features:
- Transformer models often benefit from feature scaling. Consider applying scaling techniques like StandardScaler or MinMaxScaler to your numerical features after encoding categorical variables.
from sklearn.preprocessing import StandardScaler
def scale_features(df, feature_columns):
scaler = StandardScaler()
df[feature_columns] = scaler.fit_transform(df[feature_columns])
return df
-
Handling Missing Values:
- Ensure that there are no remaining missing values after encoding. You might need to fill or drop them based on your specific case.
-
Feature Selection:
- Review the importance of each feature. Some encoded features, especially from high-cardinality categorical variables, might introduce noise.
-
Data Splitting:
- Before training, split your data into training, validation, and test sets to evaluate model performance effectively.
By following this approach, you convert all string-based categorical features into numerical values suitable for training transformer models, ensuring that the inherent relationships in your data are preserved through appropriate encoding techniques.