나만의 로보 어드바이저(robo-advisor) 만들기 [5]

금융 2016. 9. 23. 16:23

 

 

 

 

오늘은 Python과 CybosPlus를 이용하여 장중 실시간 종목 가격 변동을 모니터링하고 특정 조건(매수 혹은 매도가 도달)만족시 이벤트를 생성하는 방법을 알아보자. 

 

먼저 첨부된 python 코드는, 깔끔하지는 않지만, 장중 정해준 종목을 계속 모니터링하다가 정해진 이벤트(트레이딩)이 발생할 경우 발생한 트레이딩 정보와 변동률을 화면에 뿌려주는 기능을 한다. 

이 코드를 조금 수정하면 이벤트가 발생한 경우에 사용자 펑션 호출하여 원하는 조건(매수 혹은 매도 조건 도달, 특정 가격이상 변동, 급작스런 가격변동 탐지등)을 만족하는가를 체크하고 만족하는 경우 특정 행동을 하도록 할 수 있을것이다.

 

특정 조건 만족시 매수, 혹은 매도를 실행하는 코드를 추가하면 실시간 트레이딩이 가능해지는데 이 부분은 다음 시간에 다루기로 한다.

 

 

 

코드 설명:

 

 

 

 

 

__author__ = 'Dr. Deeeep'

import win32com.client

import io

 

 

""" Memo

02: change rate

13: currentprice

18: currenttime

"""

activeFlag = [        1,        1,        0,       0,       0,       0,      0]

itemcode =   ['A017680','A052790','A032860', 'A900110', 'A033130']

############### deco, actoz, steel, EAH, cho

crArray =    [       '',       '',       '',      '',      '',  '']

 

class CpEvent0:

    #print("E0: flag=", activeFlag[0])

    instance = None

    def OnReceived(self):

        #print("E0: flag=", activeFlag[0])

        if (activeFlag[0]>0):

            currentprice = CpEvent0.instance.GetHeaderValue(13)

            changeprice = CpEvent0.instance.GetHeaderValue(2)

            changerate = round(((changeprice / (currentprice - changeprice)) * 100.0),2)

            crArray[0] = changerate

            prt_style_all(0, changerate, currentprice, changeprice)

            #prt_style(0, changerate, currentprice, changeprice)

            #print(itemcode[0], " ", changerate, "         E0: ", currentprice, "  ", changeprice);  

        

class CpEvent1:

    #print("E1: flag=", activeFlag[1])

    instance = None

    def OnReceived(self):

        #print("E1: flag=", activeFlag[1])

        if (activeFlag[1]>0):

            currentprice = CpEvent1.instance.GetHeaderValue(13)

            changeprice = CpEvent1.instance.GetHeaderValue(2)

            changerate = round(((changeprice / (currentprice - changeprice)) * 100.0),2)

            crArray[1] = changerate

            prt_style_all(1, changerate, currentprice, changeprice)

            #prt_style(1, changerate, currentprice, changeprice)

            #print(itemcode[1], "      ", changerate, "     E1: ", currentprice, "  ", changeprice);  

        

class CpEvent2:

    #print("E2: flag=", activeFlag[2])

    instance = None

    def OnReceived(self):

        #print("E2: flag=", activeFlag[2])

        if (activeFlag[2]>0):

            currentprice = CpEvent2.instance.GetHeaderValue(13)

            changeprice = CpEvent2.instance.GetHeaderValue(2)

            changerate = round(((changeprice / (currentprice - changeprice)) * 100.0),2)

            crArray[2] = changerate

            prt_style_all(2, changerate, currentprice, changeprice)

            #prt_style(2, changerate, currentprice, changeprice)

            #print(itemcode[2], "          ", changerate, " E2: ", currentprice, "  ", changeprice);  

 

class CpEvent3:

    #print("E3: flag=", activeFlag[3])

    instance = None

    def OnReceived(self):

        #print("E3: flag=", activeFlag[3])

        if (activeFlag[3]>0):

            currentprice = CpEvent3.instance.GetHeaderValue(13)

            changeprice = CpEvent3.instance.GetHeaderValue(2)

            changerate = round(((changeprice / (currentprice - changeprice)) * 100.0),2)

            crArray[3] = changerate

            prt_style_all(3, changerate, currentprice, changeprice)

            #prt_style(3, changerate, currentprice, changeprice)

            #print(itemcode[3], "          ", changerate, " E3: ", currentprice, "  ", changeprice);  

 

class CpEvent4:

    #print("E4: flag=", activeFlag[4])

    instance = None

    def OnReceived(self):

        #print("E4: flag=", activeFlag[4])

        if (activeFlag[4]>0):

            currentprice = CpEvent4.instance.GetHeaderValue(13)

            changeprice = CpEvent4.instance.GetHeaderValue(2)

            changerate = round(((changeprice / (currentprice - changeprice)) * 100.0),2)

            crArray[4] = changerate

            prt_style_all(4, changerate, currentprice, changeprice)

            #prt_style(4, changerate, currentprice, changeprice)

            #print(itemcode[4], "          ", changerate, " E4: ", currentprice, "  ", changeprice);  

 

def prt_style_all(classnum, chrate, curprice, chprice):

    print(classnum, ", ", enter_crArray(), curprice, ",", chprice)

 

def prt_style(classnum, chrate, curprice, chprice):

    print(classnum, enter_spc(classnum), chrate, ",", exit_spc(classnum), ",", curprice, ",", chprice)

    #print(itemcode[classnum], enter_spc(classnum), chrate, ", ", curprice, ", ", chprice)

 

def enter_crArray():

    crnum = len(crArray)

    rtnline = ""

    for n in range(0, crnum):

        rtnline = rtnline + str(crArray[n]) + ","

    return rtnline

    

def enter_spc(classn):

    spc = ""

    for n in range(0, classn):

        spc = spc + "     "

    return spc

 

def exit_spc(classn):

    spc = ""

    rev = 4 - classn

    for n in range(0, rev):

        spc = spc + "     "

    return spc

 

#not working

def sprintf(buf, fmt, args):

    buf.write(fmt % args)

 

    

inst0 = win32com.client.Dispatch("dscbo1.StockCur")

inst1 = win32com.client.Dispatch("dscbo1.StockCur")

inst2 = win32com.client.Dispatch("dscbo1.StockCur")

inst3 = win32com.client.Dispatch("dscbo1.StockCur")

inst4 = win32com.client.Dispatch("dscbo1.StockCur")

 

win32com.client.WithEvents(inst0, CpEvent0)

win32com.client.WithEvents(inst1, CpEvent1)

win32com.client.WithEvents(inst2, CpEvent2)

win32com.client.WithEvents(inst3, CpEvent3)

win32com.client.WithEvents(inst4, CpEvent4)

 

inst0.SetInputValue(0,itemcode[0])

inst1.SetInputValue(0,itemcode[1])

inst2.SetInputValue(0,itemcode[2])

inst3.SetInputValue(0,itemcode[3])

inst4.SetInputValue(0,itemcode[4])

 

CpEvent0.instance = inst0

CpEvent1.instance = inst1

CpEvent2.instance = inst2

CpEvent3.instance = inst3

CpEvent4.instance = inst4

 

inst0.Subscribe()

inst1.Subscribe()

inst2.Subscribe()

inst3.Subscribe()

inst4.Subscribe()

 

 

 

이벤트 발생시 해당 종목의 가격을 체크하여 정해진 STOPLOSS 보다 작거나 STOPGAIN보다 큰 경우 적절한 행동을 하도록 하려면 다음과 같은 class를 정해주면 된다.  

 

 

class CpEvent000:

    instance = None

    monitoring = 1  # 0 no, 1 yes

    def OnReceived(self):

        if (monitoring = 1)

            value13_cprice = CpEvent1.instance.GetHeaderValue(13)

            value18_ctime = CpEvent1.instance.GetHeaderValue(18)

            print("E1: ",value18_ctime,", ", value13_cprice)

            if (value13_cprice >= stopgain_price)

                print("E1: STOPGAIN, Exit")

                monitoring = 0 # 정해진 일을 이곳에 코딩

            elif (value13_cprice <= stoploss_price)

                print("E1: STOPLOASS, Exit")

                monitoring = 0  # 정해진 일을 이곳에 코딩

 

 

<to be continued..>

 

 

 

posted by Dr.Deeeep

딥러닝 for 트레이딩

금융 2016. 8. 18. 02:38

트래이딩분야에 적용된 딥러닝 기술

 

그 동안 개인적으로 테스트해 본 트래이딩에서의 딥러닝 알고리즘은 그닥 효과가 좋지 못하다. 트래이딩 알고리즘의 시뮬레이션을 위해 구축한 웹페이지 (http://www.bigdata-trader.com/simulation_preview.jsp?month=00000000)에서 확인할 수도 있는데, 딥러닝 모델(현재 A26부터 A30까지 5개 모델이 딥러닝 모델, 나머지는 전통적 트레이딩 알고리즘)의 단타 매매 성공율은 겨우 60퍼센트 정도에 미치고 있다. 물론 딥러닝 모델은 아직 2개월 정도밖에 운영하지 않았지만 몇 년을 돌려도 크게 바뀔거 같지는 않다. 이 정도의 performance는 전통적 방법의 트래이딩 알고리즘(예를 들면 A14나 A4)보다도 훨씬 뒤쳐지는 성적이다.

 

 

 

참고로 각 알고리즘은 DBN을 이용하여 72개월간 다음 데이터를 학습한며, 매일 10거래일 전 발행한 추천 종목의 성적을 평가한다.

A26: 주가

A27: 주가+인덱스

A28: 주가변동률+인덱스변동률

A29: 주가변동률+거래량+외인거래량

A30: 주가변동률+거래량+외인거래량+외인보유portion

 

다양한 딥러닝 아키텍춰를 추가해서 LSTM 등을 이용할 계획이긴 하지만 크게 향상될것 같지는 않다. 아키텍춰보다는 데이터나 모델을 바꿔야 할듯.

 

USC의 Greg Harris 가 트래이딩 분야에 적용된 딥러닝 기술을 잘 정리를 해둔것을 발견하여 정리해본다. 원문은 http://gregharris.info/a-survey-of-deep-learning-techniques-applied-to-trading/

 

(요약 할것)

1. Limit order book modeling

 

2. price-based classification models

 

3. Text-based Classification models

 

4. Volatility Prediction

 

5. Portfolio Optimization

 

각 모델별로 아키텍춰를 달리한 논문들을 소개하고 있는데 내 시스템에 적용 가능한것부터 하나하나 테스트 해볼 생각이다.

 

========== continued..

 

일단 위에 열거된 다른 연구자들의 결과를 보고 놀라운 점은 수익 성공률이 53% 정도 밖에 안된다는 것. 내가 구현한 딥러닝 모델보다도 조금 더 나쁘고 A4나 A14보다도 훨씬 안좋다. 하지만 위 요약을 읽으면서 몇가지 새로운 모델에 대한 구상이 떠올라서 구현해보기로 한다.

 

1. 먼저 리턴(closing price - opening price)이라는 개념. 나의 예측 모델들은 모두 regression problem에 집중한데 반해 리턴이란 개념으로 접근한다면 classification 문제가 된다. + 일것이냐 - 일것이냐의 classification. 사실 class 수를 더 늘려서 regression 처럼 학습할 수 있지만. 어쩄든. 그게 중한게 아니고. return을 계산하기 위해서는 opening price 를 알아야 하는데. 이런식으로 하려면 실시간 시스템이어야 한다. 종가 확인 후 하루 한번 예측을 수행하는 일(daily) 베이스의 bigdata trader 시스템에서는 적용할 수 없다. opening price를 무시한다면 성공률이 50%로 수렴할 것이 뻔하다. 서비스 용도말고 관리자창에 테스트 용도로 장중 opening price를 입력 받아 return을 얻어내는 실험 모듈을 추가해야겠다.

  - 조금 더 생각해보니 "종목 상세 보기"에서는 사용자 입력 후 해당 종목에 한 해 실시간 장중가를 가져 올 수 있으니 그날의 리턴을 계산할 수도 있겠다.

 

2. Text 기반 classification

경제면 headline 들과 개별 종목 등락을 학습한다는 개념. 말그대로 bigdata trader의 기본 개념인데... sns 대신 경제면 headline 을 학습한다는 것.

 

3. moving box learning

DBN 을 써서 oscillating box를 학습 한다는 것인데. 학습이고 뭐고를 떠나 이 전략은 전략 자체의 validation 이 필요하다고 본다. 박스 바닥 뚫고 진입시 매수, 박스 바닥 뚫고 진출수 매도. 그러나 박스권의 설정 자체가 이미 후행적이고 결과론 적이다. oscillating box 이론이 잘 맞는 종목도 있을테니 선택적으로 적용한다면 시도해볼만 하다. 각 종목이 얼마나 oscillating box 이론에 일치하는가 평가하는 모듈이 먼저 필요하다.

 

(임시저장)

 

 

 

 

 

 

 

posted by Dr.Deeeep