AlanRex commited on
Commit
c1ecc1b
·
verified ·
1 Parent(s): 1712dd3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -35
app.py CHANGED
@@ -6,6 +6,8 @@ from datetime import datetime, timedelta
6
  import pandas as pd
7
  import numpy as np
8
  import yfinance as yf
 
 
9
 
10
  # Dash & Plotly
11
  from dash import Dash, dcc, html, callback
@@ -82,45 +84,49 @@ def create_lstm_dataset(data, time_step=60):
82
  y.append(data[i, 0])
83
  return np.array(X), np.array(y)
84
 
85
- def simple_lstm_predict(data, predict_days=5):
86
- """簡化的LSTM預測模型 (使用統計方法模擬)"""
87
- if len(data) < 60:
88
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
- # 使用移動平均和趨勢分析來模擬深度學習預測
91
- prices = data['Close'].values
92
-
93
- # 計算短期和長期移動平均
94
- ma_short = np.mean(prices[-5:])
95
- ma_medium = np.mean(prices[-20:])
96
- ma_long = np.mean(prices[-60:])
97
-
98
- # 計算價格變化趨勢
99
- recent_trend = np.polyfit(range(20), prices[-20:], 1)[0]
100
- volatility = np.std(prices[-20:]) / np.mean(prices[-20:])
101
-
102
- # 模擬預測邏輯
103
- base_change = recent_trend * predict_days
104
- trend_factor = 1.0
105
-
106
- if ma_short > ma_medium > ma_long:
107
- trend_factor = 1.02 # 上升趨勢
108
- elif ma_short < ma_medium < ma_long:
109
- trend_factor = 0.98 # 下降趨勢
110
- else:
111
- trend_factor = 1.0 # 盤整
112
 
113
- # 加入隨機性模擬市場不確定性
114
- noise_factor = np.random.normal(1, volatility * 0.1)
 
 
 
 
 
 
 
115
 
116
- predicted_price = prices[-1] * trend_factor + base_change + (prices[-1] * noise_factor * 0.01)
117
- change_pct = ((predicted_price - prices[-1]) / prices[-1]) * 100
118
 
119
- return {
120
- 'predicted_price': predicted_price,
121
- 'change_pct': change_pct,
122
- 'confidence': max(0.6, 1 - volatility * 2) # 基於波動率的信心度
123
- }
124
 
125
  def calculate_technical_indicators(df):
126
  """計算技術指標"""
 
6
  import pandas as pd
7
  import numpy as np
8
  import yfinance as yf
9
+ import tensorflow as tf
10
+ from sklearn.preprocessing import MinMaxScaler
11
 
12
  # Dash & Plotly
13
  from dash import Dash, dcc, html, callback
 
84
  y.append(data[i, 0])
85
  return np.array(X), np.array(y)
86
 
87
+ def simple_lstm_predict(df_futures):
88
+
89
+ # 這裡的 df_futures 應為台指期歷史資料
90
+ # 請確保資料集的特徵(例如:'Close')與您模型訓練時的特徵一致。
91
+ data_to_predict = df_futures['Close'].values.reshape(-1, 1)
92
+
93
+ # 模型訓練時通常會進行資料正規化,預測時也需要做同樣的處理
94
+ # 請使用與訓練時相同的scaler,如果沒有,這裡用MinMaxScaler作為範例
95
+ scaler = MinMaxScaler(feature_range=(0, 1))
96
+ scaled_data = scaler.fit_transform(data_to_predict)
97
+
98
+ # 假設您的模型需要 60 天的數據來預測下一個點
99
+ # 這裡可以根據您的模型需求進行調整
100
+ sequence_length = 60
101
+ if len(scaled_data) < sequence_length:
102
+ return None, "數據長度不足以進行預測。"
103
+
104
+ # 取得最新的 60 天資料作為輸入
105
+ last_60_days = scaled_data[-sequence_length:]
106
+ X_test = np.array([last_60_days])
107
+
108
+ # 將資料重塑為模型期望的形狀:[樣本數, 序列長度, 特徵數]
109
+ X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
110
 
111
+ try:
112
+ # 載入已訓練好的 LSTM 模型
113
+ model = tf.keras.models.load_model('stock_lstm_model_v2.keras')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
+ # 進行預測
116
+ predicted_value_scaled = model.predict(X_test)
117
+
118
+ # 反正規化,將預測結果轉換回原始價格範圍
119
+ # 由於scaler是用整個資料集fit的,所以需要用一個假的array來反轉
120
+ # 這是處理單一預測值反正規化的常用方法
121
+ temp_array = np.zeros(shape=(1, 1))
122
+ temp_array[0, 0] = predicted_value_scaled[0, 0]
123
+ prediction = scaler.inverse_transform(temp_array)[0, 0]
124
 
125
+ return prediction, f"預測台指期下一個交易日收盤價為:{prediction:.2f}點。"
 
126
 
127
+ except Exception as e:
128
+ print(f"載入或預測模型時發生錯誤: {e}")
129
+ return None, "模型載入或預測失敗,請檢查模型檔案或輸入資料。"
 
 
130
 
131
  def calculate_technical_indicators(df):
132
  """計算技術指標"""