allora/app.py

99 lines
2.9 KiB
Python
Raw Normal View History

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-04 22:25:48 +03:00
from model import download_data, format_data, train_model, get_training_data_path
2024-08-25 21:55:45 +03:00
from config import model_file_path
app = Flask(__name__)
def update_data():
2024-09-04 22:25:48 +03:00
"""Download price data, format data and train model for each token."""
tokens = ["ETH", "BTC", "SOL", "BNB", "ARB"]
2024-08-25 21:55:45 +03:00
download_data()
2024-09-04 22:25:48 +03:00
for token in tokens:
format_data(token)
train_model(token)
2024-08-25 21:55:45 +03:00
2024-09-04 22:22:25 +03:00
def get_inference(token, period):
2024-09-03 04:24:43 +03:00
try:
2024-09-04 22:25:48 +03:00
model_path = model_file_path[token]
with open(model_path, "rb") as f:
2024-09-03 04:24:43 +03:00
loaded_model = pickle.load(f)
2024-09-04 22:25:48 +03:00
# Загружаем последние данные для данного токена
training_price_data_path = get_training_data_path(token)
2024-09-03 04:24:43 +03:00
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
# Используем последние значения признаков для предсказания
2024-09-04 22:22:25 +03:00
last_row = price_data.iloc[-1]
last_timestamp = last_row["timestamp"]
2024-09-04 22:25:48 +03:00
# Преобразуем период в секунды
2024-09-04 22:22:25 +03:00
period_seconds = convert_period_to_seconds(period)
new_timestamp = last_timestamp + period_seconds
2024-09-04 22:25:48 +03:00
# Формируем данные для предсказания с новым timestamp
2024-09-04 22:22:25 +03:00
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"],
2024-09-03 04:24:43 +03:00
]
2024-09-04 22:22:25 +03:00
).reshape(1, -1)
2024-09-04 22:25:48 +03:00
# Делаем предсказание
2024-09-04 22:22:25 +03:00
future_price_pred = loaded_model.predict(X_new)
return future_price_pred[0]
2024-09-03 04:24:43 +03:00
except Exception as e:
print(f"Error during inference: {str(e)}")
raise
2024-08-25 21:55:45 +03:00
2024-09-04 22:22:25 +03:00
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}")
2024-08-25 21:55:45 +03:00
2024-09-04 22:22:25 +03:00
@app.route("/inference/<string:token>/<string:period>")
def generate_inference(token, period):
"""Generate inference for given token and period."""
2024-08-25 21:55:45 +03:00
try:
2024-09-04 22:22:25 +03:00
inference = get_inference(token, period)
2024-08-25 21:55:45 +03:00
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()
2024-09-04 22:25:48 +03:00
app.run(host="0.0.0.0", port=8080)