File size: 5,521 Bytes
b659f0b 89a96d1 abd0fdf 89a96d1 abd0fdf 1d8e5e4 abd0fdf 40b25d8 abd0fdf ccbc0e5 89a96d1 e7e5cc5 89a96d1 f5f97a9 ccbc0e5 89a96d1 ccbc0e5 89a96d1 ccbc0e5 89a96d1 ccbc0e5 89a96d1 ccbc0e5 89a96d1 96ba1cc ccbc0e5 96ba1cc 4e74780 ccbc0e5 4e74780 ccbc0e5 6b1f122 ccbc0e5 abd0fdf 9549dea abd0fdf 33cbee4 abd0fdf 59923c3 ccbc0e5 89a96d1 ccbc0e5 abd0fdf ccbc0e5 bc268c0 ccbc0e5 59923c3 ccbc0e5 53b69dc |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 |
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))
|