오늘은 CybosPlus를 이용하여 실제로 나의 계좌를 관리하고 계좌 정보를 가져오는 방법, 그리고 정해진 조건이 만족되었을 때 매수 및 매도가 이루어지도록 프로그램 매을 내는 방법을 알아보자.

posted by Dr.Deeeep

Time Series Prediction을 위한 Deep learning

 

이번 글에서는 주가 예측의 기본 개념인 time series prediction 을 딥러닝 기술로 구현하는 방법에 대해 알아보도록 하겠다.

 

 

위 그림은 구글 이미지 검색에서 time series prediction 으로 검색을 해서 찾아낸 그림 중 하나인데, 오늘 설명할 deep learning을 이용한 time series prediction의 개념을 쉽게 도식화 한 것이다.

time series 데이터란 시간 축에 따라 변하는 데이터를 (시간,값)의 형태로 쭉 기록한 데이터를 말하는데 주가 데이터, 뇌파 데이터, 기온 데이터 등이 이에 해당한다. 주가 데이터라면 x 축이 시간(월, 일, 주, 시, 초 등)이고 y 축이 주가 데이터(주가, 거래량, 변동률 등등)이 되겠다. 

time series prediction의 가장 대표적인 알로리즘은 일정 기간의 데이터를 관찰하고 바로 다음 순간의 값을 예측하는 것이다. 

 

 

<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

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

상념 2016. 8. 30. 15:06

로보 어드바이저란? 

 

 

 

 

 

새로운 용어는 아니지만 요즘 뜨고 있는 로보 어드바이저 (robo-advisor)라는 기술. 쉽게 말해 인공지능 기술을 이용하여 자신이 원하는 알고리즘으로 컴퓨터가 주식 거래를 자동으로 수행하도록 하는 기술이다. 물론 이것은 내 나름의 좁은 해석이고 원래는 더 넓고 좋은 의미가 있을것이다. 그런 글은 위키페디아를 참조.

 

빅데이터, 딥러닝, 머신러닝 등등 신조어를 만들기 좋아하는 요즘시대에 로보 어드바이저는 인공지능과 금융이라는 인간의 흥미와 욕망에 부합하여 차세대 대세어로 부족함이 없다. 

 

나는 로보 어드바이저라는 말은 처음 들어본것이 한달 정도 된 듯하다. 처음에는 무슨 신조어인가 했지만 뜻을 알고 나서는.. 흠. 이런 기술은 이미 금융 공학을 공부하거나 데이터 분석을 하는 사람들에게는 오래전부터 있었던 개념이다. 단지 "인공지능"과 "빅데이터"와 같이 현시대 최첨단을 걷는 기술들이 결합되면서 그동안의 데이터 분석에만 집중하던 금융기술이 이제 분석과 기계학습을 이용한 좀더 지능적인 의미로 떠오른 것이다. 

 

로보 어드바이저라는 개념이 원래는 더 넓은 개념의 더 좋은 뜻도 많이 있겠지만, 좁은 의미인 "빅데이터에 기반한 인공 지능 트레이딩 로봇"을 만드는 방법에 대해 연재해보도록 하겠다. 나는 이러한 로봇은 이미 수년전에 개발하여 사용하고 있다. 한때는 실전에 적용하여 트레이딩을 해보기도 했지만 튜닝없이 바로 운영을 하려니 성공률이 낮아 현재는 일단 시뮬레이션만 수행하며 실제 거래는 로봇이 만드는 리포트를 보고 수동으로 수행하고 있다.

 

나만의 로보어드바이저의 개발에 필요한 준비물을 알아보자.

 

Python 

자바

VC++ 6.0 이상

CybosPlus (대신증권계좌필요)

MySQL

 

 

 

CybosPlus 는 대신증권에서 제공하는 개발자를 위한 트레이딩용 API로 자바, python, c++ 등에서 사용할 수 있다. 빠르게는 초당 10회 정도 트레이딩을 할 수 있다. 무엇보다도 실시간 가격을 가져온다든가 처음 수년간의 데이터(빅데이터)를 구축하기 위해 필요하다.

 

일단 여기 까지...

 

 

 

posted by Dr.Deeeep

ECCB 2016 app

상념 2016. 8. 28. 12:09

 
 
다음주에 출장갈 ECCB 2016 학회의 스맛폰 앱.
 
학회 앱이 이런식으로 출시되는 것은 처음보는데 상당히 혁신적인 아이디어이다. 다른때 같으면 출장 준비로 학회 프로그램이나 학회 정보등 출력해 놓느라 분주할때인데 이번에는 그럴필요가 없다. 앱으로 모든 정보를 찾을 수 있으니 편리하다.
 
좀더 생각해 보니, 이런 학회 앱을 더 발전 시켜서 앱에서 학회 등록도 하고 (in app purchase 방식으로 등록비 지불), 논문이나 키노트 자료등도 받고 프로시딩도 팔고, 참가자간 서로 챗도 할 수 있게 하면 더 좋을 듯. 숙소나 교통 예약도 하고.
 
암튼. 이 학회에서 발표할 딥러닝 실험을 해야 하는데...
뇌파 데이터에서 생성한 뇌파 이미지들을 딥러닝(cNN)으로 학습을 해서 분류 능력을 테스트 하는 실험이다. computationgraph를 써서 아키텍춰를 좀더 복잡하고 LSTM와 DBN을 합해서 Bashivan et. al. 2016 같은 그럴듯한 모델을 시도해 볼 수도 있지만 이번 학회는 좀 급하게 준비하느라 그냥 cNN으로 가기로 했다. 문제는, DL4J에 당연히 그 흔한 이미지 클레시피케이션 예제가 있을거라고 생각하고 느긋이 딴 일 하고 있었는데.. 오늘 찾아 보니 없다. 어딜 봐도 제대로 된 자바 소스가 없는 거다. ㅠㅠ
 
할 수 없이 지금 이 나이에 황금같은 주말에 쌩으로 코딩을하고 있다. 아토피 걸린 Yona를 옆에서 재우고 긁나 안긁나 감시하면서.
하지만 지금 무엇보다 힘든 건 코어 2개뿐인 열악한 뉴맥북에서 인텔리제이로 이미지 처리 관련 코딩을 해야 한다는 거다...
 
 

posted by Dr.Deeeep

도메인을 하나 더 구입했는데..

상념 2016. 8. 24. 09:31

 

고데디에서 도메인을 하다 더 구입했는데..

바로

"deep-trader.com".

이로써 bigdata-trader.com, deep-trader.com 두개를 운영하게 되었다.

 

bigdata-trader에서는 전통적 방식의 알고리즘을 테스트 하는 것으로 하고, deep-trader에서는 딥러닝 모델들을 테스트 하는 것으로 하겠다.

 

 

posted by Dr.Deeeep

동영상의 vectorizing은 어떻게 해야하나?

상념 2016. 8. 24. 02:30

치매 예측 딥러닝을 위한 뇌파 데이터의 분류는 생각의 꼬리를 이어 이어..

Time Series 뇌파 -> 2D image data -> serial images(frames) -> video 로 이어졌고.

결국 

problem of dementia prediction은 video understanding의 문제로 전환.

이제 뇌파 이미지를 동영상 변환 하는데까지는 어떻게 된거 같은데. 그렇다면 이제 동영상은 어떻게 vectorize 해야하는 걸까? canova javadoc에는 안나온다.

 

개별 프레임을 이미지로 추출하여... 그냥 나열한 후 vector 화? 이렇게 되면 전극간 spatial 정보를 학습하겠다던 애초 가설이 충족되지 않는다. 

 

구글링이 필요함.

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

새로운 블로그 시작과 블로그의 성격

상념 2015. 8. 10. 03:06

티스토리 블로그에 계정을 만든지는 몇달 되었지만 이제 처음 글을 쓰게 된다. 이곳에는 나의 연구내용을 기록하기로 한다.

최근 나의 연구 관심은 타임시리즈 데이터의 단기간 미래 예측에 대한 것이다. 이러한 연구는 금융분야 특히 시스템 트레이딩 분야에서 유용하게 사용될 수 있을 것이다. 쉽게 말해 주가 예측에 대한 연구이다. 나는 기본적 분석을 철저히 지양하고 오로지 물결과 같이 파동치는 데이터의 성질만을 이용한 기술적 분석만으로 성공 확률 50프로 이상의 알고리즘을 발견하는 것이 가능하다고 믿고 있으며 부족하지만 내가 가진 모든 수학적 능력과 컴퓨터 프로그래밍 재능을 그러한 알고리즘의 개발에 헌신하고자 한다.

내가 기본적 분석을 지양하는 이유는 별게아니다. 그러한 방법이 틀렸거나 비효율적이기 때문이 아니다. 단지 그 분야에는 내가 관심있는 연구 내용이 없고 그 분야에서 내가 후손에게 컨트리뷰션할 것이 없기 때문이다. 기본분석이건 기술분석이건 각각 장단점이 있을것이라는데 이견은 없다. 

주가 예측에 있어 연구적 흥미 이외에 기술적 접근 방법이 맞다고 생각하는 이유, 즉 가까운 미래를 예측하는 알고리즘이 존재한다고 생각하는 이유,로 한가지 는

posted by Dr.Deeeep