이번 포스팅은 파이썬과 머신러닝을 활용한 금융 데이터 분석과 실질적인 적용 사례를 보여준다.
모듈 불러오기 및 학습 날짜 범위 설정
import pandas as pd
from pykrx import stock
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
import numpy as np
import mplcursors
# 삼성전자의 코드와 날짜 범위 설정
ticker = "005930"
end_date = pd.Timestamp.today().strftime('%Y%m%d')
start_date = (pd.Timestamp.today() - pd.DateOffset(years=1)).strftime('%Y%m%d')
데이터 수집과 정규화
먼저 pykrx 모듈로 삼성전자의 최근 1년간의 OHLCV와 펀더멘털 지표를 수집한다. 중요한 지표인 종가와 PER에 집중하여, MinMaxScaler를 활용해 데이터를 0과 1 사이로 정규화한다.
# OHLCV 데이터 수집
ohlcv = stock.get_market_ohlcv_by_date(start_date, end_date, ticker)
# 펀더멘털 지표 데이터 수집
fundamental = stock.get_market_fundamental_by_date(start_date, end_date, ticker)
# 데이터 병합
combined_data = ohlcv.join(fundamental)
# 데이터 정규화
data = combined_data[['종가', 'PER']].values
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
# LSTM을 위한 데이터 준비
def create_dataset(dataset, look_back=60):
X, Y = [], []
for i in range(len(dataset) - look_back - 1):
a = dataset[i:(i + look_back), :]
X.append(a)
Y.append(dataset[i + look_back, 0])
return np.array(X), np.array(Y)
look_back = 60
X, Y = create_dataset(scaled_data, look_back)
LSTM 모델 구성 및 훈련
TensorFlow를 사용해 LSTM 모델을 구성한다. 이 모델은 시계열 데이터를 학습하기 위해 설계되었다. 모델은 여러 LSTM 레이어와 Dropout 레이어로 구성하여 과적합을 방지한다.
# LSTM 모델 구성
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(X.shape[1], 2)))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(units=25))
model.add(Dense(units=1))
# 모델 컴파일 및 훈련
model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(X, Y, epochs=100, batch_size=32)
미래 주가 예측
훈련된 모델을 사용하여 미래 일주일간의 주가를 예측한다. 이 과정은 마지막 60일의 데이터를 기반으로 다음 날의 주가를 예측하는 것을 반복한다.
# 미래 주가 예측
future_days = 7
future_predictions = []
last_sequence = scaled_data[-look_back:]
current_sequence = last_sequence.reshape((1, look_back, 2))
# 미래 예측을 위한 반복
for _ in range(future_days):
next_price = model.predict(current_sequence)[0, 0]
future_predictions.append(next_price)
# next_price를 시퀀스에 추가
current_sequence_list = current_sequence[0].tolist()
current_sequence_list.append([next_price, 0]) # 0은 더미 값 (PER 대신 사용)
current_sequence_list.pop(0) # 첫 번째 요소 제거
current_sequence = np.array([current_sequence_list])
역정규화
역정규화를 하기 전에 예측 결과의 더미 열을 만든다.
# 예측 결과를 역정규화하기 전에 더미 열을 추가
future_predictions_array = np.array(future_predictions).reshape(-1, 1)
dummy = np.zeros((future_predictions_array.shape[0], 1))
inverse_input = np.hstack((future_predictions_array, dummy))
# 예측 결과 역정규화
future_prices = scaler.inverse_transform(inverse_input)[:, 0]
인터렉티브한 시각화
matplotlib과 mplcursors 라이브러리를 통해 실제 주가와 예측 주가를 그래프로 시각화한다. mplcursors 모듈로 마우스 호버 기능을 활성화 한다. x, y좌표 대신 주가가 표시 되도록 lambda sel: sel.annotation.set_text('Price: {}'.format(sel.target[1]))를 넣는다.
# 실제 과거 1년간의 종가 데이터
actual_prices = combined_data['종가'].values
# 예측 결과와 실제 데이터를 같이 시각화
plt.figure(figsize=(15, 6))
plt.plot(actual_prices, label='Actual Prices')
plt.plot(np.arange(len(actual_prices), len(actual_prices) + future_days), future_prices, label='Predicted Prices')
plt.title('Samsung Stock Price Prediction')
plt.xlabel('Days')
plt.ylabel('Price')
plt.legend()
# 마우스 호버 기능 활성화
cursor = mplcursors.cursor(hover=True)
cursor.connect("add", lambda sel: sel.annotation.set_text('Price: {}'.format(sel.target[1])))
plt.show()
이렇게 하면 다음과 같이 내일 부터 향후 일주일간의 주가가 예측되는 것을 확인할 수 있다.
파이썬 에러 TypeError: DatetimeArray._generate_range() got an unexpected keyword argument 'closed' (0) | 2024.01.30 |
---|---|
파이썬 matplotlib 모듈 그래프에서 날짜 표시 바꾸기 (0) | 2024.01.30 |
파이썬과 CCXT를 활용한 비트코인 데이터 분석 및 시각화 (1) | 2024.01.29 |
파이썬과 CCXT를 활용한 비트코인 및 이더리움 종가 데이터 분석 (0) | 2024.01.29 |
파이썬과 CCXT로 비트코인 OHLCV 데이터 수집 및 CSV 파일로 저장하기 (0) | 2024.01.29 |