File size: 4,902 Bytes
bfdbda2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | import requests
import json
import numpy as np
from math import sqrt
import pandas as pd
from sklearn.metrics import mean_squared_error, mean_absolute_error
from xgboost import XGBRegressor
from sklearn.model_selection import train_test_split
import streamlit as st
inp = st.text_input('BTCUSDT')
#ino = st.text_input('min or hour')
def fetch_data(access_id, secret_id):
base_url = 'https://api.coinex.com/v1/market/kline'
data = []
last_timestamp = None
limit = 100
total_size = 1000 # set a large number to fetch all data
while len(data) < total_size:
params = {
'market': inp,
'type': '1hour',
'limit': limit,
'before': last_timestamp,
'asc': 0
}
headers = {
'Content-Type': 'application/json',
'User-Agent': 'Your User Agent',
'AccessId': access_id,
'SecretId': secret_id
}
response = requests.get(base_url, params=params, headers=headers)
if response.status_code == 200:
for item in response.json()['data']:
data.append([item[0], item[1], item[4]])
last_timestamp = item[0]
if len(response.json()['data']) < limit:
# this means we've reached the end of the data
break
else:
print('Error fetching data. Status code:', response.status_code)
return None
'''
df = pd.DataFrame(data, columns=['Timestamp', 'Open', 'Close', 'High', 'Low', 'Volume'])
df['Timestamp'] = pd.to_datetime(df['Timestamp'], unit='ms')
# Set the timestamp as the index
df.set_index('Timestamp', inplace=True)
# Drop the missing values
data = df.dropna()
# Define inputs and outputs
X = data.drop('Close', axis=1).values # remove the 'Close' column for inputs
y = data['Close'].values
'''
df = pd.DataFrame(data, columns=['Timestamp', 'Open', 'Close'])
df['Timestamp'] = pd.to_datetime(df['Timestamp'], unit='ms')
# Set the timestamp as the index
df.set_index('Timestamp', inplace=True)
data = df[['Open', 'Close']]
data['Previous_Close'] = data['Close'].shift(1)
# Drop the missing values created by shifting
data = data.dropna()
# Define inputs and outputs
X = data['Previous_Close'].values.reshape(-1, 1)
y = data['Close'].values
# Added checks for null values and data types
print("X null values:", np.isnan(X.astype(float)).any())
print("y null values:", np.isnan(y.astype(float)).any())
print("X data type:", X.dtype)
print("y data type:", y.dtype)
# Split the data into training and testing datasets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_train = X_train.astype(float)
X_test = X_test.astype(float)
y_train = y_train.astype(float)
y_test = y_test.astype(float)
# Added checks for null values and data types after splitting
#print("X_train null values:", X_train.isnull().values.any())
#print("X_test null values:", X_test.isnull().values.any())
#print("y_train null values:", y_train.isnull().values.any())
# print("y_test null values:", y_test.isnull().values.any())
print("X_train data type:", X_train.dtype)
print("X_test data type:", X_test.dtype)
print("y_train data type:", y_train.dtype)
print("y_test data type:", y_test.dtype)
# Initialize XGBoost regressor model
model = XGBRegressor(n_estimators=100, learning_rate=0.1, objective='reg:squarederror')
# Train the model
model.fit(X_train, y_train)
# Evaluate the model
train_predictions = model.predict(X_train)
train_rmse = sqrt(mean_squared_error(y_train, train_predictions))
print(f"Train RMSE: {train_rmse}")
test_predictions = model.predict(X_test)
test_rmse = sqrt(mean_squared_error(y_test, test_predictions))
print(f"Test RMSE: {test_rmse}")
# Predict tomorrow's close price using the most recent close price
latest_close = data['Close'].iloc[-1]
latest_close = float(latest_close)
# Added check for the data type of 'latest_close'
print("latest_close data type:", type(latest_close))
latest_close_reshaped = np.array([[latest_close]])
# Reshape the input
#latest_close_reshaped = np.array(latest_close).reshape(1, -1)
# Added check for the data type of 'latest_close_reshaped'
print("latest_close_reshaped data type:", latest_close_reshaped.dtype)
# Make prediction
predicted_close = model.predict(latest_close_reshaped)
#st.write('سوسیس')
st.write(latest_close)
#st.write(test_rmse)
return predicted_close
#, it getting this error : File "/home/user/app/app.py", line 83 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) ^ IndentationError: unexpected indent, debug it |