gionuibk commited on
Commit
412242a
·
verified ·
1 Parent(s): e7e8afa

Upload simulate_v15_HuongA.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. simulate_v15_HuongA.py +181 -0
simulate_v15_HuongA.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+
4
+ def calculate_adx(df, period=14):
5
+ df['h_l'] = df['high'] - df['low']
6
+ df['h_pc'] = (df['high'] - df['close'].shift(1)).abs()
7
+ df['l_pc'] = (df['low'] - df['close'].shift(1)).abs()
8
+ df['tr'] = df[['h_l', 'h_pc', 'l_pc']].max(axis=1)
9
+
10
+ df['+dm'] = np.where((df['high'] - df['high'].shift(1)) > (df['low'].shift(1) - df['low']),
11
+ np.maximum(df['high'] - df['high'].shift(1), 0), 0)
12
+ df['-dm'] = np.where((df['low'].shift(1) - df['low']) > (df['high'] - df['high'].shift(1)),
13
+ np.maximum(df['low'].shift(1) - df['low'], 0), 0)
14
+
15
+ alpha = 1 / period
16
+ df['tr_smooth'] = df['tr'].ewm(alpha=alpha, adjust=False).mean() * period
17
+ df['+dm_smooth'] = df['+dm'].ewm(alpha=alpha, adjust=False).mean() * period
18
+ df['-dm_smooth'] = df['-dm'].ewm(alpha=alpha, adjust=False).mean() * period
19
+
20
+ df['+di'] = 100 * (df['+dm_smooth'] / df['tr_smooth'])
21
+ df['-di'] = 100 * (df['-dm_smooth'] / df['tr_smooth'])
22
+
23
+ df['dx'] = 100 * (df['+di'] - df['-di']).abs() / (df['+di'] + df['-di']).replace(0, 1)
24
+ df['adx'] = df['dx'].ewm(alpha=alpha, adjust=False).mean()
25
+ return df
26
+
27
+ def run_simulation():
28
+ print("--- V15.00 Huong A Causal Simulator ---")
29
+ print("Loading OHLC Parquet data...")
30
+ m1 = pd.read_parquet('native_rates_M1.parquet')
31
+ m5 = pd.read_parquet('native_rates_M5.parquet')
32
+ m15 = pd.read_parquet('native_rates_M15.parquet')
33
+
34
+ print("Calculating Causal ADX...")
35
+ m1 = calculate_adx(m1, 14)
36
+ m5 = calculate_adx(m5, 14)
37
+ m15 = calculate_adx(m15, 14)
38
+
39
+ m1['time_dt'] = pd.to_datetime(m1['time'], unit='s')
40
+ m5['time_dt'] = pd.to_datetime(m5['time'], unit='s')
41
+ m15['time_dt'] = pd.to_datetime(m15['time'], unit='s')
42
+
43
+ m1.set_index('time_dt', inplace=True)
44
+ m5.set_index('time_dt', inplace=True)
45
+ m15.set_index('time_dt', inplace=True)
46
+
47
+ df = m1[['open', 'high', 'low', 'close', 'adx', '+di', '-di']].copy()
48
+ df.rename(columns={'adx': 'adx_M1', '+di': 'di_plus_M1', '-di': 'di_minus_M1'}, inplace=True)
49
+
50
+ m5_cols = m5[['adx', '+di', '-di']].rename(columns={'adx': 'adx_M5', '+di': 'di_plus_M5', '-di': 'di_minus_M5'})
51
+ m5_cols.index = m5_cols.index + pd.Timedelta(minutes=5)
52
+ df = df.join(m5_cols)
53
+ df[['adx_M5', 'di_plus_M5', 'di_minus_M5']] = df[['adx_M5', 'di_plus_M5', 'di_minus_M5']].ffill()
54
+
55
+ m15_cols = m15[['adx', '+di', '-di']].rename(columns={'adx': 'adx_M15', '+di': 'di_plus_M15', '-di': 'di_minus_M15'})
56
+ m15_cols.index = m15_cols.index + pd.Timedelta(minutes=15)
57
+ df = df.join(m15_cols)
58
+ df[['adx_M15', 'di_plus_M15', 'di_minus_M15']] = df[['adx_M15', 'di_plus_M15', 'di_minus_M15']].ffill()
59
+
60
+ df.dropna(inplace=True)
61
+ df['adx_M1'] = df['adx_M1'].shift(1)
62
+
63
+ t_M1, t_M5, t_M15 = 18.0, 18.0, 18.0
64
+
65
+ a1 = (df['adx_M1'] >= t_M1).astype(int)
66
+ a5 = (df['adx_M5'] >= t_M5).astype(int)
67
+ a15 = (df['adx_M15'] >= t_M15).astype(int)
68
+
69
+ df['phase'] = 1
70
+ df.loc[(a15==0) & (a5==0) & (a1==0), 'phase'] = 1
71
+ df.loc[(a15==0) & (a5==0) & (a1==1), 'phase'] = 2
72
+ df.loc[(a15==0) & (a5==1) & (a1==0), 'phase'] = 3
73
+ df.loc[(a15==1) & (a5==0) & (a1==0), 'phase'] = 4
74
+ df.loc[(a15==0) & (a5==1) & (a1==1), 'phase'] = 5
75
+ df.loc[(a15==1) & (a5==0) & (a1==1), 'phase'] = 6
76
+ df.loc[(a15==1) & (a5==1) & (a1==0), 'phase'] = 7
77
+ df.loc[(a15==1) & (a5==1) & (a1==1), 'phase'] = 8
78
+
79
+ sum_di = df['di_plus_M15'] + df['di_minus_M15']
80
+ df['dmi_dir'] = np.where(df['di_plus_M15'] > df['di_minus_M15'], 1, -1)
81
+ df['dmi_score'] = (df[['di_plus_M15', 'di_minus_M15']].max(axis=1) / sum_di) * 100
82
+
83
+ # TRIGGER CALCULATION: Price Action Engulfing
84
+ df['body'] = df['close'] - df['open']
85
+ df['prev_body'] = df['body'].shift(1)
86
+ df['bull_engulf'] = (df['prev_body'] < 0) & (df['body'] > 0) & (df['close'] > df['open'].shift(1)) & (df['open'] < df['close'].shift(1))
87
+ df['bear_engulf'] = (df['prev_body'] > 0) & (df['body'] < 0) & (df['close'] < df['open'].shift(1)) & (df['open'] > df['close'].shift(1))
88
+
89
+ print("Executing Huong A Matrix (Filter + Engulfing Trigger) Causal...\n")
90
+
91
+ stats = {
92
+ 'Trend_Engulf_Buy': {'trades': 0, 'wins': 0, 'total_pips': 0.0},
93
+ 'Trend_Engulf_Sell': {'trades': 0, 'wins': 0, 'total_pips': 0.0},
94
+ 'Range_Engulf_Buy': {'trades': 0, 'wins': 0, 'total_pips': 0.0},
95
+ 'Range_Engulf_Sell': {'trades': 0, 'wins': 0, 'total_pips': 0.0}
96
+ }
97
+
98
+ for i in range(2, len(df)-60):
99
+ phase = df['phase'].iloc[i]
100
+ bullish = df['bull_engulf'].iloc[i]
101
+ bearish = df['bear_engulf'].iloc[i]
102
+ dir_mult = df['dmi_dir'].iloc[i]
103
+
104
+ gun = None
105
+ trade_dir = 0
106
+ tp, sl = 0, 0
107
+
108
+ # 1. Trend Follow Filter: Phase 7 or 8 AND DMI alignment
109
+ if phase >= 7 and df['dmi_score'].iloc[i] > 60:
110
+ if bullish and dir_mult == 1:
111
+ gun = 'Trend_Engulf_Buy'
112
+ trade_dir = 1
113
+ tp, sl = 30.0, 20.0
114
+ elif bearish and dir_mult == -1:
115
+ gun = 'Trend_Engulf_Sell'
116
+ trade_dir = -1
117
+ tp, sl = 30.0, 20.0
118
+
119
+ # 2. Range Scalp Filter: Phase 1 or 2
120
+ elif phase <= 2:
121
+ if bullish:
122
+ gun = 'Range_Engulf_Buy'
123
+ trade_dir = 1
124
+ tp, sl = 15.0, 15.0
125
+ elif bearish:
126
+ gun = 'Range_Engulf_Sell'
127
+ trade_dir = -1
128
+ tp, sl = 15.0, 15.0
129
+
130
+ if gun is None: continue
131
+
132
+ entry_price = df['close'].iloc[i]
133
+ future_highs = df['high'].iloc[i+1:i+61]
134
+ future_lows = df['low'].iloc[i+1:i+61]
135
+
136
+ pnl = 0
137
+ win = 0
138
+
139
+ # CAUSAL AMBIGUOUS BAR HANDLING (Pessimistic)
140
+ if trade_dir == 1:
141
+ for h, l in zip(future_highs, future_lows):
142
+ if l <= entry_price - (sl * 0.01):
143
+ pnl = -sl
144
+ win = 0
145
+ break
146
+ elif h >= entry_price + (tp * 0.01):
147
+ pnl = tp
148
+ win = 1
149
+ break
150
+ else:
151
+ for h, l in zip(future_highs, future_lows):
152
+ if h >= entry_price + (sl * 0.01):
153
+ pnl = -sl
154
+ win = 0
155
+ break
156
+ elif l <= entry_price - (tp * 0.01):
157
+ pnl = tp
158
+ win = 1
159
+ break
160
+
161
+ if pnl == 0:
162
+ pnl = ((df['close'].iloc[i+60] - entry_price) / 0.01) * trade_dir
163
+ if pnl > 0: win = 1
164
+
165
+ stats[gun]['trades'] += 1
166
+ stats[gun]['wins'] += win
167
+ stats[gun]['total_pips'] += pnl
168
+
169
+ print(f"|=================================================|")
170
+ for name, s in stats.items():
171
+ tr = s['trades']
172
+ if tr == 0:
173
+ print(f" * {name:<17} | Trades: 0")
174
+ continue
175
+ wr = (s['wins']/tr)*100
176
+ np_val = s['total_pips']
177
+ print(f" * {name:<17} | Trades: {tr:<4} | WinRate: {wr:>5.1f}% | Net Pips: {np_val:+.1f}")
178
+ print(f"|=================================================|")
179
+
180
+ if __name__ == '__main__':
181
+ run_simulation()