File size: 6,898 Bytes
2362763
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import pandas as pd
import numpy as np
import time

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)
    
    # Smoothed TR, +DM, -DM
    # Wilder's Smoothing: Current = Previous + (Current - Previous) / n
    # EWM with alpha = 1/n
    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
    
    # Calculate +DI and -DI
    df['+di'] = 100 * (df['+dm_smooth'] / df['tr_smooth'])
    df['-di'] = 100 * (df['-dm_smooth'] / df['tr_smooth'])
    
    # Calculate DX
    df['dx'] = 100 * (df['+di'] - df['-di']).abs() / (df['+di'] + df['-di']).replace(0, 1)
    
    # Smoothed DX = ADX
    df['adx'] = df['dx'].ewm(alpha=alpha, adjust=False).mean()
    
    return df

def process_data(file_M1, file_M5, file_M15):
    print("Loading data...")
    m1 = pd.read_parquet(file_M1)
    m5 = pd.read_parquet(file_M5)
    m15 = pd.read_parquet(file_M15)
    
    m1['time_dt'] = pd.to_datetime(m1['time'], unit='s')
    m5['time_dt'] = pd.to_datetime(m5['time'], unit='s')
    m15['time_dt'] = pd.to_datetime(m15['time'], unit='s')
    
    print("Calculating ADX...")
    m1 = calculate_adx(m1, 14)
    m5 = calculate_adx(m5, 14)
    m15 = calculate_adx(m15, 14)
    
    # Merge data to M1 freq
    m1.set_index('time_dt', inplace=True)
    m5.set_index('time_dt', inplace=True)
    m15.set_index('time_dt', inplace=True)
    
    df = m1[['close', 'adx', '+di', '-di']].rename(columns={'adx': 'adx_M1', '+di': 'di_plus_M1', '-di': 'di_minus_M1'})
    
    m5_cols = m5[['adx', '+di', '-di']].rename(columns={'adx': 'adx_M5', '+di': 'di_plus_M5', '-di': 'di_minus_M5'})
    df = df.join(m5_cols)
    df[['adx_M5', 'di_plus_M5', 'di_minus_M5']] = df[['adx_M5', 'di_plus_M5', 'di_minus_M5']].ffill()
    
    m15_cols = m15[['adx', '+di', '-di']].rename(columns={'adx': 'adx_M15', '+di': 'di_plus_M15', '-di': 'di_minus_M15'})
    df = df.join(m15_cols)
    df[['adx_M15', 'di_plus_M15', 'di_minus_M15']] = df[['adx_M15', 'di_plus_M15', 'di_minus_M15']].ffill()
    
    df.dropna(inplace=True)
    
    # T thresholds
    t1 = 20
    t5 = 16
    t15 = 16
    
    # Determine Phases
    a1 = (df['adx_M1'] >= t1).astype(int)
    a5 = (df['adx_M5'] >= t5).astype(int)
    a15 = (df['adx_M15'] >= t15).astype(int)
    
    # phase mapping
    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
    
    # Calculate Phase Transitions
    df['phase_prev'] = df['phase'].shift(1)
    df['is_transition'] = df['phase'] != df['phase_prev']
    
    # Calculate Phase Age
    age = []
    current_age = 0
    curr_p = df['phase'].iloc[0]
    for p in df['phase']:
        if p == curr_p:
            current_age += 1
        else:
            current_age = 1
            curr_p = p
        age.append(current_age)
    df['phase_age_minutes'] = age
    
    # Calculate DMI Dominance (M15)
    di_sum = df['di_plus_M15'] + df['di_minus_M15']
    di_max = df[['di_plus_M15', 'di_minus_M15']].max(axis=1)
    df['dmi_dominance'] = (di_max / di_sum) * 100
    
    # Identify Future State (Next 30 minutes max displacement)
    # Are we successfully transitioning into a trend or reversing?
    # If we are at Phase 8, does it stay in P8/P7 or drop to P1?
    print("Evaluating Transitions...")
    
    transitions = []
    
    for i in range(1, len(df)-30):
        if df['is_transition'].iloc[i]:
            pf = df['phase'].iloc[i]
            prev_pf = df['phase_prev'].iloc[i]
            dmi_dom = df['dmi_dominance'].iloc[i]
            
            # look ahead 30 mins, what is the dominant phase?
            future_phases = df['phase'].iloc[i+1:i+31]
            avg_future = future_phases.mean()
            max_future = future_phases.max()
            min_future = future_phases.min()
            
            transitions.append({
                'time': df.index[i],
                'phase_prev': prev_pf,
                'phase_new': pf,
                'dmi_dominance': dmi_dom,
                'future_avg_phase': avg_future,
                'future_max_phase': max_future
            })
            
    t_df = pd.DataFrame(transitions)
    
    # Let's analyze Phase 8 formations
    print("\n=== L0 (Phase 8) Simulation Results ===")
    p8_entries = t_df[t_df['phase_new'] == 8]
    print(f"Total entries into Phase 8: {len(p8_entries)}")
    
    # 1. P8 from P7 (Strong Micro)
    p7_to_p8 = p8_entries[p8_entries['phase_prev'] == 7]
    print(f"P7 -> P8 Transitions: {len(p7_to_p8)}")
    
    if len(p7_to_p8) > 0:
        # Success = reaches P8 and holds avg >= 7
        success_7_8 = p7_to_p8[p7_to_p8['future_avg_phase'] >= 6.5]
        print(f"  -> Win Rate (Holding Trend): {len(success_7_8)/len(p7_to_p8)*100:.2f}%")
        
        # High DMI vs Low DMI
        high_dmi = p7_to_p8[p7_to_p8['dmi_dominance'] > 65]
        if len(high_dmi) > 0:
            success_high = high_dmi[high_dmi['future_avg_phase'] >= 6.5]
            print(f"  -> Win Rate w/ DMI > 65%: {len(success_high)/len(high_dmi)*100:.2f}% (Total: {len(high_dmi)})")
            
        low_dmi = p7_to_p8[p7_to_p8['dmi_dominance'] <= 55]
        if len(low_dmi) > 0:
            success_low = low_dmi[low_dmi['future_avg_phase'] >= 6.5]
            print(f"  -> Win Rate w/ DMI <= 55%: {len(success_low)/len(low_dmi)*100:.2f}% (Total: {len(low_dmi)})")
            
    # Matrix of probabilities
    print("\n=== Phase Transition Probability Matrix (D0 Validations) ===")
    matrix = t_df.groupby(['phase_prev', 'phase_new']).size().unstack(fill_value=0)
    matrix = matrix.div(matrix.sum(axis=1), axis=0) * 100
    print(matrix.round(2))

if __name__ == '__main__':
    process_data('native_rates_M1.parquet', 'native_rates_M5.parquet', 'native_rates_M15.parquet')