solanaexpert commited on
Commit
03e6a37
·
verified ·
1 Parent(s): 024bb73

Update MLCryptoForecasterAllAssetsTPSL.py

Browse files
Files changed (1) hide show
  1. MLCryptoForecasterAllAssetsTPSL.py +16 -14
MLCryptoForecasterAllAssetsTPSL.py CHANGED
@@ -9,6 +9,7 @@ from sklearn.metrics import classification_report
9
  import ta
10
 
11
  # Function to log results to both console and file
 
12
  def log_results(message, filename="predictions_results.txt"):
13
  print(message)
14
  with open(filename, "a") as f:
@@ -56,7 +57,6 @@ def optimize_tp_sl(df, signals, side, pgrid, lgrid):
56
 
57
  # Process each symbol
58
  for symbol in symbols:
59
- # Log header for this asset
60
  log_results(f"=== {symbol} ===", result_file)
61
 
62
  # Load or download historical data
@@ -86,8 +86,8 @@ for symbol in symbols:
86
  # Compute technical indicators
87
  df['rsi'] = ta.momentum.RSIIndicator(df['close'], window=14).rsi()
88
  df['macd'] = ta.trend.MACD(df['close']).macd()
89
- for s in [10,20,50,100]: df[f'ema_{s}'] = df['close'].ewm(span=s).mean()
90
- for w in [10,20,50,100]: df[f'sma_{w}'] = df['close'].rolling(window=w).mean()
91
  bb = ta.volatility.BollingerBands(df['close'], window=20, window_dev=2)
92
  df['bbw'] = (bb.bollinger_hband() - bb.bollinger_lband()) / bb.bollinger_mavg()
93
  df['atr'] = ta.volatility.AverageTrueRange(df['high'], df['low'], df['close'], window=14).average_true_range()
@@ -102,13 +102,13 @@ for symbol in symbols:
102
  df.dropna(inplace=True)
103
 
104
  # Label signals based on Ichimoku cloud
105
- df['signal'] = np.select(
106
- [(df['close']>df['span_a'])&(df['close']>df['span_b']),
107
- (df['close']<df['span_a'])&(df['close']<df['span_b'])],
108
- [1,0], default=-1)
109
 
110
  # Train/test split
111
- features = [c for c in df.columns if c not in ['open','high','low','close','volume','signal']]
112
  X, y = df[features], df['signal']
113
  Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, shuffle=False)
114
  model = RandomForestClassifier(n_estimators=200, class_weight='balanced', random_state=42)
@@ -117,18 +117,20 @@ for symbol in symbols:
117
 
118
  # Log classification report
119
  report = classification_report(yte, ypr, zero_division=0)
120
- log_results(f"Classification report for {symbol}:\n{report}", result_file)
121
 
122
  # Predict latest trend and log time & price
 
 
123
  pred_time = df.index[-1]
124
  pred_price = df['close'].iloc[-1]
125
- latest = model.predict(X.iloc[-1:].values)[0]
126
- trend_map = {1:'Uptrend',0:'Downtrend',-1:'Neutral'}
127
- log_results(f"Time: {pred_time}, Price: {pred_price:.2f}, Prediction: {trend_map[latest]}", result_file)
128
 
129
  # Optimize TP/SL and log results
130
- hist_sign = model.predict(X.values)
131
- pgrid = np.arange(0.01,0.1,0.01); lgrid = np.arange(0.01,0.1,0.01)
 
132
  up_tp, up_sl, _ = optimize_tp_sl(df, hist_sign, 1, pgrid, lgrid)
133
  dn_tp, dn_sl, _ = optimize_tp_sl(df, hist_sign, 0, pgrid, lgrid)
134
  log_results(f"Optimal UP TP/SL: +{up_tp*100:.1f}% / -{up_sl*100:.1f}%", result_file)
 
9
  import ta
10
 
11
  # Function to log results to both console and file
12
+ # Does not insert blank lines; blank lines added explicitly after each asset block
13
  def log_results(message, filename="predictions_results.txt"):
14
  print(message)
15
  with open(filename, "a") as f:
 
57
 
58
  # Process each symbol
59
  for symbol in symbols:
 
60
  log_results(f"=== {symbol} ===", result_file)
61
 
62
  # Load or download historical data
 
86
  # Compute technical indicators
87
  df['rsi'] = ta.momentum.RSIIndicator(df['close'], window=14).rsi()
88
  df['macd'] = ta.trend.MACD(df['close']).macd()
89
+ for s in [10, 20, 50, 100]: df[f'ema_{s}'] = df['close'].ewm(span=s).mean()
90
+ for w in [10, 20, 50, 100]: df[f'sma_{w}'] = df['close'].rolling(window=w).mean()
91
  bb = ta.volatility.BollingerBands(df['close'], window=20, window_dev=2)
92
  df['bbw'] = (bb.bollinger_hband() - bb.bollinger_lband()) / bb.bollinger_mavg()
93
  df['atr'] = ta.volatility.AverageTrueRange(df['high'], df['low'], df['close'], window=14).average_true_range()
 
102
  df.dropna(inplace=True)
103
 
104
  # Label signals based on Ichimoku cloud
105
+ df['signal'] = np.select([
106
+ (df['close'] > df['span_a']) & (df['close'] > df['span_b']),
107
+ (df['close'] < df['span_a']) & (df['close'] < df['span_b'])
108
+ ], [1, 0], default=-1)
109
 
110
  # Train/test split
111
+ features = [c for c in df.columns if c not in ['open', 'high', 'low', 'close', 'volume', 'signal']]
112
  X, y = df[features], df['signal']
113
  Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, shuffle=False)
114
  model = RandomForestClassifier(n_estimators=200, class_weight='balanced', random_state=42)
 
117
 
118
  # Log classification report
119
  report = classification_report(yte, ypr, zero_division=0)
120
+ log_results(f"Classification report for {symbol}: {report}", result_file)
121
 
122
  # Predict latest trend and log time & price
123
+ latest_df = X.iloc[-1:] # DataFrame for prediction
124
+ trend_label = model.predict(latest_df)[0]
125
  pred_time = df.index[-1]
126
  pred_price = df['close'].iloc[-1]
127
+ trend_str = {1:'Uptrend', 0:'Downtrend', -1:'Neutral'}[trend_label]
128
+ log_results(f"Time: {pred_time}, Price: {pred_price:.2f}, Prediction: {trend_str}", result_file)
 
129
 
130
  # Optimize TP/SL and log results
131
+ hist_sign = model.predict(X) # Pass DataFrame to avoid warning
132
+ pgrid = np.arange(0.01, 0.1, 0.01)
133
+ lgrid = np.arange(0.01, 0.1, 0.01)
134
  up_tp, up_sl, _ = optimize_tp_sl(df, hist_sign, 1, pgrid, lgrid)
135
  dn_tp, dn_sl, _ = optimize_tp_sl(df, hist_sign, 0, pgrid, lgrid)
136
  log_results(f"Optimal UP TP/SL: +{up_tp*100:.1f}% / -{up_sl*100:.1f}%", result_file)