Introduction
In the fast-paced world of cryptocurrency trading, having an edge can make all the difference. Predicting price movements, even just a minute ahead, can significantly enhance trading strategies. This article delves into a Python-based approach that employs machine learning to forecast cryptocurrency prices a minute in advance, it can be surprisingly accurate. And the best part? It already seamlessly integrates with your Alpaca Markets account, just add your API keys.
The Power of Machine Learning in Trading
Machine learning, a subset of artificial intelligence, has been making waves in various industries, and cryptocurrency trading is no exception. By analysing historical data, machine learning models can identify patterns and make predictions about future data points. In the context of trading, this means forecasting price movements to inform buy or sell decisions.
A Glimpse into the Strategy
Our approach uses a simple linear regression model, a fundamental algorithm in the machine learning toolkit. The model is trained on the past week’s minute-by-minute price data of Bitcoin, aiming to predict its adjusted closing price 15 minutes into the future.
Based on the model’s prediction and the current price, the script decides on a trading action:
- If the predicted price is higher than the current price, it suggests a buy.
- If it’s lower, it leans towards a sell.
Continuous Learning and Decision Making
One of the standout features of this script is its ability to adapt. Every minute, it fetches the latest price data, retrains the model, and recalculates its predictions. This ensures that trading decisions are always based on the freshest data, adapting to the volatile nature of the cryptocurrency market.
Conclusion
Machine learning offers traders a potent tool, enabling more informed and timely decisions. While the provided script is a foundational implementation, it paves the way for more intricate strategies and models. As the world of cryptocurrency continues to evolve, tools like these will be indispensable for traders looking to stay ahead of the curve.
Code
from alpaca.trading.requests import MarketOrderRequest, GetAssetsRequest
from alpaca.trading.enums import OrderSide, TimeInForce, AssetClass
import datetime
import sched
import time
import pandas as pd
import pytz
import yfinance as yf
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import warnings
from alpaca.trading.client import TradingClient
API_KEY = 'AAAAA'
API_SECRET = 'AAAA'
BASE_URL = 'https://api.alpaca.markets' #live
trading_client = TradingClient(API_KEY, API_SECRET, paper=False)
side = "buy"
warnings.simplefilter(action='ignore', category=UserWarning)
bst = pytz.timezone('Europe/London')
def fetch_initial_data():
start_date = (datetime.datetime.now(bst) - datetime.timedelta(days=7))
end_date = datetime.datetime.now(bst)
return yf.download('BTC-USD', start=start_date, end=end_date, interval="1m", progress=False)
def train_model(df):
forecast_out = 15
df['Prediction'] = df['Adj Close'].shift(-forecast_out)
X = df.drop('Prediction', axis=1).values
y = df['Prediction'].values[:-forecast_out]
X = X[:-forecast_out]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
return LinearRegression().fit(X_train, y_train)
def get_prediction(df, model):
y_pred = model.predict(df.drop("Prediction", axis=1, errors="ignore"))
return y_pred[-1]
def fetch_latest_data(ticker="BTC-USD", interval="1m"):
end_date = (datetime.datetime.now(bst) - datetime.timedelta(minutes=15))
start_date = (end_date - datetime.timedelta(minutes=1))
new_data = yf.download(ticker, start=start_date, end=end_date, interval=interval, progress=False)
return new_data
s = sched.scheduler(time.time, time.sleep)
def loop(df):
s.enter(60, 1, loop, (df,))
try:
new_data = fetch_latest_data()
df = pd.concat([df, new_data])
end_date = datetime.datetime.now(bst)
start_date = (end_date - datetime.timedelta(days=7))
df = df[(df.index >= start_date) & (df.index <= end_date)]
except Exception as e:
print("Error:", e)
model = train_model(df)
pred = get_prediction(df, model)
last = df['Adj Close'].iloc[-1]
global side
if side == "buy" and pred > last: #*1.01:
print("buying")
cancel_statuses = trading_client.cancel_orders()
market_order_data = MarketOrderRequest(
symbol='BTC/USD',
notional=float(str(trading_client.get_account().equity))*0.98/last,
side=OrderSide.BUY,
time_in_force=TimeInForce.GTC
)
#market_order = trading_client.submit_order(
# order_data=market_order_data
#)
#print(market_order)
side="sell"
elif side == "sell" and pred < last: #*0.99:
print("selling")
cancel_statuses = trading_client.cancel_orders()
market_order_data = MarketOrderRequest(
symbol='BTC/USD',
notional=float(str(trading_client.get_account().equity))*0.98/last,
side=OrderSide.SELL,
time_in_force=TimeInForce.GTC
)
#market_order = trading_client.submit_order(
# order_data=market_order_data
#)
#print(market_order)
side="buy"
if __name__ == "__main__":
print("MATradingBot v0.1b")
print("* Entering Trading Cycle")
loop(fetch_initial_data())
s.run()