영화 아카이브 2020

영화리뷰 2020. 8. 2. 16:19

 

아내 버전3

요즘은 어쩌다 보니 테마를 정해서 영화를 많이 보게되었다. 코로나 때문인가? 한동안 전쟁 테마로 영화들을 보고, 그 다음은 또 연쇄살인마 주제의 영화들을 보았는데, 오늘 우연히 이 영화가 올라가 있길래 받아 보았다. 역시 SF, 특히 인공지능, 쪽 주제는 다른 모든 주제를 능가해서 내 흥미를 끈다. 

인디영화인듯 한데 내용이 나쁘지는 않다. 인공지능을 연구하는 사람들이라면 한번쯤 고민해보던 문제를 재미있게 영화화 하였다. 나름 반전도 있는데 괜한 반전이라고나 할까? 영화에 대한 좋은 여운이 망친게 아닌가 개인적으로 생각한다. 우리가 인공지능의 미래에 대해 고민해 볼 좋은 소재였는데 반전때문에 좀 주제가 산만해진게 아닌가 싶다. 

영화 '아카이브'는 비슷한 영화의 시초라 볼 수 있는 애니메이션 '공각기동대'와 같이, 은하철도 999인가?, 컴퓨터안에 인간의 영혼을 담아 몸은 죽어도 정신은 계속 살아있도록 한다는 개념인데 엄밀하게 따지면 아카이브와 공각기동대는 많이 다르다. 아카이브는 인간의 살아 생전의 모습, 목소리, 대화내용, 글, 생각등의 콘텐츠를 말 그대로 컴퓨터내에 '아카이빙'하여 이 컨텐츠에 기반하여 인물의 영혼을 모사한다는 개념으로, 양자(?) 영역의 인간 두뇌를 구성하는 방대한 정보를 그대로 카피하여 기계안에 복제한다는 '공각기동대'의 개념에 비하면 훨씬 하등한 개념이다. '아카이브'에 대한 연구는 이미 어느정도 실용화 되고 있다. 예를 들어 이미 사망한 마이클 젝슨의 목소리만을 이용하여 새로운 앨범을 출시한다든가, 국내의 모 벤춰에서는 사망한 아이의 아바타를 VR세계에 만들어서 살아있는 부모와 대화 할 수 있도록 한 적도 있다. 어쩄든 이 영화를 감상함에 있어 이런 개념 차이를 구분하는것은 의미없고 앞으로 인공지능 기계인간 시대를 피할 수 없는 우리에게 크게 2가지 해결해야할 윤리적 문제를 던져준다.

 

버전 4도 만들거야?


첫번째 문제는, 소프트웨어와 영혼의 경계를 어떻게 나눌 것인가?
이 영화에서도 이 문제는 특별히 강조되었다. 죽은 아내의 영혼을 복제한 로봇을 만들어가는데 한번에 완벽하게 만드는게 아니라 버전별로 버전1, 버전2, 버전3까지 만들게 된다. 버전3에 가서야 비로소 완전한 아내의 영혼을 복제한 기계인간이 만들어지지만. 그 단계에 이르렀을때 버전1, 버전2의 로봇은 자신들의 존재 의미에 대해 고민하게되고 그들을 만든 주인공도 죄의식과 책임감에 괴로워하게 된다. 이와 같은 문제는 유전공학의 초창기에도 윤리적 문제로 제시되어 왔던것인데 역시나 인공지능 영역에도 그대로 재현되고 있는것이다. 어디까지가 단지 인공지능 소프트웨어이고 어디서부터가 완전한 인간의 영혼이라고 인정할 수 있는 것일까? 소프트웨어가 완전한 영혼이되었다면 그때부터는 마음대로 리셋을 누르거나 파워 버튼을 내릴 수 없게 된다. 영화에서도 버전3가 처음으로 말한 것이 그것이다. 리셋버튼을 절대 누르지 말라고. 

두번쨰 문제는, 나의 영혼을 복제한 영혼은 나인가 아닌가?
내가 운이 좋아 기계안에 나의 영혼을 디지털화하여 담을 수 있는 시대까지 살아남아서 영혼을 복제해 넣아다치자. 그렇다면 그 기계는 나인가 아닌가? 그 기계는 충분히 똑똑하기 때문에 리셋버튼이 눌림을 당하지 않기위해 나인척해야할 것이고 실제로 나의 생각과 감정 그대로일 수도 있다. 하지만 그렇다고 그것이 나일까? 그리고 복제가 끝난 나는 어떻게 처리해야하는가? 안락사? 그리고 동일 영혼은 꼭 하나만 남기고 하나는 없애야 하는가? 한가지 분명한것은 살아있는 육신에 들어있는 영혼은 명백히 임의로 없앨 수 없다는 거다. 그것은 살인이니까. 그리고 기계안의 영혼은, 우리가 소프트웨어가 아니라 영혼으로 인정한 이상, 없앨 수 없다. 할 수 없이 동일 영혼의 복수 존재를 인정할 수 밖에 없게 된다. 복수 영혼을 인정하더라도 큰 문제가 있을 수는 없다고 본다. 디지털 영혼은 본래 영혼이 죽기 전까지는 디지털 영영내에서만 활동하며 자아성찰을 계속하면 되고 본래 영혼 사후에 모든것을 물려받는 것으로 하면 된다. 디지털 영혼이 많아진다고 해서 사회적 비용이 증가하지는 않는다. 오히려 이들 때문에 인간들이 더 편하고 윤택한 삶을 살게 될지도 모른다. 

아뭏든 생각해볼 수록 재미있는 고민거리가 많이 쏟아진다.

다음번에는 영화 업그레이드를 한번 리뷰해봐야겠다.

posted by Dr.Deeeep

▲ 포천시가 시정회의실에서 4차산업혁명의 아이콘 ‘드론’ 산업의 기반을 구축하기 위한 ‘포천시 드론클러스터 구축계획 용역 최종보고회’를 개최했다. 사진=포천시

http://www.dtoday.co.kr/news/articleView.html?idxno=343701

 

포천시, 드론클러스터 구축계획 용역 최종보고회 개최 - 일간투데이

[일간투데이 엄명섭 기자] 포천시는 지난 30일 시청 시정회의실에서 4차산업혁명의 아이콘 ‘드론’ 산업의 기반을 구축하기 위한 ‘포천시 드론클러...

www.dtoday.co.kr

 

posted by Dr.Deeeep

올해(2019년)는 논문도 못쓰고 특허만 3건을 받았다.

모두 딥러닝을 이용한 치매 진단 관련이다. 모두 미국 특허 출원 진행중이다.

 

딥러닝 기술 이용 치매 진단 관련 3건 특허

 

1. "질병예측 장치 및 이를 이용한 질병 예측 방법 (등록번호: 10-2057047)"은 뇌파나 심전도를 분석하여 치매를 조기 진단함에 있어 자질 추출 및 진단 과정의 블랙박스를 없애고 계산 복잡도를 낮추어 실시간 진단을 가능하게 하는 기술이다. '인바디' 처럼 휴대용 소형 치매 진단기를 개발하기 위해서 필수적인 기술이다.

 

개념도

 

2. "바이오 시그널 가시화 시스템 및 유효 패턴 추출 방법 (등록번호: 10-2009758)"은 뇌파나 심전도등 바이오 시그널에서 질병인과 정상인 그룹의 시그널을 모델링 및 가시화하고, 두 그룹을 구별하는 결정적인 패턴을 결정/인식/추출하는 방법이다.

 

 

3. "배회 감지 서버 및 이를 이용한 배회 감지 방법 (등록번호: 10-1996212)"는 치매 환자가 배회를 시작 할때 이 상황을 빨리 인식하고 보호자에게 연락하기 위한 특허이다. 딥러닝의 임베딩 기술을 이용하여 걸음 걸이의 요소(이동, 방향전환)등을 벡터화한 후 벡터 연산을 통해 비정상 상황을 빨리 감지한다.

 

 

 

posted by Dr.Deeeep

딥러닝에서 노이즈의 중요성??

상념 2017. 1. 12. 00:59

 

 

위 그림은 이글과 아무 관련이 없고 구글에서 퍼온 그림임.

뇌파를 보다보면 점점 노이즈 처리의 어려움으로 분석의 한계에 봉착하게 된다.아니 노이즈 처리의 어려움까지 가기전에 어디까지를 노이즈로 할것이고 어느 영역까지를 뇌파로 할것인지 결정하는 것부터 큰문제거리다. 그만큼 뇌파라는게 온갖 생체,환경,장비시그널의 결합체인것이다. 뇌파에는 뇌파이외에도, 심전도, 관측장비시그널, 근육움직임파동, 눈깜빡임, 눈동자 움직임, 턱근육 움직임, 전류, 저항잡음, 주변환경신호,등등이 섞여 있는데. 이건 마치 수백명이 물장구치는 수영장에서 철수가 만드는 파형만을 뽑아분석하려는 것과 같다... 어쩄든 그런 얘기를 하려는 건 아니고.

노이즈가 극히 적다는 가정하에 노이즈가 러닝에 어떤 영향을 끼지는지 조사를 해보았다. 몇가지 실험을 해보면 노이즈가 있는 데이터는 러닝 효율이 좋다. 내가 가진 정신착란 생쥐의 뇌파의 경우는 96퍼센트의 정확률로 분류하기까지 한다. 어마어마하게 뭔가 잘못된것이다. 물론 오버피팅이 되는 것이다. 첨부 이미지처럼 저렇게 electric pop 노이즈의 경우는 특히 그렇다. 쉽게 말해 저렇게 특이한 데이타(노이즈)가 들어오면 기계가 기억하기 쉽기 때문에 오버피팅이 되는 것이다. 마치 학생들 이름을 잘 못외우는 교사가 코에 유난히 큰 점이 있는 학생의 이름은 잘 기억하는 것과 같다( 맞는 예인가? ) 이러한 노이즈는 학습된 기계의 지능자체를 올려주는 것은 아니기때문에 지양해야한다.

하지만 저런 노이즈 말고 좀더 부드러운 노이즈는 어떨까? 몇몇 논문에서는 마일드한 노이즈를 섞어서 학습하는 것이 기계의 지능을 높이는 바람직한 학습을 가능하게 한다고 밝히고 있다. 즉, 앞의 예를 이용하면, 거의 대부분의 학생들 얼굴에 적절히 주근깨와 점들이 있다면 그 교사는 주근깨와 점에 집중하지 않고 학생들의 얼굴과 그외 본질에 연관하여 이름을 기억하게 되므로 더 많은 학생의 이름을 오래 기억할 수 있다. 딥러닝에 드롭아웃을 주는 이유도 아마 이와 같은 맥락인듯하다. 데이터에 노이즈를 넣을 수는 없으니까 학습할 때 노이즈를 줘서 학습 효과를 떨어뜨리는 것이다.

현실로 돌아와서..  뇌파에서는 저 그림과 같은 노이즈를 지우는 것은 사실 큰 의미는 없어 보인다. 이미 뇌파는 앞서 말한 노이즈 아닌 불필요 데이터들과 섞여 크게 요동치고 있고 자동화된 노이즈 제거 노력은 오히려 데이터를 일그러뜨려 망칠뿐이다. 그 보다는 뇌파와 섞이는 다른 신호들도 모두 저장하고 모두 같이 분석하는 기술의 개발이 필요한듯하다. 그럴려면 엄청난 양의 데이터 분석이 필요하겠지만..

 

posted by Dr.Deeeep

나만의 로보 어드바이저(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

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

금융 2016. 8. 30. 15:37

Python을 이용한 주가 데이터 크롤링

 

기본적으로 로보 어드바이저는 대용량의 주가 및 환경 데이터 + 지능적 트레이딩 알고리즘에 의해 구동된다. 따라서 나만의 로보 어드바이저를 만들기 위해서는 나만의 트레이딩 알고리즘을 구현할 수 있는 프로그램 능력과 대용량 데이터를 분석할 수 있는 분석 능력뿐 아니라 데용량 데이터를 수집할 수 있는 수집 능력이 필수 적이다. 따라서 주가 데이터의 크롤러가 필수적이다. 이 글에서는 주가 데이터의 크롤러 제작에 필요한 기술과 구현 방법에 대해 살펴보겠다.

 

공학도라면 서론을 길게 말하는것을 싫어한다. 결론 먼저, 설명 나중이므로. 먼저 쿨하게 내가 제작한 주가 데이터 크롤러 소스를 밑에 붙여 놓았다. 바쁜 사람은 그냥 카피해가서 바로 사용하면 된다. 안 바쁜 독자라면 계속 읽어보자.

 

이 코드는 파이썬으로 제작한 주가 데이터 크롤러이다. 로보 어드바이저는 두가지 크롤러가 필요한데, 롱텀 크롤러와 실시간 크롤러가 그것이다. 롱텀 크롤러는 처음 로보 어드바이저를 기동하기 위해 최초 한번은 몇 년치 주가 데이터를 한꺼번에 크롤링 하는 작업이 필요한데 그때 사용하기 위한 크롤러 이다. 밑에 소스는 롱텀 크롤러 소스이다. 이 후에는 변경(추가)된 데이터만을 매일매일, 혹은 실시간으로, 가져오는 간략화된(속도가 빠른) 실시간 크롤러가 필요한데 그것은 나중에 올리기로 한다. 물론 롱텀 그롤러와 실시간 크롤러는 비슷한 코드로 구성된다. 단지 용도에 맞게 프로그램 흐름도가 조금 다를뿐이다.

 

이 크롤러는 CybosPlus와 Python으로 구현되었다. CybosPlus는 대신증권에서 제공하는 시스템 트레이딩을 위한 API이다. CybosPlus에 대한 정보는 쉽게 찾아 볼 수 있으므로 생략하기로 한다.

 

(임시저장...)

 

 

 

 

#
# Developed by "Dr.Deeeep"
#
# intelligent version of crawler, in this version
#   - it check the last day of item in the database and crawling from the last day.
#   - the data of last day will be overwritten because they may are not the final value
#

 

import time
import mysql.connector
import win32com.client

config = {
  'user': 'USERID',
  'password': 'PASSWORD',
  'host': 'yourhost.com',
  'database': 'DBNAME',
  'raise_on_warnings': True,
}
# Don't forget to change the server setting to arrow remote connection to MySQL.
# mysql examples are available at
# https://dev.mysql.com/doc/connector-python/en/connector-python-examples.html
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()

 

cpcybos = win32com.client.Dispatch("CpUtil.CpCybos")

if cpcybos.IsConnect == 1:
    print("Cybos connection succeeded")
else:
    print("Cybos connection failed")

   
inStockCode = win32com.client.Dispatch("CpUtil.CpStockCode")    # general stock item info
inStockMst = win32com.client.Dispatch("dscbo1.StockMst")        # Current data
inStockChart = win32com.client.Dispatch("CpSysdib.StockChart")  # Past Data

totalItemNumInCybosPlus = inStockCode.GetCount()
print("Total number of items = ",totalItemNumInCybosPlus)

# print all items in BT format
# Some variables, such as changerate, fortramt, totaltraceprice, should be calculated on the fly, thus filled with dummy '-999.0'

 

#itemcode
finalpriceArray = []        #inStockChart.SetInputValue(5, 5)
startpriceArray = []        #inStockChart.SetInputValue(5, 2)
highpriceArray = []         #inStockChart.SetInputValue(5, 3)
lowpriceArray = []          #inStockChart.SetInputValue(5, 4)
changerateArray = []         #inStockChart.SetInputValue(5, 6)       may need to calculate from (today final / yesterday final)
tramtArray = []             #inStockChart.SetInputValue(5, 8)
orgtramtArray = []          #inStockChart.SetInputValue(5, 20)      THIS data is not complete in cybosdb. cannot use..
fortramtArray = []          # -999.0 #inStockChart.SetInputValue(5, ???) may need to cal from (today fortotal - yesterday fortotal)
fortotalArray = []          #inStockChart.SetInputValue(5, 16)
forportionArray = []        #inStockChart.SetInputValue(5, 17)
totaltradepriceArray = []   # -999.0    #inStockChart.SetInputValue(5, 0) may need to cal from (tramt * final price)

#beyond BT Format
circulationrateArray = []   #inStockChart.SetInputValue(5, 25)
totalstocknumArray = []     #inStockChart.SetInputValue(5, 12)
sichongArray = []           #inStockChart.SetInputValue(5, 13)


###################################################
#
#   This number represents the number of record to crawl for each cybosplus access
#   Must be large enough to cover the gap between the last date in my db and today while keep small enough to prevent the waste of speed of cybosplus access.
numOfCrawling = 200        # n days
#
#   This string number is the starting itemcode for the case of resuming suspened, quitted, crawling job
startingItemCode = "000000"    # 000000 for new start
#
#
###################################################


currentItemIndex = -1
for aItemcode in range(0, inStockCode.GetCount()):   # for each itemcode
    currentItemIndex = currentItemIndex + 1
    print("### progress = ", ((currentItemIndex * 100) / totalItemNumInCybosPlus), " %")
                     
    dateToCrawlArray = []       #inStockChart.SetInputValue(5, 0)

    # this line print just the item code and name
    # print(inStockCode.GetData(0,i), inStockCode.GetData(1,i), inStockCode.GetData(2,i))

    itemcode = inStockCode.GetData(0,aItemcode)

    # this can be used for resuming suspended process
    # THIS may not necessary for intelligent version of crawler
    if itemcode < "A"+startingItemCode:
        print("Skipping "+itemcode)
        continue

    inStockChart.SetInputValue(0, itemcode)

    ## retrieve LAST DATE in DB of this itemcode ==========================
    ## if no data for this item, set the last date to 20050101
   
    print ("itemcode = ", itemcode)
    shortItemcode = itemcode[1:]

    sqlStr = ("select max(date) from datatable where itemcode='"+ shortItemcode+ "'")

    #print("sqlStr = ", sqlStr, ", newItemcode = ", shortItemcode)
    cursor.execute(sqlStr)

 

    #######################################
    # modified source
    row = cursor.fetchone()
    if row[0]:
        lastDateInMyDB = row[0]
    else:                           # Null. number of returned row is 0. no data in DB.
        print ("itemcode = ", itemcode, " is added newly... skipping..")
        print ("TODO:  add code here to handle newly added items. !!!!!!!!!!!!")
        continue
    #######################################

 


    ## retrieving LAST DATE in CybosPlus ========================
    inStockChart.SetInputValue(1, '2')  # retrieve by num of records
    inStockChart.SetInputValue(4, 1)    # num of record to retrive is. Just the last one
    inStockChart.SetInputValue(5, 0)    # field type, tr amt(8), finalprice(5), date(0)
    inStockChart.SetInputValue(6, ord('D')) # chart type,  by Day
    inStockChart.SetInputValue(9, '0')  # modified price? yes. 0 for no
    inStockChart.BlockRequest()
    lastDateInCybosPlus = inStockChart.GetDataValue(0,0)
    print("in itemcode = ", itemcode, ", The latest data in CybosPlus = ", lastDateInCybosPlus)


#TODO:
#    dateToCrawlArray = retieve DATE array from lastDateInMyDB to lastDateInCybosPlus

#    for aDate in dateArray:
#        do the same with other crawlers


    ## retireve dateToCrawlArray
    print("in itemcode = ", itemcode, ", Now retrieving Date2Crawl array...")
    inStockChart.SetInputValue(1, '1')  # retrieve by num of specified date
    inStockChart.SetInputValue(3, lastDateInMyDB) # starting date
    inStockChart.SetInputValue(2, lastDateInCybosPlus) # ending date
    inStockChart.SetInputValue(4, numOfCrawling) # get some data which number is given
    inStockChart.SetInputValue(5, 0)    # field type, tr amt(8), finalprice(5), date(0)
    inStockChart.SetInputValue(6, ord('D')) # chart type,  by Day
    inStockChart.BlockRequest()

    numofdate2Crawl = inStockChart.GetHeaderValue(3)    # num of rec retrieved
    print("in itemcode = ", itemcode, ", Num of DATE to crwal = ", numofdate2Crawl, " From = ", lastDateInMyDB, " to = ", lastDateInCybosPlus)
    for i in range(numofdate2Crawl):
        volumn = inStockChart.GetDataValue(0,i)
        dateToCrawlArray.insert(0, volumn)
        if int(volumn) <= int(lastDateInMyDB):
            break

    print("in itemcode = ", itemcode, ", dateToCrawArray = ", dateToCrawlArray)

    for aCrawlDate in dateToCrawlArray:
       
        ## retrieving FINALPRICE =========================
        inStockChart.SetInputValue(1, '1')  # retrieve by num of specified date
        inStockChart.SetInputValue(3, aCrawlDate) # starting date
        inStockChart.SetInputValue(2, aCrawlDate) # ending date
        inStockChart.SetInputValue(4, 1) # get a data
        inStockChart.SetInputValue(5, 5)    # finalprice(5)
        inStockChart.SetInputValue(6, ord('D')) # chart type,  by Day
        inStockChart.SetInputValue(9, '0')  # modified price? yes. 0 for no
        inStockChart.BlockRequest()
        numofreturned_finalprice = inStockChart.GetHeaderValue(3)    # num of rec retrieved
        #print(" Num of retrieved record (FP) = ", numofreturned_finalprice)
        if (numofreturned_finalprice > 0):
            finalprice = inStockChart.GetDataValue(0,0)  
            #print("     final price was ", finalprice)
        else:
            finalprice = '-999.0'
            print(itemcode, "     No data. default final price: -999.0")


        ## retrieving STARTPRICE ============================
        inStockChart.SetInputValue(1, '1')  # retrieve by num of specified date
        inStockChart.SetInputValue(3, aCrawlDate) # starting date
        inStockChart.SetInputValue(2, aCrawlDate) # ending date
        inStockChart.SetInputValue(4, 1) # get a data
        inStockChart.SetInputValue(5, 2)    # startprice
        inStockChart.SetInputValue(6, ord('D')) # chart type,  by Day
        inStockChart.SetInputValue(9, '0')  # modified price? yes. 0 for no
        inStockChart.BlockRequest()
        numofreturned_startprice = inStockChart.GetHeaderValue(3)    # num of rec retrieved
        #print(" Num of retrieved record (SP) = ", numofreturned_startprice)
        if (numofreturned_startprice > 0):
            startprice = inStockChart.GetDataValue(0,0)      
            #print("    start price was ", startprice)
        else:
            startprice = '-999.0'
            print(itemcode, "              No data. default START PRICE : -999.0")


        ## retrieving HIGHPRICE ============================
        inStockChart.SetInputValue(1, '1')  # retrieve by num of specified date
        inStockChart.SetInputValue(3, aCrawlDate) # starting date
        inStockChart.SetInputValue(2, aCrawlDate) # ending date
        inStockChart.SetInputValue(4, 1) # get a data
        inStockChart.SetInputValue(5, 3)    # highprice
        inStockChart.SetInputValue(6, ord('D')) # chart type,  by Day
        inStockChart.SetInputValue(9, '0')  # modified price? yes. 0 for no
        inStockChart.BlockRequest()
        numofreturned_highprice = inStockChart.GetHeaderValue(3)    # num of rec retrieved
        #print(" Num of retrieved record (HP) = ", numofreturned_highprice)
        if (numofreturned_highprice > 0):
            highprice = inStockChart.GetDataValue(0,0)      
            #print("    high price was ", highprice)
        else:
            highprice = '-999.0'
            print(itemcode, "                 No data. default HIGH PRICE: -999.0")

 

        ## retrieving LOWPRICE ============================
        inStockChart.SetInputValue(1, '1')  # retrieve by num of specified date
        inStockChart.SetInputValue(3, aCrawlDate) # starting date
        inStockChart.SetInputValue(2, aCrawlDate) # ending date
        inStockChart.SetInputValue(4, 1) # get a data
        inStockChart.SetInputValue(5, 4)    # lowprice
        inStockChart.SetInputValue(6, ord('D')) # chart type,  by Day
        inStockChart.SetInputValue(9, '0')  # modified price? yes. 0 for no
        inStockChart.BlockRequest()
        numofreturned_lowprice = inStockChart.GetHeaderValue(3)    # num of rec retrieved
        #print(" Num of retrieved record (LowP) = ", numofreturned_lowprice)
        if (numofreturned_lowprice > 0):
            lowprice = inStockChart.GetDataValue(0,0)      
            #print("    low price was ", lowprice)
        else:
            lowprice = '-999.0'
            print(itemcode, "                   No data. default LOW PRICE: -999.0")

 

        ## retrieving CHANGERATE ============================
        changerate = '-999.0'     
        #print("    changerate was ", changerate)


        ## retrieving TRAMT ============================
        inStockChart.SetInputValue(1, '1')  # retrieve by num of specified date
        inStockChart.SetInputValue(3, aCrawlDate) # starting date
        inStockChart.SetInputValue(2, aCrawlDate) # ending date
        inStockChart.SetInputValue(4, 1) # get a data
        inStockChart.SetInputValue(5, 8)    # tramt
        inStockChart.SetInputValue(6, ord('D')) # chart type,  by Day
        inStockChart.SetInputValue(9, '0')  # modified price? yes. 0 for no
        inStockChart.BlockRequest()
        numofreturned_tramt = inStockChart.GetHeaderValue(3)    # num of rec retrieved
        #print(" Num of retrieved record (TRAMT) = ", numofreturned_tramt)
        if (numofreturned_tramt > 0):
            tramt = inStockChart.GetDataValue(0,0)      
            #print("    tramt was ", tramt)
        else:
            tramt = '-999.0'
            print(itemcode, "                     No data. default TRAMT: -999.0")

 

 

        ## retrieving ORGTRAMT ============================
        inStockChart.SetInputValue(1, '1')  # retrieve by num of specified date
        inStockChart.SetInputValue(3, aCrawlDate) # starting date
        inStockChart.SetInputValue(2, aCrawlDate) # ending date
        inStockChart.SetInputValue(4, 1) # get a data
        inStockChart.SetInputValue(5, 20)    # org tramt
        inStockChart.SetInputValue(6, ord('D')) # chart type,  by Day
        inStockChart.SetInputValue(9, '0')  # modified price? yes. 0 for no
        inStockChart.BlockRequest()
        numofreturned_orgtramt = inStockChart.GetHeaderValue(3)    # num of rec retrieved
        #print(" Num of retrieved record (ORG TRAMT) = ", numofreturned_orgtramt)
        if (numofreturned_orgtramt > 0):
            orgtramt = inStockChart.GetDataValue(0,0)      
            #print("    orgtramt was ", orgtramt)
        else:
            orgtramt = '-999.0'
            print(itemcode[1:], "                      No data. default ORG TRAMT: -999.0")
           

        ## retrieving FORTRAMT ============================
        fortramt = '-999.0'     
        #print("    fortramt was ", fortramt)

 

        ## retrieving FORTOTAL ============================
        inStockChart.SetInputValue(1, '1')  # retrieve by num of specified date
        inStockChart.SetInputValue(3, aCrawlDate) # starting date
        inStockChart.SetInputValue(2, aCrawlDate) # ending date
        inStockChart.SetInputValue(4, 1) # get a data
        inStockChart.SetInputValue(5, 16)    # startprice
        inStockChart.SetInputValue(6, ord('D')) # chart type,  by Day
        inStockChart.SetInputValue(9, '0')  # modified price? yes. 0 for no
        inStockChart.BlockRequest()
        numofreturned_fortotal = inStockChart.GetHeaderValue(3)    # num of rec retrieved
        #print(" Num of retrieved record (FORTOTAL) = ", numofreturned_fortotal)
        if (numofreturned_fortotal > 0):
            fortotal = inStockChart.GetDataValue(0,0)      
            #print("    fortotal was ", fortotal)
        else:
            fortotal = '-999.0'
            print(itemcode, "                          No data. default FORTOTAL: -999.0")

       

        ## retrieving FORPORTION ============================
        inStockChart.SetInputValue(1, '1')  # retrieve by num of specified date
        inStockChart.SetInputValue(3, aCrawlDate) # starting date
        inStockChart.SetInputValue(2, aCrawlDate) # ending date
        inStockChart.SetInputValue(4, 1) # get a data
        inStockChart.SetInputValue(5, 17)    # startprice
        inStockChart.SetInputValue(6, ord('D')) # chart type,  by Day
        inStockChart.SetInputValue(9, '0')  # modified price? yes. 0 for no
        inStockChart.BlockRequest()
        numofreturned_forportion = inStockChart.GetHeaderValue(3)    # num of rec retrieved
        #print(" Num of retrieved record (FORPORTION) = ", numofreturned_forportion)
        if (numofreturned_forportion > 0):
            forportion = inStockChart.GetDataValue(0,0)
            forportion = float("{0:.4f}".format(forportion))
            #print("    forportion was ", forportion)
        else:
            forportion = '-999.0'
            print(itemcode, "                          No data. default FORPORTION: -999.0")

       

        ## retrieving TOTALTRADEPRICE ============================
        totaltradeprice = '-999.0'   
        #print("    total trade price was ", totaltradeprice)


        ## retrieving CIRCULATIONRATE ============================
        circulationrate = '-999.0'   
        #print("    circulation rate was ", circulationrate)
       

        ## retrieving TOTALSTOCKNUM ============================
        inStockChart.SetInputValue(1, '1')  # retrieve by num of specified date
        inStockChart.SetInputValue(3, aCrawlDate) # starting date
        inStockChart.SetInputValue(2, aCrawlDate) # ending date
        inStockChart.SetInputValue(4, 1) # get a data
        inStockChart.SetInputValue(5, 12)    # startprice
        inStockChart.SetInputValue(6, ord('D')) # chart type,  by Day
        inStockChart.SetInputValue(9, '0')  # modified price? yes. 0 for no
        inStockChart.BlockRequest()
        numofreturned_totalstocknum = inStockChart.GetHeaderValue(3)    # num of rec retrieved
        #print(" Num of retrieved record (TOTALSTOCKNUM) = ", numofreturned_totalstocknum)
        if (numofreturned_totalstocknum > 0):
            totalstocknum = inStockChart.GetDataValue(0,0)      
            #print("    totalstocknum was ", totalstocknum)
        else:
            totalstocknum = '-999.0'
            print(itemcode, "                     No data. default TOTALSTOCKNUM: -999.0")
           


        ## retrieving SICHONG ============================
        inStockChart.SetInputValue(1, '1')  # retrieve by num of specified date
        inStockChart.SetInputValue(3, aCrawlDate) # starting date
        inStockChart.SetInputValue(2, aCrawlDate) # ending date
        inStockChart.SetInputValue(4, 1) # get a data
        inStockChart.SetInputValue(5, 13)    # startprice
        inStockChart.SetInputValue(6, ord('D')) # chart type,  by Day
        inStockChart.SetInputValue(9, '0')  # modified price? yes. 0 for no
        inStockChart.BlockRequest()
        numofreturned_sichong = inStockChart.GetHeaderValue(3)    # num of rec retrieved
        #print(" Num of retrieved record (SICHONG) = ", numofreturned_sichong)
        if (numofreturned_sichong > 0):
            sichong = inStockChart.GetDataValue(0,0)      
            #print("    sichong was ", sichong)
        else:
            sichong = '-999.0'
            print(itemcode, "                No data. default SICHONG: -999.0")
       

        #sqlStr = ("insert into cybosplus date="+str(aCrawlDate)+", itemcode="+itemcode[1:]+", finalprice="+str(finalprice)+", startprice="+str(startprice))
        #print("insert sqlStr = ", sqlStr)

        add_record = ("insert into datatable "
                      "(date, itemcode, finalprice, startprice, highprice, lowprice, changerate, tradeamount, orgtradeamount, fortradeamount, fortotalamount, forportion, totaltradeprice, totalstocknum, sichong) "
                      "values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) "
                      "on duplicate key update "
                      "finalprice=%s, startprice=%s, highprice=%s, lowprice=%s, changerate=%s, tradeamount=%s, orgtradeamount=%s, fortradeamount=%s, fortotalamount=%s, forportion=%s, totaltradeprice=%s, totalstocknum=%s, sichong=%s")
             
        data_record = (aCrawlDate, itemcode[1:], finalprice, startprice, highprice,
                       lowprice, changerate, tramt, orgtramt, fortramt,
                       fortotal, forportion, totaltradeprice, totalstocknum, sichong,
                       finalprice, startprice, highprice,
                       lowprice, changerate, tramt, orgtramt, fortramt,
                       fortotal, forportion, totaltradeprice, totalstocknum, sichong)

        cursor.execute(add_record, data_record)
        cnx.commit()       

cursor.close()
cnx.close()

 


 

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

세부과제 2
Deep learning for Early Detection of Dementia
and a pilot study

운영회의

20160524_치매조기예측_딥러닝_김선호.pdf
다운로드

 

2016.05.24

 

 

 

 

목차

인공지능(기계학습)을 이용한 질병 진단

Why Deep Learning?

기존 기계학습

Deep Learning

Deep Learning을 이용한 EEG 분석 Pilot Study

 

 

Why Deep Learning (Neural Network)?
Integrated Learning

 

 

기존 데이터 분석을 통한 질병 진단

기존 기계학습을 이용한 학습

기존 기계학습을 이용한 진단

딥러닝을 이용한 진단

 

 

딥러닝을 이용한 학습

사람의 인지 과정과 유사

추상화: 저수준표현è고수준 표현

 

 

 

기존 기계학습 기법 대비 Deep Learning 장점

자동화된 Feature selection

학습 데이터 제작 비용 ↓ 시간 ↓

대용량 원시 데이터 학습 (sensor, raw,…)

월등한 성능!!

 

 

 

현재 딥러닝 기술 수준

Playing Game

Object Recognition

Semantic Segmentation

Image Completion

Hand Writing by Machine

Music Composition

Image Caption Generation

Visual Question Answering

Word Analogy

Neural Machine Translation

 

Playing Game

Object Recognition

Semantic Segmentation

Image Completion

Hand Writing by Machine

Music Composition

Painting

Image Caption Generation

Visual Question Answering

Word Analogy

Neural Machine Translation

 

 

Deep Learning을 이용한 EEG 분석 Pilot Study

UCI EEG Data

Two groups: alcoholic and nc

122 subjects x about 120 trials (different stimuli); total 11057 cases

Each case:  64 electrodes x 256 hz

 

 

 

 

700mb

Stimulus: object S1, or S1 and S2 (matched or non-matched)

Electrode position: Zhang et al. 1995

 

 

Alcoholic EEG vs NC EEG

Pilot Study

Pilot Study

Deep Belief Network을 이용한 EEG 데이터 학습

EEG 최대값 465.63, 최소값 -158.96, 평균 -1.86

대부분 -30~+100에 집중

Z-score normalization

 

 

 

 

 

 

 

 

 

 

Pilot Study

전체 데이터의 90% 학습, 10%는 평가에 이용 10 fold cross-validation

 

 

실험결과

Accuracy(=(TP+TN)/(P+N)): 0.77

Precision(=TP/(TP+FP)): 0.78

Sensitivity(=Recall=TP/(TP+FN)): 0.78

F1 score(=2TP/(2TP+FP+FN)): 0.78

 

 

 

 

 

 

 

 

 

 

Further Study

Further study

뇌파 패턴 분석

Normalization 최적화 (z-score, linear min-max, 3depth linear, Bezier,...)

Activation function 최적화

 

 

                                                      

Network type 최적화

DBN, CNN, RNN, LSTM, RBM, DeepQ,..

 

 

 

 

Question? Comment?

posted by Dr.Deeeep