-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy patha
251 lines (251 loc) · 8.9 KB
/
a
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Advanced Forex Trading System\n",
"Documentation and implementation of a multi-timeframe forex trading system.\n",
"System Overview\n",
"\n",
"Multi-timeframe analysis (H1, H4, D)\n",
"Pairs: EUR/USD, GBP/USD, AUD/USD, USD/JPY\n",
"Cross-validated model training\n",
"Hyperparameter optimization\n",
"Performance tracking"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"from oandapyV20 import API\n",
"import oandapyV20.endpoints.instruments as instruments\n",
"from sklearn.ensemble import RandomForestClassifier\n",
"from sklearn.model_selection import TimeSeriesSplit\n",
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
"import optuna\n",
"from ta.trend import EMAIndicator, MACD\n",
"from ta.volatility import BollingerBands\n",
"from ta.momentum import RSIIndicator\n",
"import datetime\n",
"import joblib\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class AdvancedForexModel:\n",
" def __init__(self, api_key):\n",
" self.pairs = ['EUR_USD', 'GBP_USD', 'AUD_USD', 'USD_JPY']\n",
" self.timeframes = ['H1', 'H4', 'D']\n",
" self.api = API(access_token=api_key)\n",
" self.models = {}\n",
" self.best_params = {}\n",
" self.performance_metrics = {}\n",
" \n",
" def fetch_multi_timeframe_data(self, pair):\n",
" data = {}\n",
" for tf in self.timeframes:\n",
" params = {\"count\": 5000, \"granularity\": tf}\n",
" r = instruments.InstrumentsCandles(instrument=pair, params=params)\n",
" self.api.request(r)\n",
" \n",
" df = pd.DataFrame([\n",
" {\n",
" 'time': candle['time'],\n",
" 'open': float(candle['mid']['o']),\n",
" 'high': float(candle['mid']['h']),\n",
" 'low': float(candle['mid']['l']),\n",
" 'close': float(candle['mid']['c']),\n",
" 'volume': float(candle['volume'])\n",
" } for candle in r.response['candles']\n",
" ])\n",
" data[tf] = df\n",
" return data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def optimize_hyperparameters(self, X, y):\n",
" def objective(trial):\n",
" params = {\n",
" 'n_estimators': trial.suggest_int('n_estimators', 100, 1000),\n",
" 'max_depth': trial.suggest_int('max_depth', 10, 100),\n",
" 'min_samples_split': trial.suggest_int('min_samples_split', 2, 20),\n",
" 'min_samples_leaf': trial.suggest_int('min_samples_leaf', 1, 10)\n",
" }\n",
" \n",
" tscv = TimeSeriesSplit(n_splits=5)\n",
" scores = []\n",
" \n",
" for train_idx, val_idx in tscv.split(X):\n",
" X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n",
" y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n",
" \n",
" model = RandomForestClassifier(**params, random_state=42)\n",
" model.fit(X_train, y_train)\n",
" score = model.score(X_val, y_val)\n",
" scores.append(score)\n",
" \n",
" return np.mean(scores)\n",
" \n",
" study = optuna.create_study(direction='maximize')\n",
" study.optimize(objective, n_trials=50)\n",
" return study.best_params"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def train_models(self):\n",
" for pair in self.pairs:\n",
" print(f\"Training models for {pair}\")\n",
" data = self.fetch_multi_timeframe_data(pair)\n",
" \n",
" for timeframe in self.timeframes:\n",
" df = self.add_technical_indicators(data[timeframe])\n",
" X, y = self.prepare_training_data(df)\n",
" \n",
" # Remove NaN values\n",
" X = X.dropna()\n",
" y = y[X.index]\n",
" \n",
" # Optimize hyperparameters\n",
" best_params = self.optimize_hyperparameters(X, y)\n",
" self.best_params[f\"{pair}_{timeframe}\"] = best_params\n",
" \n",
" # Train model\n",
" model = RandomForestClassifier(**best_params, random_state=42)\n",
" model.fit(X, y)\n",
" \n",
" # Evaluate\n",
" metrics = self.evaluate_model(model, X, y)\n",
" self.performance_metrics[f\"{pair}_{timeframe}\"] = metrics\n",
" \n",
" # Save\n",
" self.models[f\"{pair}_{timeframe}\"] = model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def generate_signals(self):\n",
" signals = []\n",
" for pair in self.pairs:\n",
" data = self.fetch_multi_timeframe_data(pair)\n",
" pair_signals = {}\n",
" \n",
" for timeframe in self.timeframes:\n",
" df = self.add_technical_indicators(data[timeframe])\n",
" X = df[self.feature_columns].iloc[-1:]\n",
" \n",
" model = self.models[f\"{pair}_{timeframe}\"]\n",
" prediction = model.predict(X)\n",
" probability = model.predict_proba(X)\n",
" \n",
" pair_signals[timeframe] = {\n",
" 'prediction': prediction[0],\n",
" 'confidence': np.max(probability[0])\n",
" }\n",
" \n",
" consensus = self.calculate_consensus(pair_signals)\n",
" if consensus['signal'] != 0:\n",
" entry, tp, sl = self.calculate_levels(data['H1'], consensus['signal'])\n",
" signals.append({\n",
" 'pair': pair,\n",
" 'signal': 'BUY' if consensus['signal'] == 1 else 'SELL',\n",
" 'confidence': consensus['confidence'],\n",
" 'entry': entry,\n",
" 'take_profit': tp,\n",
" 'stop_loss': sl,\n",
" 'timestamp': datetime.datetime.now().isoformat()\n",
" })\n",
" \n",
" return signals"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Fetch and display multi-timeframe data for EUR/USD\n",
"api_key = 'b9887c2d3ef2c6a6c5ab64bdbbb92737-934714c530e944cbf486e77819774434'\n",
"trader = AdvancedForexModel(api_key)\n",
"data = trader.fetch_multi_timeframedef train_models(self):\n",
" for pair in self.pairs:\n",
" print(f\"Training models for {pair}\")\n",
" data = self.fetch_multi_timeframe_data(pair)\n",
" \n",
" for timeframe in self.timeframes:\n",
" df = self.add_technical_indicators(data[timeframe])\n",
" X, y = self.prepare_training_data(df)\n",
" \n",
" # Remove NaN values\n",
" X = X.dropna()\n",
" y = y[X.index]\n",
" \n",
" # Optimize hyperparameters\n",
" best_params = self.optimize_hyperparameters(X, y)\n",
" self.best_params[f\"{pair}_{timeframe}\"] = best_params\n",
" \n",
" # Train model\n",
" model = RandomForestClassifier(**best_params, random_state=42)\n",
" model.fit(X, y)\n",
" \n",
" # Evaluate\n",
" metrics = self.evaluate_model(model, X, y)\n",
" self.performance_metrics[f\"{pair}_{timeframe}\"] = metrics\n",
" \n",
" # Save\n",
" self.models[f\"{pair}_{timeframe}\"] = model_data('EUR_USD')\n",
"\n",
"# Display the data for each timeframe\n",
"for timeframe, df in data.items():\n",
" print(f\"Timeframe: {timeframe}\")\n",
" print(df.head())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 2
}