History of Code
History of Code
___________________
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
from sklearn.metrics import mean_squared_error, accuracy_score
import matplotlib.pyplot as plt
import ccxt
import time
# Load data
exchange = ccxt.bybit()
# Create 10-day and 50-day moving averages for the 'close' price
df = create_moving_averages(df, 'close', [10, 50])
return df
except ccxt.NetworkError as e:
print('Network error:', e)
print(f"Retrying ({retries+1}/{max_retries})...")
retries += 1
time.sleep(retry_delay)
except ccxt.ExchangeError as e:
print('Exchange error:', e)
return pd.DataFrame() # Return an empty DataFrame in case of
exchange error
except Exception as e:
print('Error:', e)
return pd.DataFrame() # Return an empty DataFrame for any other
error
# Grid search
grid_search = GridSearchCV(estimator=xgb_model, param_grid=param_grid,
cv=tscv, scoring='neg_mean_squared_error', n_jobs=-1)
grid_search.fit(X, y)
# Best parameters
best_params = grid_search.best_params_
print("Best parameters:", best_params)
# Best estimator
best_estimator = grid_search.best_estimator_
# Cross-validation results
cv_results = grid_search.cv_results_
print("Cross-validation results:", cv_results)
# Calculate accuracy
threshold = 0 # Define threshold for classifying positive and negative
predictions
binary_predictions = np.where(predictions > threshold, 1, 0)
accuracy = accuracy_score(y > threshold, binary_predictions)
print("Accuracy:", accuracy)
# Strategy Testing
# Generate signals (example: buy if predicted return > 0, sell otherwise)
signals = np.where(predictions > 0, 1, -1)
# Calculate returns
returns = signals * data['target'].shift(-1) # Shift y by 1 to align returns with
signals
cumulative_returns = returns.cumsum()
2__________________________________________________________________
_______________
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
from sklearn.metrics import mean_squared_error, accuracy_score
import matplotlib.pyplot as plt
import ccxt
import time
import joblib
import json
import os
# Load data
exchange = ccxt.bybit()
# Create 10-day and 50-day moving averages for the 'close' price
df = create_moving_averages(df, 'close', [10, 50])
return df
except ccxt.NetworkError as e:
print('Network error:', e)
print(f"Retrying ({retries+1}/{max_retries})...")
retries += 1
time.sleep(retry_delay)
except ccxt.ExchangeError as e:
print('Exchange error:', e)
return pd.DataFrame() # Return an empty DataFrame in case of
exchange error
except Exception as e:
print('Error:', e)
return pd.DataFrame() # Return an empty DataFrame for any other
error
# Best parameters
best_params = grid_search.best_params_
print("Best parameters:", best_params)
# Best estimator
best_estimator = grid_search.best_estimator_
# Cross-validation results
cv_results = grid_search.cv_results_
print("Cross-validation results:", cv_results)
# Calculate accuracy
threshold = 0 # Define threshold for classifying positive and negative
predictions
binary_predictions = np.where(predictions > threshold, 1, 0)
accuracy = accuracy_score(y > threshold, binary_predictions)
print("Accuracy:", accuracy)
# Strategy Testing
# Generate signals (example: buy if predicted return > 0, sell otherwise)
signals = np.where(predictions > 0, 1, -1)
# Calculate returns
returns = signals * data['target'].shift(-1) # Shift y by 1 to align returns with
signals
cumulative_returns = returns.cumsum()
else:
print("Data fetching failed. Exiting...")
3__________________________________________________________________
________________
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
from sklearn.metrics import mean_squared_error, accuracy_score
import matplotlib.pyplot as plt
import ccxt
import time
import joblib
import json
import os
def get_kraken_pairs():
kraken = ccxt.kraken()
markets = kraken.load_markets()
kraken_pairs = list(markets.keys())
return kraken_pairs
# Create 10-day and 50-day moving averages for the 'close' price
df = create_moving_averages(df, 'close', [10, 50])
return df
except ccxt.NetworkError as e:
print('Network error:', e)
print(f"Retrying ({retries+1}/{max_retries})...")
retries += 1
time.sleep(retry_delay)
except ccxt.ExchangeError as e:
print('Exchange error:', e)
return pd.DataFrame() # Return an empty DataFrame in case of
exchange error
except Exception as e:
print('Error:', e)
return pd.DataFrame() # Return an empty DataFrame for any other
error
# Load data
exchange = ccxt.bybit()
if not symbol_data.empty:
# Split data into features and target
X = symbol_data.drop(['timestamp', 'target'], axis=1)
y = symbol_data['target']
# Grid search
grid_search = GridSearchCV(estimator=xgb_model,
param_grid=param_grid, cv=tscv, scoring='neg_mean_squared_error', n_jobs=-1)
grid_search.fit(X, y)
# Best parameters
best_params = grid_search.best_params_
# Best estimator
best_estimator = grid_search.best_estimator_
# Calculate accuracy
threshold = 0 # Define threshold for classifying positive and negative
predictions
binary_predictions = np.where(predictions > threshold, 1, 0)
accuracy = accuracy_score(y > threshold, binary_predictions)
4__________________________________________________________________
________________
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
from sklearn.metrics import mean_squared_error, accuracy_score
import matplotlib.pyplot as plt
import ccxt
import time
import joblib
import json
import os
def get_kraken_pairs():
kraken = ccxt.kraken()
markets = kraken.load_markets()
kraken_pairs = list(markets.keys())
return kraken_pairs
# Create 10-day and 50-day moving averages for the 'close' price
df = create_moving_averages(df, 'close', [10, 50])
return df
except ccxt.NetworkError as e:
print('Network error:', e)
print(f"Retrying ({retries+1}/{max_retries})...")
retries += 1
time.sleep(retry_delay)
except ccxt.ExchangeError as e:
print('Exchange error:', e)
return pd.DataFrame() # Return an empty DataFrame in case of
exchange error
except Exception as e:
print('Error:', e)
return pd.DataFrame() # Return an empty DataFrame for any other
error
# Load data
exchange = ccxt.bybit()
if not symbol_data.empty:
# Split data into features and target
X = symbol_data.drop(['timestamp', 'target'], axis=1)
y = symbol_data['target']
# Grid search
grid_search = GridSearchCV(estimator=xgb_model,
param_grid=param_grid, cv=tscv, scoring='neg_mean_squared_error', n_jobs=-1)
grid_search.fit(X, y)
# Best parameters
best_params = grid_search.best_params_
# Best estimator
best_estimator = grid_search.best_estimator_
# Calculate accuracy
threshold = 0 # Define threshold for classifying positive and negative
predictions
binary_predictions = np.where(predictions > threshold, 1, 0)
accuracy = accuracy_score(y > threshold, binary_predictions)
5__________________________________________________________________
_____________
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
from sklearn.metrics import mean_squared_error, accuracy_score
import matplotlib.pyplot as plt
import ccxt
import time
import joblib
import json
import os
def get_kraken_pairs():
kraken = ccxt.kraken()
markets = kraken.load_markets()
kraken_pairs = list(markets.keys())
return kraken_pairs
# Create 10-day and 50-day moving averages for the 'close' price
df = create_moving_averages(df, 'close', [10, 50])
# Normalize numerical features ('open', 'high', 'low', 'close', 'volume',
'ma10', 'ma50', 'target')
df = normalize_numerical_features(df, ['open', 'high', 'low', 'close',
'volume', 'ma10', 'ma50', 'target'])
return df
except ccxt.NetworkError as e:
print('Network error:', e)
print(f"Retrying ({retries+1}/{max_retries})...")
retries += 1
time.sleep(retry_delay)
except ccxt.ExchangeError as e:
print('Exchange error:', e)
return pd.DataFrame() # Return an empty DataFrame in case of
exchange error
except Exception as e:
print('Error:', e)
return pd.DataFrame() # Return an empty DataFrame for any other
error
# Grid search
grid_search = GridSearchCV(estimator=xgb_model,
param_grid=param_grid, cv=tscv, scoring='neg_mean_squared_error', n_jobs=-1)
grid_search.fit(X, y)
# Best parameters
best_params = grid_search.best_params_
# Best estimator
best_estimator = grid_search.best_estimator_
# Calculate accuracy
threshold = 0 # Define threshold for classifying positive and negative
predictions
binary_predictions = np.where(predictions > threshold, 1, 0)
accuracy = accuracy_score(y > threshold, binary_predictions)
def delete_trained_data(crypto_pairs):
for symbol in crypto_pairs:
# Delete existing model file
model_filename = f'xgboost_model_{symbol.replace("/", "_")}.pkl'
if os.path.exists(model_filename):
os.remove(model_filename)
print(f"Deleted model file: {model_filename}")
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
from sklearn.metrics import mean_squared_error, accuracy_score
import matplotlib.pyplot as plt
import ccxt
import time
import joblib
import json
import os
def get_kraken_pairs():
kraken = ccxt.kraken()
markets = kraken.load_markets()
kraken_pairs = list(markets.keys())
return kraken_pairs
# Create 10-day and 50-day moving averages for the 'close' price
df = create_moving_averages(df, 'close', [10, 50])
return df
except ccxt.NetworkError as e:
print('Network error:', e)
print(f"Retrying ({retries+1}/{max_retries})...")
retries += 1
time.sleep(retry_delay)
except ccxt.ExchangeError as e:
print('Exchange error:', e)
return pd.DataFrame() # Return an empty DataFrame in case of
exchange error
except Exception as e:
print('Error:', e)
return pd.DataFrame() # Return an empty DataFrame for any other
error
# Load data
exchange = ccxt.kraken()
# Grid search
grid_search = GridSearchCV(estimator=xgb_model, param_grid=param_grid,
cv=tscv, scoring='neg_mean_squared_error', n_jobs=-1)
grid_search.fit(X, y)
# Best parameters
best_params = grid_search.best_params_
# Best estimator
best_estimator = grid_search.best_estimator_
# Calculate accuracy
threshold = 0 # Define threshold for classifying positive and negative
predictions
binary_predictions = np.where(predictions > threshold, 1, 0)
accuracy = accuracy_score(y > threshold, binary_predictions)
7__________________________________________________________________
________-device
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
from sklearn.metrics import mean_squared_error, accuracy_score
import ccxt
import time
import joblib
import logging
import asyncio
import tkinter as tk
from tkinter import messagebox
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from mplfinance.original_flavor import candlestick_ohlc
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# Setup logging
logging.basicConfig(filename='trading.log', level=logging.INFO, format='%(asctime)s
- %(levelname)s - %(message)s')
# Load data
exchange = ccxt.kraken() # Use Kraken exchange
# Create 10-day and 50-day moving averages for the 'close' price
df = create_moving_averages(df, 'close', [10, 50])
return df
except ccxt.NetworkError as e:
logging.error(f'Network error: {e}')
logging.info(f"Retrying ({retries+1}/{max_retries})...")
retries += 1
await asyncio.sleep(retry_delay)
except ccxt.ExchangeError as e:
logging.error(f'Exchange error: {e}')
return pd.DataFrame() # Return an empty DataFrame in case of
exchange error
except Exception as e:
logging.error(f'Error: {e}')
return pd.DataFrame() # Return an empty DataFrame for any other
error
if data.empty:
logging.error("Data fetching failed. Exiting...")
return None
# Grid search
grid_search = GridSearchCV(estimator=xgb_model, param_grid=param_grid,
cv=tscv, scoring='neg_mean_squared_error', n_jobs=-1)
grid_search.fit(X, y)
# Best estimator
best_estimator = grid_search.best_estimator_
return best_estimator
def start_trading(self):
symbol = self.symbol_entry.get()
if symbol:
logging.info(f"Starting real-time trading for {symbol}...")
self.start_button.config(state="disabled")
self.symbol_entry.config(state="disabled")
asyncio.run(start_real_time_trading(symbol))
self.plot_chart(symbol)
else:
messagebox.showwarning("Warning", "Please enter a symbol.")
7__________________________________________________________________
_-colab
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
from sklearn.metrics import mean_squared_error, accuracy_score
import ccxt
import time
import joblib
import logging
import asyncio
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from mplfinance.original_flavor import candlestick_ohlc
# Setup logging
logging.basicConfig(filename='trading.log', level=logging.INFO, format='%(asctime)s
- %(levelname)s - %(message)s')
# Load data
exchange = ccxt.kraken() # Use Kraken exchange
# Create 10-day and 50-day moving averages for the 'close' price
df = create_moving_averages(df, 'close', [10, 50])
return df
except ccxt.NetworkError as e:
logging.error(f'Network error: {e}')
logging.info(f"Retrying ({retries+1}/{max_retries})...")
retries += 1
await asyncio.sleep(retry_delay)
except ccxt.ExchangeError as e:
logging.error(f'Exchange error: {e}')
return pd.DataFrame() # Return an empty DataFrame in case of
exchange error
except Exception as e:
logging.error(f'Error: {e}')
return pd.DataFrame() # Return an empty DataFrame for any other
error
if data.empty:
logging.error("Data fetching failed. Exiting...")
return None
# Grid search
grid_search = GridSearchCV(estimator=xgb_model, param_grid=param_grid,
cv=tscv, scoring='neg_mean_squared_error', n_jobs=-1)
grid_search.fit(X, y)
# Best estimator
best_estimator = grid_search.best_estimator_
8__________________________________________________________________
___________________-
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
from sklearn.metrics import mean_squared_error, accuracy_score, f1_score
import matplotlib.pyplot as plt
import ccxt
import time
import joblib
import json
import logging
return real_time_data
except Exception as e:
print(f"Error fetching live data: {e}")
return pd.DataFrame()
return df
except ccxt.NetworkError as e:
print('Network error:', e)
print(f"Retrying ({retries+1}/{max_retries})...")
retries += 1
time.sleep(retry_delay)
except ccxt.ExchangeError as e:
print('Exchange error:', e)
return pd.DataFrame() # Return an empty DataFrame in case of exchange
error
except Exception as e:
print('Error:', e)
return pd.DataFrame() # Return an empty DataFrame for any other error
print("Max retries exceeded. Unable to fetch data.")
return pd.DataFrame() # Return an empty DataFrame if max retries exceeded
# Grid search
grid_search = GridSearchCV(estimator=xgb_model, param_grid=param_grid,
cv=tscv, scoring='neg_mean_squared_error', n_jobs=-1)
grid_search.fit(X, y)
else:
logging.error(f"Data fetching failed for timeframe: {timeframe}")
logging.info("Training and evaluation completed for all timeframes.")