forked from Boulder-Investment-Technologies/lppls
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test
110 lines (91 loc) · 3.67 KB
/
test
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
# M-LNN 모델 정의
class M_LNN:
def __init__(self, input_dim, penalty_coeff=1.0):
self.input_dim = input_dim
self.penalty_coeff = penalty_coeff
self.model = self.build_model()
self.optimizer = Adam(learning_rate=0.01)
self.scaler = MinMaxScaler()
def build_model(self):
model = Sequential([
Input(shape=(self.input_dim,)),
Dense(64, activation='relu'),
Dense(32, activation='relu'),
Dense(7) # tc, m, ω, A, B, C1, C2 출력
])
return model
def custom_loss(self, y_true, y_pred):
mse = K.mean(K.square(y_true - y_pred))
penalty = penalty_function(y_pred[:, :3], K.constant([0.8, 0.1, 6]), K.constant([1.2, 1, 13]))
return mse + self.penalty_coeff * penalty
def train(self, X_train, y_train, epochs=100, validation_split=0.2):
self.model.compile(loss=self.custom_loss, optimizer=self.optimizer)
checkpoint = ModelCheckpoint('best_model.keras', save_best_only=True, monitor='val_loss', mode='min')
early_stop = EarlyStopping(patience=20, restore_best_weights=True)
history = self.model.fit(X_train, y_train, epochs=epochs, validation_split=validation_split,
callbacks=[checkpoint, early_stop], verbose=1)
return history
def predict(self, X):
return self.model.predict(X)
# 메인 함수
def main():
# NASDAQ 데이터 다운로드
data = yf.download("^IXIC", "1997-01-01", "2000-12-31")
# observations 배열 생성 (UNIX timestamp로 변환)
observations = np.array([data.index.astype(np.int64) // 10**9, data['Close'].values])
# t_obs와 price 설정
t_obs = observations[0, :] # UNIX timestamp
price = observations[1, :] # 종가
# 데이터 전처리
X = t_obs.reshape(-1, 1)
y = price.reshape(-1, 1)
X_scaler = MinMaxScaler()
y_scaler = MinMaxScaler()
X_scaled = X_scaler.fit_transform(X)
y_scaled = y_scaler.fit_transform(y)
# 모델 초기화 및 학습
deep_model = M_LNN(input_dim=X_scaled.shape[1])
history = deep_model.train(X_scaled, y_scaled, epochs=500)
# 학습 과정 시각화
plt.figure(figsize=(10, 5))
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Model Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
# 예측
predictions_scaled = deep_model.predict(X_scaled)
predictions = predictions_scaled * (y_scaler.data_max_ - y_scaler.data_min_) + y_scaler.data_min_
# 예측 결과를 DataFrame에 저장
deep_res_df = pd.DataFrame({
'Date': data.index,
'Close': data['Close'],
'tc': predictions[:, 0],
'm': predictions[:, 1],
'omega': predictions[:, 2],
'A': predictions[:, 3],
'B': predictions[:, 4],
'C1': predictions[:, 5],
'C2': predictions[:, 6]
})
print(deep_res_df.head())
# LPPLS 피팅 결과 계산
last_pred = predictions[-1]
fitted_values = lppls(X, last_pred[0], last_pred[1], last_pred[2],
last_pred[3], last_pred[4], last_pred[5], last_pred[6])
# 결과 시각화
plt.figure(figsize=(12, 6))
plt.plot(data.index, data['Close'], label='NASDAQ', alpha=0.5) #change name
plt.plot(data.index, fitted_values, 'r-', label='Fitted LPPLS')
plt.title('NASDAQ vs Fitted LPPLS') #change anme
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# 메인 함수 실행
if __name__ == "__main__":
main()