KOSPI - 예탁금, 수입금액지수, 금리 상관관계¶
약어¶
A : 1년, Q : 1분기, M : 1달, D : 1일
Library¶
In [1]:
import requests
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
### 회귀분석
import numpy as np
import statsmodels.api as sm
plt.rcParams['font.family'] = 'Malgun Gothic'
plt.rcParams['axes.unicode_minus'] = False # 마이너스 기호 깨짐 방지
In [2]:
api_key = ''
Def¶
분석도구
In [3]:
### 최초시점 기준 변동률
def calc_growth_rate(row):
return 1+round((row - row.iloc[0]) / row.iloc[0], 2)
### ex : growth_rate_df = df.apply(calc_growth_rate, axis=0)
In [4]:
# 회귀분석
def osl(df, deva):
#deva = "dependent variable"
col_list = df.columns.tolist()
col_list.remove(deva)
y = df[deva]
X = df[col_list]
# 상수항 추가
X = sm.add_constant(X)
# 회귀 모형 적합
model = sm.OLS(y, X)
result = model.fit()
# 회귀분석 결과 출력
print(result.summary())
ecos_데이터 요청
In [5]:
def ecos_data(STAT_CODE, period, **CODE ):
ITEM_CODE = CODE['ITEM_CODE']
### 기간설정
if period == "A":
st_date = '1960'
end_date = '2022'
elif period == "M" or "Q":
st_date = '196001'
end_date = '202212'
else:
st_date = '19600101'
end_date = '20221231'
#api_key = ''
url = f"https://ecos.bok.or.kr/api/StatisticSearch/{api_key}/json/kr/1/100000/{STAT_CODE}/{period}/{st_date}/{end_date}/{ITEM_CODE[0]}/{ITEM_CODE[1]}/{ITEM_CODE[2]}/{ITEM_CODE[3]}"
response = requests.get(url)
data = response.json()['StatisticSearch']['row']
df = pd.DataFrame(data)[['TIME', 'DATA_VALUE']]
df['TIME'] = pd.to_datetime(df['TIME'], format='%Y%m')
df['DATA_VALUE'] = df['DATA_VALUE'].astype('float64')
df = df.set_index('TIME')
return df
ecos_요청데이터 concat
In [6]:
def ecos_datas(data_condition):
dfs = []
for key in data_condition.keys():
condition = data_condition[key]
df = ecos_data(condition[0], condition[1], ITEM_CODE = condition[2])
df.columns = [key]
dfs.append(df)
df = pd.concat(dfs, axis=1)
return df
데이터 수집¶
In [57]:
# 비교할 데이터 요청코드 입력
data_condition = {
"KOSPI" : ["901Y014", "M", ["1070000","?","?","?"]],
"예탁금" : ["901Y056", "M", ["S23A","?","?","?"]], ### 투자자 예탁금
"국고채3년" : ["902Y001", "M", ["1010701","?","?","?"]],
"LIBOR" : ["902Y001", "M", ["1030401","?","?","?"]],
"환율" : ["731Y004", "M", ["0000001","0000100","?","?"]],
"M1" : ["101Y019", "M", ["BBLA00","?","?","?"]],
"수입금액지수" : ["403Y003", "M", ["*AA","?","?","?"]],
"소비자물가지수" : ["901Y009", "M", ["0","?","?","?"]],
}
# 데이터 요청
df = ecos_datas(data_condition)
df
Out[57]:
| KOSPI | 예탁금 | 국고채3년 | LIBOR | 환율 | M1 | 수입금액지수 | 소비자물가지수 | |
|---|---|---|---|---|---|---|---|---|
| TIME | ||||||||
| 1964-05-01 | NaN | NaN | NaN | NaN | 255.77 | NaN | NaN | NaN |
| 1964-06-01 | NaN | NaN | NaN | NaN | 255.77 | NaN | NaN | NaN |
| 1964-07-01 | NaN | NaN | NaN | NaN | 255.77 | NaN | NaN | NaN |
| 1964-08-01 | NaN | NaN | NaN | NaN | 255.77 | NaN | NaN | NaN |
| 1964-09-01 | NaN | NaN | NaN | NaN | 255.77 | NaN | NaN | NaN |
| ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 2022-08-01 | 2472.05 | 53063280.0 | 3.685 | 3.09971 | 1318.44 | 1336447.0 | 184.16 | 108.62 |
| 2022-09-01 | 2155.49 | 50852276.0 | 4.186 | 3.75471 | 1391.59 | 1322918.4 | 170.26 | 108.93 |
| 2022-10-01 | 2293.61 | 48619094.0 | 4.185 | 4.46029 | 1426.66 | 1287865.7 | 165.06 | 109.21 |
| 2022-11-01 | 2472.53 | 46674550.0 | 3.689 | 4.77857 | 1364.10 | 1249905.7 | 164.45 | 109.10 |
| 2022-12-01 | 2236.40 | 46448436.0 | 3.722 | 4.76729 | 1296.22 | 1225205.6 | 166.41 | 109.28 |
704 rows × 8 columns
그래프¶
In [58]:
# 그래프 크기 설정
fig, ax = plt.subplots(figsize=(10, 6))
# 색상 리스트
colors = ['red', 'blue', 'green', 'purple']
# y축 라벨 리스트
labels = df.columns
# 그래프 그리기
for i, (col, label) in enumerate(zip(df.columns, labels)):
ax_i = ax.twinx()
ax_i.spines["right"].set_position(("axes", 1 + 0.1 * i))
color = np.random.rand(3)
df[col].plot(ax=ax_i, color=color)
ax_i.set_ylabel(label, color=color)
ax_i.tick_params(axis='y', labelcolor=color)
# x축 라벨
ax.set_xlabel('')
# 그래프 타이틀
plt.title('')
# 그리드 표시
plt.grid(True)
# 그래프 출력
plt.show()
#plt.legend()
elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
회귀분석¶
In [59]:
#deva = "dependent variable" 종속변수
deva = "KOSPI"
df = df.dropna()
osl(df, deva)
OLS Regression Results
==============================================================================
Dep. Variable: KOSPI R-squared: 0.949
Model: OLS Adj. R-squared: 0.947
Method: Least Squares F-statistic: 705.5
Date: Wed, 08 Mar 2023 Prob (F-statistic): 3.50e-168
Time: 13:08:34 Log-Likelihood: -1770.0
No. Observations: 275 AIC: 3556.
Df Residuals: 267 BIC: 3585.
Df Model: 7
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
const -1417.8457 325.190 -4.360 0.000 -2058.108 -777.584
예탁금 2.077e-05 2.37e-06 8.753 0.000 1.61e-05 2.54e-05
국고채3년 79.1189 18.330 4.316 0.000 43.028 115.210
LIBOR -27.7686 9.913 -2.801 0.005 -47.287 -8.250
환율 -1.7231 0.128 -13.481 0.000 -1.975 -1.471
M1 -0.0007 0.000 -3.941 0.000 -0.001 -0.000
수입금액지수 -1.9158 1.042 -1.838 0.067 -3.968 0.137
소비자물가지수 57.5475 4.633 12.421 0.000 48.426 66.669
==============================================================================
Omnibus: 5.484 Durbin-Watson: 0.405
Prob(Omnibus): 0.064 Jarque-Bera (JB): 7.120
Skew: 0.124 Prob(JB): 0.0284
Kurtosis: 3.748 Cond. No. 9.06e+08
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 9.06e+08. This might indicate that there are
strong multicollinearity or other numerical problems.
종속변수 시점 -1¶
In [60]:
#df[deva] = df[deva].shift(-1, freq='MS')
#df = df.dropna()
#osl(df, deva)
인공신경망¶
In [62]:
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# 스케일링
scaler = MinMaxScaler()
scaled_df = pd.DataFrame(scaler.fit_transform(df), columns=df.columns, index=df.index)
# 입력 데이터와 출력 데이터 분할
X = scaled_df.drop(deva, axis=1)
y = scaled_df[deva]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, shuffle=False)
# 인공신경망 모델 생성
model = Sequential()
model.add(Dense(10, input_dim=X.shape[1], activation='relu'))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
# 모델 학습
model.fit(X_train, y_train, epochs=100, batch_size=1, verbose=0)
# 테스트 데이터로 예측
y_pred = model.predict(X_test)
# A열의 스케일러 객체를 생성하고 fit_transform() 메서드를 호출합니다.
A_scaler = MinMaxScaler().fit(df[[deva]])
scaled_A = A_scaler.transform(df[[deva]])
# inverse_transform() 함수를 이용해 스케일링된 값을 이전 값으로 복원합니다.
restored_A = A_scaler.inverse_transform(scaled_A)
# 예측 결과 그래프로 출력
import matplotlib.pyplot as plt
plt.plot(y_test.index, A_scaler.inverse_transform(y_test.values.reshape(-1, 1)), label='actual')
plt.plot(y_test.index, A_scaler.inverse_transform(y_pred), label='predicted')
plt.legend()
plt.show()
3/3 [==============================] - 0s 2ms/step
In [ ]:
'주가예측' 카테고리의 다른 글
| VIX - NASDAQ상관관계 분석 (0) | 2023.03.07 |
|---|---|
| 한국거래소 전체지수 시세 - python requests (2) (0) | 2021.07.22 |
| 한국거래소 전체지수 시세 - python requests (1) (12) | 2021.07.22 |
| 주가 예측 (0) | 2021.07.22 |