atsuga commited on
Commit
ccbc0e5
·
verified ·
1 Parent(s): a573be7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -103
app.py CHANGED
@@ -3,6 +3,7 @@ from asgiref.wsgi import WsgiToAsgi
3
  from flask import Flask, render_template, request, jsonify
4
  import pickle
5
  import numpy as np
 
6
  import pandas as pd
7
  from fastapi.middleware.wsgi import WSGIMiddleware
8
 
@@ -15,116 +16,85 @@ with open('model.pkl', 'rb') as model_file:
15
  with open('scaler.pkl', 'rb') as scaler_file:
16
  scaler = pickle.load(scaler_file)
17
 
18
- # List untuk menyimpan 7 prediksi terakhir
19
- predictions_history = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  # Halaman utama
22
  @flask_app.route('/')
23
  def home():
24
  return render_template('index.html')
25
 
26
- # Endpoint untuk prediksi berdasarkan input pengguna
27
- @flask_app.route('/predict', methods=['POST'])
28
  def predict():
29
- try:
30
- # Mendapatkan data dari form input
31
- input_data = request.get_json()
32
-
33
- # Ambil nilai input (pastikan semuanya adalah angka)
34
- sell_1 = float(input_data['features'][2])
35
- sell_2 = float(input_data['features'][1])
36
- sell_3 = float(input_data['features'][0])
37
-
38
- # Normalisasi data menggunakan scaler
39
- last_row = np.array([
40
- scaler.transform([[sell_1]]).flatten()[0],
41
- scaler.transform([[sell_2]]).flatten()[0],
42
- scaler.transform([[sell_3]]).flatten()[0]
43
- ]).reshape(1, -1)
44
-
45
- # Buat DataFrame dari nilai yang telah dinormalisasi
46
- last_row_df = pd.DataFrame(last_row, columns=['sell-1', 'sell-2', 'sell-3'])
47
-
48
- # Prediksi harga berdasarkan model
49
- predicted_value_normalized = model.predict(last_row_df)
50
- predicted_value = scaler.inverse_transform(predicted_value_normalized.reshape(-1, 1))
51
-
52
- # Ambil harga emas terakhir untuk perhitungan persentase
53
- last_price_inversed = sell_1 # Menggunakan harga hari ketiga (sell_3) sebagai harga terakhir
54
-
55
- # Hitung perubahan persentase
56
- percentage_change = ((predicted_value[0][0] - last_price_inversed) / last_price_inversed) * 100
57
-
58
- # Tentukan tanda perubahan (positif atau negatif)
59
- change_sign = '+' if percentage_change > 0 else ''
60
-
61
- # Simpan hasil prediksi dalam history (menyimpan 7 prediksi terakhir)
62
- predictions_history.append(predicted_value[0][0])
63
- if len(predictions_history) > 7:
64
- predictions_history.pop(0)
65
-
66
- # Kembalikan hasil prediksi dalam bentuk JSON
67
- return jsonify({
68
- 'last_price': last_price_inversed,
69
- 'predicted_value': predicted_value[0][0],
70
- 'percentage_change': f"{change_sign}{percentage_change:.2f}%",
71
- 'raw_data': input_data,
72
- 'predictions_history': predictions_history # Tampilkan 7 prediksi terakhir
73
- })
74
-
75
- except Exception as e:
76
- return jsonify({'error': str(e)}), 400
77
-
78
- # Endpoint untuk prediksi otomatis selama 7 hari
79
- @flask_app.route('/auto-predict', methods=['POST'])
80
- def predict_seven_days():
81
- try:
82
- # Mendapatkan data yang dikirimkan dari frontend
83
- input_data = request.get_json()
84
-
85
- # Ambil nilai input (pastikan semuanya adalah angka)
86
- price_day_1 = float(input_data['features'][0])
87
- price_day_2 = float(input_data['features'][1])
88
- price_day_3 = float(input_data['features'][2])
89
-
90
- # Normalisasi data
91
- last_row = np.array([
92
- scaler.transform([[price_day_1]]).flatten()[0],
93
- scaler.transform([[price_day_2]]).flatten()[0],
94
- scaler.transform([[price_day_3]]).flatten()[0]
95
- ]).reshape(1, -1)
96
-
97
- last_row_df = pd.DataFrame(last_row, columns=['sell-1', 'sell-2', 'sell-3'])
98
-
99
- # Prediksi selama 7 hari
100
- predictions = []
101
- current_price = [price_day_1, price_day_2, price_day_3]
102
-
103
- for day in range(7):
104
- # Prediksi harga untuk hari ini
105
- predicted_value_normalized = model.predict(last_row_df)
106
- predicted_value = scaler.inverse_transform(predicted_value_normalized.reshape(-1, 1))
107
-
108
- # Menyimpan prediksi untuk hari ini
109
- predictions.append(predicted_value[0][0])
110
-
111
- # Update data input untuk prediksi hari berikutnya
112
- current_price = [current_price[1], current_price[2], predicted_value[0][0]]
113
- last_row = np.array([
114
- scaler.transform([[current_price[0]]]).flatten()[0],
115
- scaler.transform([[current_price[1]]]).flatten()[0],
116
- scaler.transform([[current_price[2]]]).flatten()[0]
117
- ]).reshape(1, -1)
118
- last_row_df = pd.DataFrame(last_row, columns=['sell-1', 'sell-2', 'sell-3'])
119
-
120
- # Kembalikan hasil prediksi selama 7 hari
121
- return jsonify({
122
- 'predictions': predictions,
123
- 'raw_data': input_data
124
  })
125
 
126
- except Exception as e:
127
- return jsonify({'error': str(e)}), 400
128
-
129
- faapp = FastAPI()
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  app.mount("/", WSGIMiddleware(flask_app))
 
3
  from flask import Flask, render_template, request, jsonify
4
  import pickle
5
  import numpy as np
6
+ import requests
7
  import pandas as pd
8
  from fastapi.middleware.wsgi import WSGIMiddleware
9
 
 
16
  with open('scaler.pkl', 'rb') as scaler_file:
17
  scaler = pickle.load(scaler_file)
18
 
19
+ # Data contoh untuk windowed_data dan normalized_df, bisa diganti sesuai data nyata
20
+ windowed_data = pd.DataFrame() # Pastikan windowed_data ada
21
+ normalized_df = pd.DataFrame() # Pastikan normalized_df ada
22
+
23
+ # Fungsi prediksi untuk 7 hari ke depan
24
+ def predict_7_days(windowed_data, normalized_df, linear_model, scaler):
25
+ predictions = []
26
+ last_row = windowed_data.drop(columns=['sell', 'buy']).iloc[-1].values.reshape(1, -1)
27
+
28
+ # Iterasi untuk 7 hari ke depan
29
+ for _ in range(7):
30
+ # Prediksi nilai untuk hari berikutnya
31
+ predicted_value_normalized = linear_model.predict(last_row)
32
+ predicted_value = scaler.inverse_transform(predicted_value_normalized.reshape(-1, 2))
33
+
34
+ # Simpan prediksi
35
+ predictions.append(predicted_value[0])
36
+
37
+ # Update input untuk iterasi berikutnya
38
+ new_row_normalized = np.hstack([last_row[0, 2:], predicted_value_normalized[0]])
39
+ last_row = new_row_normalized.reshape(1, -1)
40
+
41
+ # Transformasikan prediksi menjadi DataFrame untuk visualisasi
42
+ predictions_df = pd.DataFrame(
43
+ predictions,
44
+ columns=['sell', 'buy'],
45
+ index=pd.date_range(start=normalized_df.index[-1] + pd.Timedelta(days=1), periods=7)
46
+ )
47
+
48
+ # Harga terakhir
49
+ last_price = scaler.inverse_transform(normalized_df[['sell', 'buy']].iloc[-1].values.reshape(-1, 2))
50
+
51
+ # Hitung persentase perubahan harian
52
+ predictions_df['sell_change'] = predictions_df['sell'].pct_change().fillna(0) * 100
53
+ predictions_df['buy_change'] = predictions_df['buy'].pct_change().fillna(0) * 100
54
+
55
+ # Hitung perubahan total dari hari ini ke hari ketujuh
56
+ total_sell_change = ((predictions_df['sell'].iloc[-1] - last_price[0][0]) / last_price[0][0]) * 100
57
+ total_buy_change = ((predictions_df['buy'].iloc[-1] - last_price[0][1]) / last_price[0][1]) * 100
58
+
59
+ return predictions_df, total_sell_change, total_buy_change, last_price
60
+
61
 
62
  # Halaman utama
63
  @flask_app.route('/')
64
  def home():
65
  return render_template('index.html')
66
 
67
+ @flask_app.route('/predict', methods=['GET'])
 
68
  def predict():
69
+ # Prediksi harga untuk 7 hari ke depan
70
+ predictions_df, total_sell_change, total_buy_change, last_price = predict_7_days(windowed_data, normalized_df, linear_model, scaler)
71
+
72
+ # Membuat hasil prediksi untuk respons JSON
73
+ predictions_result = []
74
+ for date, (sell, buy, sell_change, buy_change) in predictions_df.iterrows():
75
+ predictions_result.append({
76
+ 'date': date.strftime('%Y-%m-%d'),
77
+ 'sell': round(sell, 2),
78
+ 'buy': round(buy, 2),
79
+ 'sell_change': round(sell_change, 2),
80
+ 'buy_change': round(buy_change, 2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  })
82
 
83
+ # Menambahkan perubahan total
84
+ result = {
85
+ 'last_price': {
86
+ 'sell': round(last_price[0][0], 2),
87
+ 'buy': round(last_price[0][1], 2)
88
+ },
89
+ 'predictions': predictions_result,
90
+ 'total_changes': {
91
+ 'sell_change': round(total_sell_change, 2),
92
+ 'buy_change': round(total_buy_change, 2)
93
+ }
94
+ }
95
+
96
+ return jsonify(result)
97
+
98
+ # Menjalankan aplikasi Flask
99
+ app = FastAPI()
100
  app.mount("/", WSGIMiddleware(flask_app))