📈

Predicting Cryptocurrency Prices with Python and Deep Learning

Jul 7, 2024

Predicting Cryptocurrency Prices with Python and Deep Learning

Introduction

  • Purpose: Predict cryptocurrency prices using Python and deep learning
  • Sponsored by Tab Nine: An auto-completion engine powered by GPT-2
    • Supports all modern and relevant programming languages
    • Integratable with most IDEs (e.g., VS Code, IntelliJ, PyCharm)
    • Free basic code completions and privacy-focused (local AI model option available)

Disclaimer

  • Financial Topic Warning: NOT investment advice; focused on programming
  • Model utility: Shows how to predict next day's price using past data but not guaranteed to be accurate or profitable
  • Risk: Possible losses, not responsible for any financial outcomes

Required Libraries

  • numpy, pandas, matplotlib, pandas-datareader, tensorflow, scikit-learn
  • Install commands: pip install numpy pandas matplotlib pandas-datareader tensorflow scikit-learn

Initial Setup and Imports

  • Import necessary libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd import pandas_datareader as web import datetime as dt from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import Dense, Dropout, LSTM from tensorflow.keras.models import Sequential

Fetching Financial Data

  • Define cryptocurrency (e.g., BTC for Bitcoin)
  • Define currency to compare against (e.g., USD)
  • Define training time frame cryptocurrency = 'BTC' against_currency = 'USD' start = dt.datetime(2016, 1, 1) end = dt.datetime.now() data = web.DataReader(f'{cryptocurrency}-{against_currency}', 'yahoo', start, end)

Data Preparation

  • Scale data to be between 0 and 1 scaler = MinMaxScaler(feature_range=(0, 1)) scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1, 1))
  • Set prediction days (e.g., 60) and prepare training dataset prediction_days = 60 x_train, y_train = [], [] for x in range(prediction_days, len(scaled_data)): x_train.append(scaled_data[x-prediction_days:x, 0]) y_train.append(scaled_data[x, 0]) x_train, y_train = np.array(x_train), np.array(y_train) x_train = np.reshape(x_train, (x_train.shape[0, x_train.shape[1], 1))

Building and Training the LSTM Model

  • Defining the Sequential model and adding layers model = Sequential() model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 1))) model.add(Dropout(0.2)) model.add(LSTM(units=50, return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(units=50)) model.add(Dropout(0.2)) model.add(Dense(units=1))
  • Compile and train the model model.compile(optimizer='adam', loss='mean_squared_error') model.fit(x_train, y_train, epochs=25, batch_size=32)

Testing the Model

  • Fetch and prepare test data for prediction test_start = dt.datetime(2020, 1, 1) test_end = dt.datetime.now() test_data = web.DataReader(f'{cryptocurrency}-{against_currency}', 'yahoo', test_start, test_end) actual_prices = test_data['Close'].values total_dataset = pd.concat((data['Close'], test_data['Close']), axis=0) model_inputs = total_dataset[len(total_dataset) - len(test_data) - prediction_days:].values model_inputs = model_inputs.reshape(-1, 1) model_inputs = scaler.transform(model_inputs)
  • Create test sequences and make predictions x_test = [] for x in range(prediction_days, len(model_inputs)): x_test.append(model_inputs[x - prediction_days:x, 0]) x_test = np.array(x_test) x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1)) prediction_prices = model.predict(x_test) prediction_prices = scaler.inverse_transform(prediction_prices)

Visualization

  • Plot actual and predicted prices plt.plot(actual_prices, color='black', label='Actual Prices') plt.plot(prediction_prices, color='green', label='Predicted Prices') plt.title('Cryptocurrency Price Prediction') plt.xlabel('Time') plt.ylabel('Price') plt.legend(loc='upper left') plt.show()

Future Predictions

  • Predict next day or arbitrary future day (e.g., 30 days ahead) real_data = [model_inputs[len(model_inputs) + 1 - prediction_days:len(model_inputs + 1), 0]] real_data = np.array(real_data) real_data = np.reshape(real_data, (real_data.shape[0], real_data.shape[1], 1)) prediction = model.predict(real_data) prediction = scaler.inverse_transform(prediction)
  • Adjusting for future day predictions future_day = 30 x_test = [] for x in range(prediction_days, len(model_inputs)-future_day): x_test.append(model_inputs[x-prediction_days:x, 0]) x_test = np.array(x_test) x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1)) prediction_prices = model.predict(x_test) prediction_prices = scaler.inverse_transform(prediction_prices)

Conclusion

  • Model can predict day-by-day but struggles with longer predictions
  • Potential inaccuracies in volatile cryptocurrency markets
  • Future improvements: better algorithms, more data, other types of models

Experiment and Feedback

  • Test with different cryptocurrencies (ETH, XRP, etc.) and different parameters
  • Share thoughts and performance results in comments

Closing

  • Remember to check out and utilize Tab Nine
  • Encouragement to like, comment, subscribe and hit notification bell for more content