algorithm trading simple - amazon s3 · an interview of traditional fund manager • nevsky...

48
Algorithm Trading Introduction DeepNumbers, 안명호 [email protected] 1

Upload: others

Post on 27-Dec-2019

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Algorithm Trading

Introduction

DeepNumbers, 안명호

[email protected]

1

Page 2: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Algorithm Trading?

Page 3: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

'수학 부호' 사이먼스 회장 "수학 즐기니 부 쌓여가”

3

사이먼스 회장은미국 하버드대수학과 교수에서 돌연월가에서

헤지펀드(르네상스테크놀로지) 회사창립자로 변신, 총 재산이13조원을 훌쩍

넘는 세계 88위의부호로 성공했다.

그의 회사는수학적 모델을 이용한계량분석 기법인 ‘퀀트펀드’를 통해지난

2000년대연이어 대박행진을이어갔다.

이데일리 2014.08.13, 이승현기자

Page 4: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

James Harris Simons

4

• Renaissance Technology 설립자

• MIT, UC 버클리 수학박사

• 전 하버드대수학교수

• 수학자 및 헤지펀드매니져

• 1976년베블런상 수상

• 2006년역대 최고 연봉

– 17억달러(2조원)

https://en.wikipedia.org/wiki/James_Harris_Simons

실제로 그를만나본 사람들은

'사이먼스는 돈이 중요한사람이라기보다는단순히 수학에 미친사람’

Page 5: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Algorithm Trading is …

5

• 알고리즘 트레이딩은 수학적 계산과 IT 시스템을 이용해 트레이딩을 하는 것으로 시스템 트레

이딩, Algo Trading 혹은 Blackbox 트레이딩

이라고한다.

• 알고리즘 트레이딩은 투자은행, 연기금, 헤지펀드, 증권회사등 많은 곳에서 사용되고 있으며,

최근 몇년사이에는 수학적지식과 IT지식을 가

진개인들도많이참여하고있다.

Page 6: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Algorithm Trading의 궁극적목표

6

적절한종목을선택하고매도와매수시기를알아내수익을실현하는것!!!

Page 7: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Algorithm Trading의 현재

7

미국은 2012년 알고리즘 트레이딩 거래량이 85%에달할만큼 알고리즘 트레이딩은 가파르게 증가

Page 8: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Human VS Machine - Result

• Goove WM, Zald DH등이 작성한 Clinical

versus Mechanical Prediction: a meta-

analysis 논문에 의하면 136건의 사례를

조사해보니 수학적 모델이 사람보다 비슷하거나

더 좋은 결과를 가져올 확률이 94%라고 한다.

8

(source- http://www.ncbi.nlm.nih.gov/pubmed/10752360)

Page 9: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

An Interview of traditional fund manager

• Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long period of success, partly blaming “black box algorithmic funds” for making markets harder to navigate for old-fashioned investors.

• Common lament among fund managers

Martin Taylor, Nevsky Captital

Source- http://www.ft.com/cms/s/0/5eb91614-bee5-11e5-846f-79b0e3d20eaf.html#axzz4C07WwHSs

Page 10: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Algorithm Trading 장단점

10

장점 단점

• 과학적 접근 : 데이터에 기반해 과학적으로 투자전략을 검증하고개발한다.

• 무감정 : 수학적 모델에 기반해 결정해 투자의 큰 장애물인 감정이개입할 여지가 없다.

• 속도 : 알고리즘트레이딩이 사람보다 비교할 수 없을정도로 빠른속도를 자랑한다.

• 유동성 : 잦은 거래에 의한 시장 유동성 확대로 시장의 교란이 잦다.

• 경쟁력 :미국의 경우 알고리즘 트레이딩의 일반화로잘 알려진 전략의경우 효과가 적다.

• 에러 : 수학적 모델의 에러 혹은 프로그램 오류로 인한 손실이 발생할수 있다.

Page 11: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Algorithm Trading 모델 종류

11

Theory Driven Data Driven

Top-down Bottom-up

TheoryDrivenApproach를많이적용함

Page 12: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Renaissance Technologies

• Renaissance is one of the first highly

successful hedge funds using quantitative

trading — known as "quant hedge funds" — that

rely on powerful computers and sophisticated

mathematics to guide investment strategies.

• Medallion Fund : From 1994 through mid-2014 it

averaged a 71.8% annual return before fee

Hedge Fund Rank 12

AUM : 65B$

Top-Performing Hedge Funds

Page 13: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

TwoSigma Investment

Machine Learning, Distributed Computing

Hedge Fund Rank 11

AUM : 35B$

Page 14: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Edward Thorp – 1세대

14

• Edward Throp는 알고리즘 트레이딩의 1세대로 월스트리트에서 최초로 수학을이용해 펀드를운영하였다.

• MIT 수학과 교수출신으로 Princeton-Newport Partners라는투자를 설립했고 1970년부터 1998년 청산하기 까지 연평균 2

0%라는놀라운 수익을 보여주었다.

• 주식에 조금이라도 관심있는 사람이라면 누구나 아는 워렌 버핏의 연평균수익율이 21.6%이고, 같은 기간 S&P500의 연평

균수익율이 8.84%라는 것을 감안해보면 소프가 보여준 수익

율이 얼마나대단한 것인지를 알수 있을 것이다.

Page 15: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Edward Thorp

15

21, MIT 천재들의라스베가스 무너뜨리기

UCLA 물리학과대학원시절에동료들과 돈을 쉽게 버는 방법에 대해 이야기하던중 영감

을받아카지노 룰렛에서 공이어디에 멈출지를 예측할수 있는 최초라고얘기되는 웨어

러블 장치를고안하기도 했다.

특히 카드게임인블랙잭은 소프의인생에 있어중요한 부분을차지한다고 할수 있다.

소프는 “부의 공식 :블랙잭 승리 전략” 이라는 제목의 논문을 발표했는데 블랙잭 게임을

수학적으로분석해딜러를 이길수있는 방법을설명한 것으로미국전역의 도박사들로부

터 엄청난인기를 얻었다.

소프가 제시한 방법은 딜러 데크의 상황에 따른 확률을 계산하는 것으로 흔히 카드카운

팅로 알려진 것이다. 소프는 이 방법을 소개하는데 그치지 않고 직접 라스베가스로 가

서 많은 돈을 벌었다고 하니 케빈스페이시가 출연한 2008년 개봉 영화 “21”의 실사판

이라 할수 있다.

Page 16: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

James Harris Simons - 2세대

16

르네사스테크놀로지는 자사의 운용방식이나 적용모델등을 외부에

공개하지 않기로 유명한 회사로 직원을 채용할 때, 르네사스테크놀

로지에서 얻은 내용들은 일정기간동안 외부에 공개하지 않는 비밀

서약을 맺는다고한다.

그래서 르네사스 테크놀로지에서 어떤 모델을 이용해 알고리즘 트

레이딩을 하는지는 자세히 알려져있지 않지만, Trend Following에

기반한 모델을적극적으로 사용하는것으로 알려져있다.

Trend Following은 어떠한 긴 흐름의 추세가 시작되면 이를 파악

해 상승흐름에올라탈 수있다는 이론에기반한다.

Trend Following은 오랜 역사를 가진 모델로 수학적 이론이 잘 정

립되어 있고, 이해하기도 쉬워, 시장에서 널리 사용되는 것중의 하

나로 세계에서가장 큰선물거래기관에서 적용하고있다.

Page 17: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Kenneth C. Griffin – 3세대

17

소프, 사이먼과 달리 그리핀은 하버드경제학과 출신이며, 현역으로 활발히 활동

하고 있는헤지펀드 매니져이다.

2014년 포브스 미국 400대 부호 가운데 69위에 랭크되었고 자산은 70억달러

로 추정된다.

어려서부터 컴퓨터 프로그래밍에 능했던 그리핀은 하버드대학 재학시절 소프가

저술한 책인 “Beat the market”이라는 책을 읽고 전환사채에 대한 아이디어를

얻고 “컨버터블헤지펀드넘버원”이라는합자회사를 시작했다.

그리핀은거의모든 금융기관과투자가들이 엄청한손실을 봤던 1987년 10월 1

9일, 블랙먼데이에하버드 대학교 기숙사에서 펀드를 운영하며 수익을올리면서

월스트리트에서 유명세를타기 시작했다.

그리고 1990년에대학교를 졸업하며 Citadel이라는헤지펀드를 설립했다.

시타델은 가장 성공적인 헤지펀드라는 평가를 받고 있으며 2015년 기준으로 2

5조달러의자금을 운영하고있는 세계최대의 헤지펀드중의하나이다.

Page 18: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Machine Learning?

Page 19: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Machine Learning?

• 머신 러닝(영어: machine learning) 또는 기계 학습(機械學習)은 인공 지능의 한 분야로,

컴퓨터가 학습할 수 있도록 하는 알고리즘과 기술을 개발하는 분야를 말한다. 가령, 기계 학습을

통해서 수신한 이메일이 스팸인지 아닌지를 구분할 수 있도록 훈련할 수 있다.

• 기계 학습의 핵심은 표현(representation)과 일반화(generalization)에 있다. 표현이란

데이터의 평가이며, 일반화란 아직 알 수 없는 데이터에 대한 처리이다. 이는 전산 학습

이론 분야이기도 하다. 다양한 기계 학습의 응용이 존재한다. 문자 인식은 이를 이용한 가장 잘

알려진 사례이다.

FromWIKI

MachineLearningCrashCoursebyMHR 19

Page 20: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Machine Learning Concept

MachineLearningCrashCoursebyMHR 20

ProgramInput Output

Traditional Approach

OutputInput Program

Machine Learning Approach

Page 21: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Essense of Machine Learning

MachineLearningCrashCoursebyMHR 21

y = f(x)

• Training: given a training set of labeled examples {(x1,y1), …, (xN,yN)}, estimate the prediction function f by minimizing the prediction error on the training set

• Testing: apply f to a never before seen test example x and output the predicted value y = f(x)

output prediction function

feature

Page 22: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Regression

MachineLearningCrashCoursebyMHR 22

predictor variable x,y = w0 + w1x

TrainingDataSet

Page 23: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Finding Parameter is What ML does

MachineLearningCrashCoursebyMHR 23

Page 24: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

What Machine Learning can do

MachineLearningCrashCoursebyMHR 24

Clustering Regression Classification

SupervisedLearningUnsupervisedLearning

Page 25: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Overfitting & Underfitting

MachineLearningCrashCoursebyMHR 25

Page 26: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Tutorial Dev Environment

MachineLearningCrashCoursebyMHR 26

Page 27: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

개발환경

• 하드웨어• Intel i5 이상, 메모리 4GB, HDD 256GB 이상• 되도록이면 i7에서 제일 빠른 CPU 사용

• OS• 파이썬을 사용할 수 있는 환경(Windows, OS X, Linux)• Linux를 강력추천

• Database• MySQL, 주가 관련 데이터 저장용이다.

• 프로그래밍 언어• 파이썬, 파이썬은 강력한 언어로 웹 개발, 클라우드, 금융에 이르기까지 폭넓게사용되고 있다. 언어가 간결하고 배우기 쉬우며 다양한 라이브러리를 가지고있다.

MachineLearningCrashCoursebyMHR 27

Page 28: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Machine Learning Library

• NumPy• 고차원의 수학적 기능을제공하는 오픈소스 파이썬 라이브러리다. NumPy의 핵심 기능은 ndarray인데, 이는 n 차원의배열 데이터 클래스로다차원배열을 유연하면서도 빠른 속도로사용할 수 있다. NumPy는 각종 수학과 과학연산에서많이 사용되는 벡터나스칼라로 활용할 수 있고, 데이터베이스와 연동해 사용할 수도있다.

• SCIPY• 과학 연산에 필요한기능을 제공하는 라이브러리로, 최적화, 선형대수, 적분, FFT 등의 기능을 제공한다.

• Pandas• 금융데이터 처리용 라이브러리로, DataFrame 클래스를이용해 시계열 금융데이터 처리에필요한 각종 기능이 있다.

• Matplotlib• 그래프를 그리거나 데이터를시각화하는 데 필요한 풍부한기능을 가지고 있는 라이브러리다. 그래프를 저장하거나 확대 또는 축소를위한 간단한 UI도 제공한다.

• Sklearn• 파이썬 머신러닝 라이브러리로, 딥러닝을 제외한 현존하는 거의모든 머신러닝 알고리즘이 구현되어있고 데이터 처리와 머신러닝 학습결과를분석하는 기능들도 포함되어 있다. 알고리즘과 관계없이 사용법이 일관돼짧은 학습시간에 직관적으로 이용할 수있는 파이썬의 대표적인 머신러닝라이브러리이다.

• Statsmodels• 파이썬 통계 라이브러리로데이터 탐색, 통계적 모델추정, 통계 테스트 등 다양한통계 관련 기능을 지원한다.

MachineLearningCrashCoursebyMHR 28

Page 29: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

SCIKIT - Learn

• Python Machine Learning Library• Deep Learning은지원하지 않음

• Used in many areas• 학계, 산업계등 다양한 분야에서 폭넓게 활용

• Wide Coverage• 상당히 많은 수의 Machine Learning 알고리즘 지원• Machine Learning 알고리즘뿐만 아니라 Data Processing등연관된 거의 모든 기능을지원함

• Developer Friendly• 개발자가 사용하기 쉬운 라이브러리

• Consistency in Usage• 알고리즘에 상관없이 거의 일관된 사용법으로 Machine Learning 활용가능

MachineLearningCrashCoursebyMHR 29

Page 30: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Pandas

• Python Data Analysis Library

• Originally from Hedge Fund Developer

• Wes McKinney

• Many Functions for Finance Industry

• Support DBMS, Excel, CSV

• SQL을 사용해 데이터처리 가능

• Time Series Analysis

• Moving Average, ARIMA…

MachineLearningCrashCoursebyMHR 30

Page 31: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Pandas - Plot

MachineLearningCrashCoursebyMHR 31

In [6]: df['Min wage']['2010-01-01':].plot()

Out[6]: <matplotlib.axes._subplots.AxesSubplot at 0x108705208>

In [7]: import matplotlib.pyplot as plt

In [8]: plt.show()

Page 32: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

실습 – Machine Learning 개발환경설정

• Anaconda를 이용해 각자의 환경에 맞는

Python과 라이브러리를 설치하세요.

MachineLearningCrashCoursebyMHR 32

https://www.continuum.io/downloads

Page 33: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Library Installation

MachineLearningCrashCoursebyMHR 33

https://www.continuum.io/downloads에서

Anaconda를이용한필요 라이브러리 설치

Windows, OSX, Linux 모두 지원함

설치프로그램을다운받아서 실행해주면설치 완료

Page 34: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

설치확인

MachineLearningCrashCoursebyMHR 34

Python test_installation.py

Page 35: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

실습 - 종목코드및 주가 데이터 다운로드

MachineLearningCrashCoursebyMHR 35

Pandas를 이용해주가데이터를

다운로드하고파일로저장한다.

Page 36: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Pandas - Download Data

defdownload_stock_data(file_name,company_code,year1,month1,date1,year2,month2,date2):

start = datetime.datetime(year1, month1, date1)end = datetime.datetime(year2, month2, date2)df = web.DataReader("%s.KS" % (company_code), "yahoo", start, end)df.to_pickle(file_name)return df

download_stock_data('samsung_2010.data','005930',2010,1,1,2015,11,30)

download_stock_data('hanmi.data','128940',2015,1,1,2015,11,30)

MachineLearningCrashCoursebyMHR 36

Google, Yahoo 등에서제공하는데이터를받아올수있음

Page 37: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Download KOSPI Data

MachineLearningCrashCoursebyMHR 37

def download_whole_stock_data(market_type,year1,month1,date1,year2,month2,date2):df_code =read_stock_code_from_xls('stock_code.xls')forindexinrange(df_code.shape[0]):

stock_code =df_code.loc[index,df_code.columns[0]]name=df_code.loc[index,df_code.columns[1]]market=df_code.loc[index,df_code.columns[2]]ifmarket_type.upper()=='KOSPI':

print"...downloading %sof%s:code=%s,name=%s"%(index+1,df_code.shape[0],stock_code,name)

download_stock_data('%s.data'%(stock_code),stock_code,year1,month1,date1,year2,month2,date2)

Data_loader.py참조

Page 38: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Simple Tutorial

Page 39: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

실습 - 주가예측

• SVR을이용해서주가를 예측ML 프로그램 개발

• SVR 정보는아래 링크참조

• http://scikit-

learn.org/stable/modules/generated/sklearn.svm.SVR.html

• Data는실습시간에 사용했던함수를 이용해서다운로드

• Pandas 이용

• Print DataFrame.columns를실행하면데이터의컬럼정보 확인가능

• Input, Output Variable

MachineLearningCrashCoursebyMHR 39

Page 40: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Pandas – Data Structure

MachineLearningCrashCoursebyMHR 40

• Series• 1차원: index를 사용하여 참조

• DataFrame• 2차원: index, columns• 스프레드 시트, SQL 테이블

• Panel• 3차원

• items: axis 0• major_axis: axis 1• minor_axis: axis 2

• Panel4D, PanelND (실험 중)http://pandas.pydata.org/pandas-docs/stable/dsintro.html 참조

Dataframe

Page 41: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Pandas - Dataframe

MachineLearningCrashCoursebyMHR 41

In [1]: import pandas as pd

In [2]: file = "https://raw.githubusercontent.com/sk8erchoi/csv-files/master/college_reg_fee_2015.csv"

In [3]: df = pd.read_csv(file)

In [4]: df[['Name', 'Avg']][:3]Out[4]:

Name Avg0 ICT폴리텍대학 22001 가톨릭상지대학교 55042 강동대학교 5725

In [5]: df[['Name', 'Avg']].sort(['Avg'], ascending=False).head(3)Out[5]:

Name Avg72 서울예술대학교 810118 계원예술대학교 756461 백제예술대학교 7486

Page 42: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Data Preparation

def load_stock_data(file_name):df = pd.read_pickle(file_name).dropna(how='any')return df.reset_index(drop=True)

MachineLearningCrashCoursebyMHR 42

Simply Remove NAN

Page 43: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Preprocessing

def doPreProcessing(dataset,column_name,threshold=3):df_revised = dataset[ dataset[column_name]>0 ]return df_revised[((df_revised[column_name] -

df_revised[column_name].mean()) / df_revised[column_name].std()).abs() < threshold]

MachineLearningCrashCoursebyMHR 43

Remove Outliers

Page 44: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Outlier

MachineLearningCrashCoursebyMHR 44

이상치(Outlier)는특정데이터변수의분포에서비정상적으로벗어난값

Page 45: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Training

def prepareDataset(dataset,split_ratio=0.75):

split_index = math.trunc(dataset.shape[0] * 0.75)

input_column_array = ['Open','Low','Close','Volume']

output_column = ['High']

input_data = dataset[input_column_array]

output_data = dataset[output_column]

# Create training and test sets

X_train = input_data[0:split_index]

Y_train = output_data[0:split_index]

X_test = input_data[split_index+1:input_data.shape[0]-1]

Y_test = output_data[split_index+1:input_data.shape[0]-1]

return X_train,np.ravel(Y_train),X_test,np.ravel(Y_test)

def createSVRModel():

regr = SVR(C=1.0, epsilon=0.2, kernel='rbf')

return regr

MachineLearningCrashCoursebyMHR 45

Page 46: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

Evaluation

def plotTrainingResult(model,test_x,test_y):# Plot outputspred_y = model.predict(test_x)plt.plot(pred_y, color='blue',

linewidth=3)plt.plot(test_y, color='red', linewidth=3)plt.show()

MachineLearningCrashCoursebyMHR 46

Page 47: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

실습 – RandomForest Regressor를 이용한 주가 예측

MachineLearningCrashCoursebyMHR 47

• RandomForest Regressor을이용해서 주가를

예측 ML 프로그램 개발

• RFR 정보는 아래 링크참조

• http://scikit-

learn.org/stable/modules/generated/skl

earn.ensemble.RandomForestRegressor.

html

• 앞의 예제를 수정해서 사용

Page 48: Algorithm Trading Simple - Amazon S3 · An Interview of traditional fund manager • Nevsky Capital, a $1.5bn hedge fund, earlier this month decided to call it quits after a long

48

감사합니다.