Development of Crypto Asset Behavior Clustering Model
Clustering cryptocurrencies by behavioral patterns allows automatic grouping of assets with similar characteristics. This is useful for: building diversified portfolios, finding asset replacements within a cluster, understanding market structure.
Feature Engineering for Clustering
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
def create_behavioral_features(prices_dict, lookback_days=90):
features = {}
for symbol, price_series in prices_dict.items():
returns = price_series.pct_change().dropna()
if len(returns) < lookback_days * 24: # hourly data
continue
recent_returns = returns.iloc[-lookback_days*24:]
features[symbol] = {
# Return characteristics
'annualized_return': recent_returns.mean() * 365 * 24,
'annualized_vol': recent_returns.std() * np.sqrt(365 * 24),
'sharpe': recent_returns.mean() / (recent_returns.std() + 1e-8) * np.sqrt(365*24),
# Distribution shape
'skewness': recent_returns.skew(),
'kurtosis': recent_returns.kurt(),
# Tail risk
'var_95': np.percentile(recent_returns, 5),
'cvar_95': recent_returns[recent_returns <= np.percentile(recent_returns, 5)].mean(),
# Trend characteristics
'momentum_30d': price_series.iloc[-720:].pct_change(720).iloc[-1], # 30d return
'trend_strength': abs(recent_returns.mean()) / (recent_returns.std() + 1e-8),
# Drawdown
'max_drawdown': calculate_max_drawdown(price_series.iloc[-lookback_days*24:]),
# Correlation with BTC
'btc_corr': recent_returns.corr(prices_dict.get('BTC', pd.Series()).pct_change().dropna()),
# Volume-based (if available)
'avg_daily_volume_usd': get_avg_daily_volume(symbol),
}
return pd.DataFrame(features).T
Clustering Algorithms
K-Means — classic, fast, assumes spherical clusters:
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
def kmeans_clustering(features_df, n_clusters=6, seed=42):
# Normalize
scaler = StandardScaler()
features_scaled = scaler.fit_transform(features_df.fillna(0))
# Optimal k through Elbow method
inertias = []
k_range = range(2, 15)
for k in k_range:
km = KMeans(n_clusters=k, random_state=seed, n_init=10)
km.fit(features_scaled)
inertias.append(km.inertia_)
# Select k at the "elbow"
best_k = find_elbow(inertias, k_range)
km = KMeans(n_clusters=best_k, random_state=seed, n_init=10)
labels = km.fit_predict(features_scaled)
return labels, km, scaler
DBSCAN — finds arbitrary-shaped clusters and outliers:
from sklearn.cluster import DBSCAN
def dbscan_clustering(features_scaled, eps=0.5, min_samples=3):
db = DBSCAN(eps=eps, min_samples=min_samples, metric='euclidean')
labels = db.fit_predict(features_scaled)
n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
n_noise = (labels == -1).sum()
return labels, n_clusters, n_noise
Hierarchical Clustering with dendrogram:
from scipy.cluster.hierarchy import linkage, dendrogram, fcluster
def hierarchical_clustering(features_scaled, symbols, method='ward', n_clusters=6):
Z = linkage(features_scaled, method=method)
# Dendrogram visualization
fig, ax = plt.subplots(figsize=(16, 8))
dendrogram(Z, labels=symbols, orientation='top', ax=ax)
plt.tight_layout()
labels = fcluster(Z, t=n_clusters, criterion='maxclust')
return labels, Z
Dimension Reduction for Visualization
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import umap
def reduce_dimensions(features_scaled, method='umap', n_components=2):
if method == 'pca':
reducer = PCA(n_components=n_components, random_state=42)
elif method == 'tsne':
reducer = TSNE(n_components=n_components, random_state=42)
elif method == 'umap':
reducer = umap.UMAP(n_components=n_components, random_state=42)
embedding = reducer.fit_transform(features_scaled)
return embedding
Cluster Interpretation
After clustering, analyze characteristics of each cluster:
def describe_clusters(features_df, labels):
features_df['cluster'] = labels
cluster_stats = features_df.groupby('cluster').agg({
'annualized_return': 'mean',
'annualized_vol': 'mean',
'sharpe': 'mean',
'btc_corr': 'mean',
'max_drawdown': 'mean',
'skewness': 'mean'
}).round(3)
# Name clusters by characteristics
cluster_names = {}
for cluster_id, row in cluster_stats.iterrows():
if row['btc_corr'] > 0.85 and row['annualized_vol'] > 1.5:
name = 'High-beta altcoins'
elif row['btc_corr'] > 0.8 and row['annualized_vol'] < 1.0:
name = 'Blue-chip crypto'
elif row['btc_corr'] < 0.5:
name = 'Decorrelated assets'
elif row['sharpe'] > 2.0:
name = 'Strong performers'
else:
name = f'Cluster {cluster_id}'
cluster_names[cluster_id] = name
return cluster_stats, cluster_names
Practical Applications
Portfolio diversification: select 1–2 assets from each cluster for maximum diversification.
Rotation strategies: buy best asset from top-cluster by momentum, rotate monthly.
Peer group analysis: when one cluster asset surges, find laggards in same cluster — potential next movers.
Developing a clustering system with K-Means/DBSCAN/Hierarchical methods, UMAP visualization, automatic cluster interpretation and monthly rebalancing.







