tickdata / stats_matrix.py
gionuibk's picture
Upload stats_matrix.py with huggingface_hub
13825c8 verified
Raw
History Blame Contribute Delete
4.1 kB
import pandas as pd
import numpy as np
def calculate_adx(df, period=14):
df = df.copy()
# Calculate True Range
df['h_l'] = df['high'] - df['low']
df['h_pc'] = (df['high'] - df['close'].shift(1)).abs()
df['l_pc'] = (df['low'] - df['close'].shift(1)).abs()
df['tr'] = df[['h_l', 'h_pc', 'l_pc']].max(axis=1)
# Calculate Directional Movement
df['+dm'] = np.where((df['high'] - df['high'].shift(1)) > (df['low'].shift(1) - df['low']),
np.maximum(df['high'] - df['high'].shift(1), 0), 0)
df['-dm'] = np.where((df['low'].shift(1) - df['low']) > (df['high'] - df['high'].shift(1)),
np.maximum(df['low'].shift(1) - df['low'], 0), 0)
alpha = 1 / period
df['tr_smooth'] = df['tr'].ewm(alpha=alpha, adjust=False).mean() * period
df['+dm_smooth'] = df['+dm'].ewm(alpha=alpha, adjust=False).mean() * period
df['-dm_smooth'] = df['-dm'].ewm(alpha=alpha, adjust=False).mean() * period
df['+di'] = 100 * (df['+dm_smooth'] / df['tr_smooth'])
df['-di'] = 100 * (df['-dm_smooth'] / df['tr_smooth'])
df['dx'] = 100 * (df['+di'] - df['-di']).abs() / (df['+di'] + df['-di']).replace(0, 1)
df['adx'] = df['dx'].ewm(alpha=alpha, adjust=False).mean()
return df
def run_stats():
# Use February tick data because it's a full month and manageable
print("Loading tick data (Feb 2026)...")
ticks = pd.read_parquet('ticks_XAUUSD.sc_2026_02.parquet')
print("Resampling to OHLC...")
ticks['time_dt'] = pd.to_datetime(ticks['time_msc'], unit='ms')
ticks.set_index('time_dt', inplace=True)
# M1 Resample
m1 = ticks['bid'].resample('1min').ohlc()
m1.dropna(inplace=True)
m1 = calculate_adx(m1, 14)
# M5 Resample
m5 = ticks['bid'].resample('5min').ohlc()
m5.dropna(inplace=True)
m5 = calculate_adx(m5, 14)
# M15 Resample
m15 = ticks['bid'].resample('15min').ohlc()
m15.dropna(inplace=True)
m15 = calculate_adx(m15, 14)
# Reindex to M1
print("Combining Dataframes...")
df = m1[['close', 'adx']].rename(columns={'adx': 'adx_M1'})
df = df.join(m5[['adx']].rename(columns={'adx': 'adx_M5'})).ffill()
df = df.join(m15[['adx']].rename(columns={'adx': 'adx_M15'})).ffill()
df.dropna(inplace=True)
t1, t5, t15 = 20, 16, 16
a1 = (df['adx_M1'] >= t1).astype(int)
a5 = (df['adx_M5'] >= t5).astype(int)
a15 = (df['adx_M15'] >= t15).astype(int)
df['phase'] = 0
df.loc[(a1==0) & (a5==0) & (a15==0), 'phase'] = 1
df.loc[(a1==0) & (a5==0) & (a15==1), 'phase'] = 2
df.loc[(a1==0) & (a5==1) & (a15==0), 'phase'] = 3
df.loc[(a1==0) & (a5==1) & (a15==1), 'phase'] = 4
df.loc[(a1==1) & (a5==0) & (a15==0), 'phase'] = 5
df.loc[(a1==1) & (a5==0) & (a15==1), 'phase'] = 6
df.loc[(a1==1) & (a5==1) & (a15==0), 'phase'] = 7
df.loc[(a1==1) & (a5==1) & (a15==1), 'phase'] = 8
# Phase Transitions
df['phase_prev'] = df['phase'].shift(1)
df['is_transition'] = df['phase'] != df['phase_prev']
total_days = (df.index[-1] - df.index[0]).total_seconds() / 86400
total_transitions = df['is_transition'].sum() - 1 # Remove first row True
print("\n--- TRANSITION FREQUENCY ---")
print(f"Dataset span: {total_days:.2f} Days")
print(f"Average transitions per DAY: {total_transitions / total_days:.1f}")
print(f"Average transitions per WEEK: {total_transitions / total_days * 5:.1f} (5 trading days)")
print(f"Average transitions per MONTH: {total_transitions / total_days * 20:.1f} (20 trading days)")
print("\n--- PHASE DISTRIBUTION (%) ---")
phase_counts = df['phase'].value_counts(normalize=True) * 100
print(phase_counts.sort_index().round(2))
print("\n--- TRANSITION MATRIX (%) ---")
trans_df = df[df['is_transition']][1:]
matrix = trans_df.groupby(['phase_prev', 'phase']).size().unstack(fill_value=0)
matrix = matrix.div(matrix.sum(axis=1), axis=0) * 100
print(matrix.round(2))
if __name__ == '__main__':
run_stats()