2024-08-25 21:55:45 +03:00
|
|
|
import json
|
|
|
|
import pickle
|
|
|
|
import pandas as pd
|
|
|
|
import numpy as np
|
|
|
|
from datetime import datetime
|
|
|
|
from flask import Flask, jsonify, Response
|
2024-09-03 04:24:43 +03:00
|
|
|
from model import download_data, format_data, train_model, training_price_data_path
|
2024-08-25 21:55:45 +03:00
|
|
|
from config import model_file_path
|
|
|
|
|
|
|
|
app = Flask(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
def update_data():
|
|
|
|
"""Download price data, format data and train model."""
|
|
|
|
download_data()
|
|
|
|
format_data()
|
|
|
|
train_model()
|
|
|
|
|
|
|
|
|
|
|
|
def get_eth_inference():
|
|
|
|
"""Load model and predict current price."""
|
2024-09-03 04:24:43 +03:00
|
|
|
try:
|
|
|
|
with open(model_file_path, "rb") as f:
|
|
|
|
loaded_model = pickle.load(f)
|
|
|
|
|
|
|
|
# Загружаем последние данные из файла
|
|
|
|
price_data = pd.read_csv(training_price_data_path)
|
2024-08-25 21:55:45 +03:00
|
|
|
|
2024-09-03 04:24:43 +03:00
|
|
|
# Используем последние значения признаков для предсказания
|
|
|
|
X_new = (
|
|
|
|
price_data[
|
|
|
|
[
|
|
|
|
"timestamp",
|
|
|
|
"price_diff",
|
|
|
|
"volatility",
|
|
|
|
"volume",
|
|
|
|
"moving_avg_7",
|
|
|
|
"moving_avg_30",
|
|
|
|
]
|
|
|
|
]
|
|
|
|
.iloc[-1]
|
|
|
|
.values.reshape(1, -1)
|
|
|
|
)
|
2024-08-25 21:55:45 +03:00
|
|
|
|
2024-09-03 04:24:43 +03:00
|
|
|
# Делаем предсказание
|
|
|
|
current_price_pred = loaded_model.predict(X_new)
|
|
|
|
|
|
|
|
return current_price_pred[0]
|
|
|
|
except Exception as e:
|
|
|
|
print(f"Error during inference: {str(e)}")
|
|
|
|
raise
|
2024-08-25 21:55:45 +03:00
|
|
|
|
|
|
|
|
|
|
|
@app.route("/inference/<string:token>")
|
|
|
|
def generate_inference(token):
|
|
|
|
"""Generate inference for given token."""
|
|
|
|
if not token or token != "ETH":
|
|
|
|
error_msg = "Token is required" if not token else "Token not supported"
|
2024-09-03 04:24:43 +03:00
|
|
|
return Response(
|
|
|
|
json.dumps({"error": error_msg}), status=400, mimetype="application/json"
|
|
|
|
)
|
2024-08-25 21:55:45 +03:00
|
|
|
|
|
|
|
try:
|
|
|
|
inference = get_eth_inference()
|
|
|
|
return Response(str(inference), status=200)
|
|
|
|
except Exception as e:
|
2024-09-03 04:24:43 +03:00
|
|
|
return Response(
|
|
|
|
json.dumps({"error": str(e)}), status=500, mimetype="application/json"
|
|
|
|
)
|
2024-08-25 21:55:45 +03:00
|
|
|
|
|
|
|
|
|
|
|
@app.route("/update")
|
|
|
|
def update():
|
|
|
|
"""Update data and return status."""
|
|
|
|
try:
|
|
|
|
update_data()
|
|
|
|
return "0"
|
|
|
|
except Exception:
|
|
|
|
return "1"
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
update_data()
|
|
|
|
app.run(host="0.0.0.0", port=8000)
|