Powered by Cognitive K.i.
Example code for Predictive modeling
Here's an example code that retrieves real-time Bitcoin prices for the BTC/USD trading pair for the past 24 hours and performs a simple linear regression model to predict the future price:
```python
import requests
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression from datetime import datetime, timedelta
# Function to convert timestamp to datetime def timestamp_to_datetime(timestamp):
return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
# Retrieve Bitcoin prices for the past 24 hours url = "https://www.binance.com/en/terms."
params = {
"symbol": "BTCUSDT",
"interval": "1m",
"limit": 1440,
"endTime": int(datetime.now().timestamp() * 1000), # Current timestamp
"startTime": int((datetime.now() - timedelta(days=1)).timestamp() * 1000) # 24 hours ago } response = requests.get(url, params=params) data = response.json()
# Extract relevant data
df = pd.DataFrame(data, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'trades', 'taker_buy_base', 'taker_buy_quote', 'ignore']) df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms') df['close'] = df['close'].astype(float)
# Calculate features and target variable df['time_index'] = (df['timestamp'] - df['timestamp'].min()).dt.total_seconds() / 60 # Convert timestamp to minutes df['target'] = df['close'].shift(-1) # Shift the closing price upward by 1 row
# Drop NaN rows
df.dropna(inplace=True)
# Train a linear regression model
X = df[['time_index']]
y = df['target']
model = LinearRegression()
model.fit(X, y)
# Predict tomorrow's closing price
next_time_index = df['time_index'].max() + 1 predicted_price = model.predict([[next_time_index]])
# Print the predicted price
print("Predicted BTC/USD price in 24 hours:", predicted_price[0]) ```
Please note that this code uses the Binance API to fetch the data. Make sure you have the necessary libraries installed (`requests`, `pandas`, `numpy`, and `scikit-learn`) before running the code. You may also need to sign up for a Binance account and replace the `symbol` parameter with the correct trading pair if you want to use a different exchange.
Sent from my iPhone