Download Two_parameter.py from Pezh/Coinex: direct link, hf CLI and curl.
- Browser
- Download file 4.9 kB
-
https://huggingface.co/spaces/Pezh/Coinex/resolve/main/Two_parameter.py
- Command line
-
hf download hf://spaces/Pezh/Coinex/Two_parameter.py
-
curl -L -o Two_parameter.py https://huggingface.co/spaces/Pezh/Coinex/resolve/main/Two_parameter.py
4.9 kB
| 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 |