99 lines
2.9 KiB
Python
99 lines
2.9 KiB
Python
import json
|
||
import pickle
|
||
import pandas as pd
|
||
import numpy as np
|
||
from datetime import datetime
|
||
from flask import Flask, jsonify, Response
|
||
from model import download_data, format_data, train_model, get_training_data_path
|
||
from config import model_file_path
|
||
|
||
app = Flask(__name__)
|
||
|
||
|
||
def update_data():
|
||
"""Download price data, format data and train model for each token."""
|
||
tokens = ["ETH", "BTC", "SOL", "BNB", "ARB"]
|
||
download_data()
|
||
for token in tokens:
|
||
format_data(token)
|
||
train_model(token)
|
||
|
||
|
||
def get_inference(token, period):
|
||
try:
|
||
model_path = model_file_path[token]
|
||
|
||
with open(model_path, "rb") as f:
|
||
loaded_model = pickle.load(f)
|
||
|
||
# Загружаем последние данные для данного токена
|
||
training_price_data_path = get_training_data_path(token)
|
||
price_data = pd.read_csv(training_price_data_path)
|
||
|
||
# Используем последние значения признаков для предсказания
|
||
last_row = price_data.iloc[-1]
|
||
last_timestamp = last_row["timestamp"]
|
||
|
||
# Преобразуем период в секунды
|
||
period_seconds = convert_period_to_seconds(period)
|
||
new_timestamp = last_timestamp + period_seconds
|
||
|
||
# Формируем данные для предсказания с новым timestamp
|
||
X_new = np.array(
|
||
[
|
||
new_timestamp,
|
||
last_row["price_diff"],
|
||
last_row["volatility"],
|
||
last_row["volume"],
|
||
last_row["moving_avg_7"],
|
||
last_row["moving_avg_30"],
|
||
]
|
||
).reshape(1, -1)
|
||
|
||
# Делаем предсказание
|
||
future_price_pred = loaded_model.predict(X_new)
|
||
return future_price_pred[0]
|
||
|
||
except Exception as e:
|
||
print(f"Error during inference: {str(e)}")
|
||
raise
|
||
|
||
|
||
def convert_period_to_seconds(period):
|
||
"""Конвертируем период в секунды."""
|
||
if period.endswith("min"):
|
||
return int(period[:-3]) * 60
|
||
elif period.endswith("h"):
|
||
return int(period[:-1]) * 3600
|
||
elif period.endswith("d"):
|
||
return int(period[:-1]) * 86400
|
||
else:
|
||
raise ValueError(f"Unknown period format: {period}")
|
||
|
||
|
||
@app.route("/inference/<string:token>/<string:period>")
|
||
def generate_inference(token, period):
|
||
"""Generate inference for given token and period."""
|
||
try:
|
||
inference = get_inference(token, period)
|
||
return Response(str(inference), status=200)
|
||
except Exception as e:
|
||
return Response(
|
||
json.dumps({"error": str(e)}), status=500, mimetype="application/json"
|
||
)
|
||
|
||
|
||
@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=8080)
|