multistep / app.py
atsuga's picture
Update app.py
4e74780 verified
from fastapi import FastAPI
from asgiref.wsgi import WsgiToAsgi
from flask import Flask, render_template, request, jsonify
import pickle
import numpy as np
import pandas as pd
from fastapi.middleware.wsgi import WSGIMiddleware
flask_app = Flask(__name__)
# Load model dan scaler yang sudah disimpan
with open('model.pkl', 'rb') as model_file:
linear_model = pickle.load(model_file)
with open('scaler.pkl', 'rb') as scaler_file:
scaler = pickle.load(scaler_file)
# Fungsi prediksi untuk 7 hari ke depan
def predict_7_days(sell_features, buy_features, linear_model, scaler):
# Data dari frontend
# Ambil nilai input (pastikan semuanya adalah angka)
sell_1 = float(sell_features[6])
sell_2 = float(sell_features[5])
sell_3 = float(sell_features[4])
sell_4 = float(sell_features[3])
sell_5 = float(sell_features[2])
sell_6 = float(sell_features[1])
sell_7 = float(sell_features[0])
buy_1 = float(buy_features[6])
buy_2 = float(buy_features[5])
buy_3 = float(buy_features[4])
buy_4 = float(buy_features[3])
buy_5 = float(buy_features[2])
buy_6 = float(buy_features[1])
buy_7 = float(buy_features[0])
# Menyusun data jual dan beli sebagai pasangan (sell, buy)
data = np.array([
[sell_1, buy_1],
[sell_2, buy_2],
[sell_3, buy_3],
[sell_4, buy_4],
[sell_5, buy_5],
[sell_6, buy_6],
[sell_7, buy_7]
])
# Normalisasi data menggunakan scaler (menormalkan pasangan jual dan beli)
normalized_data = scaler.transform(data)
# Buat DataFrame dari nilai yang telah dinormalisasi
# Kolom disesuaikan untuk 7 fitur jual dan 7 fitur beli
last_row = pd.DataFrame(
normalized_data.flatten().reshape(1, -1),
columns=['sell-1', 'sell-2', 'sell-3', 'sell-4', 'sell-5', 'sell-6', 'sell-7', 'buy-1', 'buy-2', 'buy-3', 'buy-4', 'buy-5', 'buy-6', 'buy-7']
)
predictions = []
# Iterasi untuk 7 hari ke depan
for _ in range(7):
# Prediksi nilai untuk hari berikutnya
predicted_value_normalized = linear_model.predict(last_row)
predicted_value = scaler.inverse_transform(predicted_value_normalized.reshape(-1, 2))
# Simpan prediksi
predictions.append(predicted_value[0])
# Update input untuk iterasi berikutnya
new_row_normalized = np.hstack([last_row.iloc[0, 2:], predicted_value_normalized[0]])
last_row = pd.DataFrame(new_row_normalized.reshape(1, -1), columns=last_row.columns)
# Transformasikan prediksi menjadi DataFrame untuk visualisasi
predictions_df = pd.DataFrame(
predictions,
columns=['sell', 'buy'],
index=pd.date_range(start=pd.Timestamp.today() + pd.Timedelta(days=1), periods=7)
)
# Harga terakhir dari data sebelumnya
last_price = [sell_features[7], buy_features[7]] # Harga jual dan beli terakhir
# Hitung persentase perubahan harian
# Data pertama dihitung berdasarkan last_price
predictions_df['sell_change'] = predictions_df['sell'].pct_change() * 100
predictions_df['buy_change'] = predictions_df['buy'].pct_change() * 100
# Perubahan untuk data pertama dihitung manual
predictions_df.loc[predictions_df.index[0], 'sell_change'] = ((predictions_df['sell'].iloc[0] - last_price[0]) / last_price[0]) * 100
predictions_df.loc[predictions_df.index[0], 'buy_change'] = ((predictions_df['buy'].iloc[0] - last_price[1]) / last_price[1]) * 100
# Ganti nilai NaN untuk baris lainnya dengan 0
predictions_df['sell_change'] = predictions_df['sell_change'].fillna(0)
predictions_df['buy_change'] = predictions_df['buy_change'].fillna(0)
# Hitung perubahan total dari hari ini ke hari ketujuh
total_sell_change = ((predictions_df['sell'].iloc[-1] - last_price[0]) / last_price[0]) * 100
total_buy_change = ((predictions_df['buy'].iloc[-1] - last_price[1]) / last_price[1]) * 100
return predictions_df, total_sell_change, total_buy_change, last_price
# Halaman utama
@flask_app.route('/')
def home():
return render_template('index.html')
@flask_app.route('/predict', methods=['POST'])
def predict():
data = request.get_json() # Mengambil data dari request JSON
# Ambil fitur sell dan buy yang dikirim dari frontend
sell_features = data['sell_features']
buy_features = data['buy_features']
# Prediksi harga untuk 7 hari ke depan
predictions_df, total_sell_change, total_buy_change, last_price = predict_7_days(sell_features, buy_features, linear_model, scaler)
# Membuat hasil prediksi untuk respons JSON
predictions_result = []
for date, (sell, buy, sell_change, buy_change) in predictions_df.iterrows():
predictions_result.append({
'date': date.strftime('%Y-%m-%d'),
'sell': round(sell, 2),
'buy': round(buy, 2),
'sell_change': round(sell_change, 2),
'buy_change': round(buy_change, 2)
})
# Menambahkan perubahan total
result = {
'last_price': {
'sell': round(last_price[0], 2),
'buy': round(last_price[1], 2)
},
'predictions': predictions_result,
'total_changes': {
'sell_change': round(total_sell_change, 2),
'buy_change': round(total_buy_change, 2)
}
}
return jsonify(result)
# Menjalankan aplikasi FastAPI yang memanggil aplikasi Flask
app = FastAPI()
app.mount("/", WSGIMiddleware(flask_app))