Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Python
- 주식
- TimeSeries
- 파이썬
- 백테스트
- 빅데이터분석기사
- lstm
- 비트코인
- 파이썬 주식
- backtest
- 변동성돌파전략
- 실기
- PolynomialFeatures
- 데이터분석
- docker
- 프로그래머스
- 볼린저밴드
- Programmers
- ADP
- Quant
- SQL
- Crawling
- hackerrank
- sarima
- 코딩테스트
- GridSearchCV
- randomforest
- 토익스피킹
- 데이터분석전문가
- 파트5
Archives
- Today
- Total
데이터 공부를 기록하는 공간
백테스트 - MLP 일봉 4년데이터 본문
결과 ) 안좋음
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%%time
import pyupbit
df = pyupbit.get_ohlcv("KRW-BTC","day", count=24*30*24)
data = df.copy()
data['return'] = np.log(data['close']/data['close'].shift(1))
data.dropna(inplace=True)
data['direction'] = np.where(data['return']>0, 1, 0)
lags = 5
cols = []
for lag in range(1, lags+1):
col = "lag_{}".format(lag)
data[col] = data['return'].shift(lag)
cols.append(col)
for lag in range(1, lags+1):
col = "volumeR_{}".format(lag)
data[col] = data['volume'].shift(lag)
cols.append(col)
data.dropna(inplace=True)
data['momentum'] = data['return'].rolling(5).mean().shift(1)
data['volatility'] = data['return'].rolling(20).std().shift(1)
data['distance'] = (data['close']-data['close'].rolling(50).mean()).shift(1)
data.dropna(inplace=True)
cols.extend(['momentum','volatility','distance'])
cutoff = '2021-11-01'
training_data = data[data.index<cutoff].copy()
mu, std = training_data.mean(), training_data.std()
training_data_ = (training_data-mu)/std
test_data = data[data.index>=cutoff].copy()
test_data_ = (test_data-mu)/std
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
#from keras.optimizers import Adam, RMSprop
#(오류해결) https://exerror.com/importerror-cannot-import-name-adam-from-keras-optimizers-error/
from tensorflow.keras.optimizers import Adam
from keras.metrics import Precision
optimizer = Adam(learning_rate=0.0001)
def set_seeds(seed=100):
#random.seed(seed)
np.random.seed(100)
tf.random.set_seed(100)
set_seeds()
model = Sequential()
model.add(Dense(32, activation='relu',
input_shape=(len(cols),)))
#model.add(Dropout(0.2))
model.add(Dense(32, activation='relu'))
#model.add(Dropout(0.2))
model.add(Dense(32, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer=optimizer,
loss='binary_crossentropy',
metrics=['Precision'])
%%time
model.fit(training_data_[cols], training_data['direction'],
epochs=20, verbose=False,
validation_split=0.2, shuffle=False)
res = pd.DataFrame(model.history.history)
res[['precision','val_precision']].plot(figsize=(10,6), style='--')
cutoff_value = 0.5
pred = np.where(model.predict(training_data_[cols])>cutoff_value, 1,0)
training_data['prediction'] = np.where(pred > 0, 1, 0)
training_data['strategy'] = (training_data['prediction']*
training_data['return'])
training_data[['return','strategy']].sum().apply(np.exp)
training_data[['return','strategy']].cumsum().apply(np.exp).plot(figsize=(10,6))
cutoff_value = 0.5
pred_test = np.where(model.predict(test_data_[cols])>cutoff_value, 1,0)
test_data['prediction'] = np.where(pred_test > 0, 1, 0)
test_data['strategy'] = (test_data['prediction']*
test_data['return'])
test_data[['return','strategy']].sum().apply(np.exp)
test_data[['return','strategy']].cumsum().apply(np.exp).plot(figsize=(10,6))
▷ test 데이터에 대해서 좋지 않은 결과가 나온다.
epoch=100으로 하는 경우, train은 1600배의 수익률이 나오기도 한다 하지만 train이 중요한게 아니니..
---
1. 거래량, MACD, RSI, 볼린저밴드
'STOCK > 비트코인' 카테고리의 다른 글
볼린저밴드-추세추종 (실전 테스트) (0) | 2022.01.11 |
---|---|
볼린저밴드-추세추종 (0) | 2022.01.10 |
백테스트 - SMA 1시간봉 (0) | 2022.01.03 |
백테스트 - MLP 5분봉 volume 변수추가 (0) | 2022.01.03 |
백테스트 - MLP 5분봉 (0) | 2022.01.03 |
Comments