예제 #1
0
def loadAllStockMst() :
    fileName = u'StockMst.des'
    stockFile = cxFile(fileName)
    sep = u'\t'

    lines = stockFile.readlines() 
    print lines[0]
예제 #2
0
파일: testSim.py 프로젝트: ClarkOh/snowball
def getDayVariance(code) :
    if type(code) != str and type(code) != unicode :
        print 'invalid code type', type(code)
        return None
    #dataPath = u'database\\day\\'
    dataPath = u'D:\\user\\clark\\MyWork\\codes\\RapidSnowBall\\database\\day\\'
    #dataPath = u'D:\\user\\MyProject_old\\codes\\RapidSnowBall\\database\\day\\'
    fileName = dataPath + code + u'.data'
    #fileName = u'D:\\user\\MyProject_old\\codes\\RapidSnowBall\\database\\day\\A000020.data'
    from cxFile import cxFile
    try :
        dataFile = cxFile(fileName)
    except :
        print 'file open failed :', fileName
        return None

    lines = dataFile.readlines()
    if len(lines) == 0 :
        print 'no data in %s'%(code)
        return None
    
    dataList = []
    from common import getFieldDataList

    for index in range(1,len(lines)) :
        dataList.append(int(getFieldDataList(lines[index])[6]))

    result = cal_mean_and_variance(dataList) 
    print result
    return result
예제 #3
0
파일: testCP.py 프로젝트: ClarkOh/snowball
def testStockMst_ver_1() :
    from cxCybosPlus import gCybosPlusClassDic
    stockMst = gCybosPlusClassDic['cxCpStockMst']
    stockMst.SetInputValue(0, u'A000660')
    stockMst.BlockRequest()
    option = 1
    if option == 1 :
        headerValueIndexList = [u'0',u'1',u'2',u'3',4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,
                                19,20,21,22,23,24,25,26,27,28,u'31',32,33,34,u'35',36,37,38,39,
                                40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,
                                60,61,62,63,64,65,66,67,68,69,70]
        for headerValueIndex in headerValueIndexList :
            print headerValueIndex, stockMst.GetHeaderValue(headerValueIndex)

    else :
        from cxFile import cxFile
        from common import UNI
        resultFile = cxFile()
        for headerValueIndex in stockMst.headerIndexDic.keys() :
            name = stockMst.headerIndexDic[headerValueIndex][1]
            value = stockMst.GetHeaderValue(headerValueIndex)
            #print UNI(name) + u' ' + UNI(value)
            #print name, stockMst.GetHeaderValue(headerValueIndex)
            resultFile.write(UNI(name)+u' : '+UNI(value) + u'\n')
        resultFile.close()

    del stockMst
예제 #4
0
파일: testSim.py 프로젝트: ClarkOh/snowball
def testGetFieldDataList() :
    from cxFile import cxFile
    fileName = u'database\day\A000020.data'
    dataFile = cxFile(fileName)
    dataLines = dataFile.readlines()
    fieldDataList = getFieldDataList(dataLines[1])
    print fieldDataList
    dataFile.close()
예제 #5
0
파일: common.py 프로젝트: ClarkOh/snowball
def test_cpBlockRequest() :
    from cxFile import cxFile
    resultFile = cxFile()
    paramList = [
        [ 0, 'A000660'],
    ]
    testBlockRequest( 'cxCpStockMst', paramList, 1, 1, 1, 0, resultFile, sys.stderr )
    resultFile.close()
예제 #6
0
파일: cxStock.py 프로젝트: ClarkOh/MyWork
def test() :
    from cxFile import cxFile
    resultFile = cxFile()
    stock = cxStock('A153360','오진원','KR71521304506')
   
    resultFile.write(stock.dump())
    resultFile.write(u'\n')
    resultFile.close()
    del stock
예제 #7
0
def test_01():
    from cxFile import cxFile
    resultFile = cxFile()
    stockMgr = cxStockMgr()

    if stockMgr.update() > 0:
        resultFile.write(stockMgr.dump())
        #for result in stockMgr.searchStockCode( u'삼성' )   :
        #    print result[0], result[1]

    resultFile.close()
    del stockMgr
예제 #8
0
def test_01() :
    from cxFile import cxFile
    resultFile = cxFile()
    stockMgr = cxStockMgr()

    if stockMgr.update() > 0 :
        resultFile.write(stockMgr.dump())
        #for result in stockMgr.searchStockCode( u'삼성' )   :
        #    print result[0], result[1] 

    resultFile.close()
    del stockMgr
예제 #9
0
def getAllStockMst() :
    import time

    from cxCybosPlus import constants
    from cxCybosPlus import gCybosPlusClassDic
    from cxStockMgr  import stockMgr
    cpCybos = gCybosPlusClassDic['cxCpCybos']
    stockMst = gCybosPlusClassDic['cxCpStockMst']
    stockList = stockMgr.getStockList()

    sep = u'\t'
    newLine = u'\n'
    
    fileName = u'StockMst.des'
    if common.checkFileExist(fileName) == True :
        os.remove(fileName)
    stockMstFile = cxFile(fileName)
    strLine = u''
    
    for key in stockMst.headerIndexDic.keys() :
        strLine += stockMst.headerIndexDic[key][1] + sep 
    strLine += newLine
    print strLine
    stockMstFile.write(strLine)
   
    #stockList = [[u'A000660',u'SK하이닉스']]
    for stockItem in stockList :
        print stockItem[0]
        stockMst.SetInputValue(u'0',stockItem[0])
        stockMst.BlockRequest()
        result = stockMst.getResult()
        
        print 'getResult (',result[0],')'
        
        if result[0] != 0 :
            print stockItem[0], ': BlockRequest is failed (%d).'%(result[0])
            continue
        
        strLine = u''
        for key in stockMst.headerIndexDic.keys() :
            strLine += unicode(result[5][0][key][2]) + sep
        strLine += newLine
        print strLine
        stockMstFile.write(strLine)
        
        remainCount = cpCybos.GetLimitRemainCount(constants.LT_NONTRADE_REQUEST)
        remainTime = cpCybos.LimitRequestRemainTime()
        print remainCount, remainTime
        if remainCount <= 0 :
            time.sleep((remainTime/1000)+1)

    stockMstFile.close()
예제 #10
0
파일: testCP.py 프로젝트: ClarkOh/snowball
def testStockMst_ver_2() :
    from common import testBlockRequest
    from cxFile import cxFile

    stockCode = u'A000660'
    paramList = [ [ 0, stockCode ], ]
    option = 1
    if option == 1 :
        print testBlockRequest('cxCpStockMst', paramList, 1, 1, 0, 0)
    else :
        resultFile = cxFile()
        testBlockRequest( 'cxCpStockMst', paramList, 1, 1, 0, 0,resultFile )
        resultFile.close()
예제 #11
0
파일: common.py 프로젝트: ClarkOh/MyWork
def test_cpBlockRequest():
    from cxFile import cxFile

    resultFile = cxFile()

    paramList = [
        [0, 'A000660'],
    ]

    testBlockRequest('cxCpStockMst', paramList, 1, 1, 1, 0, resultFile,
                     sys.stderr)

    resultFile.close()
예제 #12
0
파일: common.py 프로젝트: ClarkOh/MyWork
def test_cxStockChart():

    from cxCybosPlus import getCybosPlusClassDic
    from cxLog import cxLog
    from cxFile import cxFile

    log = cxLog()
    resultFile = cxFile()

    cpClsDic = getCybosPlusClassDic()
    className = 'cxStockChart'

    fieldList = [ 0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, \
                  14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, \
                  25, 26, 37 ]

    paramList = [
        [0, u'A000660'],  # 하이닉스
        [1, ord('1')],
        [2, 20121010],
        [3, 19920901],
        [4, len(fieldList)],
        [5] + fieldList,
        [6, ord('D')],
        [10, ord('3')]
    ]

    resultList = templateBlockRequest(cpClsDic[className],
                                      paramList,
                                      errLog=log)

    bFirst = 1
    for results in resultList:
        resultFile.write(
            getResultStringLandscape(
                results,
                statusOption=0,
                headerValue=0,  #len(results[5]), 
                dataValue=1,  #len(results[6]),
                titleOption=bFirst))
        bFirst = 0

        #resultFile.write( getHeaderResultString(results[5], 1 ) )
        #resultFile.write( '\n' )
        #resultFile.write( getDataResultString(results[6], 1 ) )

    log.close()
    resultFile.close()

    del cpClsDic
예제 #13
0
    def install(self) :
        import time
        from cxCybosPlus import constants
        cpCybos = self.cpClsDic['cxCpCybos']
        self.updateFailedStockList = []
        stockList = stockMgr.getStockList()

        updateFailedStockCodeListFileName = self.basePath + u'updateFailedStockCodeList.txt'
        updateFailedStockCodeListFile = cxFile(updateFailedStockCodeListFileName)

        for chartType in self.chartType.keys() :
        #{
            for code, name, fullcode in stockList :
            #{
                print chartType, code, name,
                resultList = self.update(chartType,code)

                if resultList.result != u'ok' :
                #{
                    failedString = common.UNI(code) + u' ' + \
                                   common.UNI(name) + u' ' + \
                                   common.UNI(chartType) + u' ' + \
                                   common.UNI(resultList.result) + u'\n'
                    print failedString
                    updateFailedStockCodeListFile.write(failedString)
                    self.updateFailedStockList.append([ chartType, code, name ])
                #}

                remainCount = cpCybos.GetLimitRemainCount(constants.LT_NONTRADE_REQUEST)
                remainTime = cpCybos.LimitRequestRemainTime()
                print '\tremainCount : %d, remainTime : %d'%(remainCount, remainTime)

                if remainCount <= 0 :
                #{
                    print '\ttime.sleep for %d msec. [%d sec.]'%(remainTime, (remainTime/1000)+1 )
                    time.sleep((remainTime/1000) + 1)
                #}
            #}
        #}

        updateFailedStockCodeListFile.close()
        
        if len(self.updateFailedStockList) > 0 :
        #{
            print 'update failed stock list'
            for chartType, code, name in self.updateFailedStockList :
                print chartType, code, name
        #} 
        
        return True
예제 #14
0
파일: common.py 프로젝트: ClarkOh/snowball
def test_cxStockChart() :

    from cxCybosPlus import gCybosPlusClassDic        
    from cxLog import cxLog
    from cxFile import cxFile
   
    log = cxLog()
    resultFile = cxFile()

    className = 'cxStockChart'
    cpClsDic = gCybosPlusClassDic[className]

    fieldList = [ 0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, \
                  14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, \
                  25, 26, 37 ]

    paramList = [ 
        [ 0, u'A000660' ], # 하이닉스
        [ 1, ord('1') ],
        [ 2, 20121010 ],
        [ 3, 19920901 ],
        [ 4, len(fieldList) ],
        [ 5 ] + fieldList,
        [ 6, ord('D') ],
        [ 10, ord('3') ]
    ]
   
    resultList = templateBlockRequest( cpClsDic[className], paramList, errLog = log )

    bFirst = 1
    for results in resultList :
        resultFile.write( getResultStringLandscape( results, 
                                                    statusOption = 0, 
                                                    headerValue = 0, #len(results[5]), 
                                                    dataValue = 1, #len(results[6]),
                                                    titleOption = bFirst ) )
        bFirst = 0
        
        #resultFile.write( getHeaderResultString(results[5], 1 ) )
        #resultFile.write( '\n' )
        #resultFile.write( getDataResultString(results[6], 1 ) )
        

    log.close()
    resultFile.close()

    del cpClsDic
예제 #15
0
    def loadLogData(self, stockCode, chartType ) :

        try :
            ct = self.chartTypeDic[chartType]
        except KeyError :
            print 'ERROR: cxEmulator.loadLogData : param chartType : "%s" is not valid.\n'%\
                    (chartType) 
            return None

        cpStockCode = self.cpClsDic['cxCpStockCode']

        stockName = cpStockCode.CodeToName(stockCode)
        #print '"%s"'%(stockName)
        if stockName == u'' :
            print 'Can not find stock name for stock code "%s".'%(stockCode)
            return

        path = 'log\\%s\\'%(chartType.lower())

        fileName = u'%s%s_%s.log'%(path,stockCode,stockName)

        print fileName 

        if checkFileExist(fileName) == False : return None

        dataFile = cxFile(fileName)

        tmpList = []
        dataList = []
        i = 0
        for lines in dataFile.readlines() :
            if i < 5 : 
                i += 1
                continue
            tmpList = []
            for item in lines[:-1].split() :
                tmpList.append(item)
            dataList.append(tmpList)
        dataFile.close()
        del dataFile

        #print 'len of dataList', len(dataList) 
        #print dataList[0]
        #print dataList[len(dataList)-1]
        return dataList
예제 #16
0
    def saveLogDataToFile(self, fileName=u"stockDayData.txt", condition=19910100):

        if (self.data == None) or (len(self.data) == 0):
            return False
        try:
            dataFile = cxFile(fileName)
        except BaseException as e:
            print e
            return False

        for stockCode, dayLog in self.data:
            dataFile.write("%s\n" % stockCode)
            for date, highPrice, lowPrice, currentPrice, tradingVolumn, tradingCost in dayLog:
                if date >= condition:
                    dataFile.write(
                        "\t%d %d %d %d %d %d\n" % (date, highPrice, lowPrice, currentPrice, tradingVolumn, tradingCost)
                    )
        dataFile.close()

        return True
예제 #17
0
    def update(self, argChartType, argStockCode, argClear=False, argFileName=u'') :
        # filtering chart type
        chartType = self.getChartType(argChartType)
        if chartType.result != u'ok' :
        #{
            return cxReturnValue(chartType.value, chartType.result)
        #}

        # filtering file name or set default file name
        fileName = u''
        if argFileName == u'' : # if there aren't specific file name
        #{
            dataFileName = self.getFileName(chartType.value, argStockCode)
            if dataFileName.result != u'ok' :
            #{
                return cxReturnValue(dataFileName.value, dataFileName.result)
            #}
            fileName = dataFileName.value
        #}
        else :  # specific file name are given.
        #{
            fileName = argFileName
        #}

        # filtering argClear
        if chartType.value == u'M' or chartType.value == u'W':
            argClear = True    

        dataFile = cxFile(fileName) 

        if argClear == True :   # delete file and update file
            if dataFile.isExist() == True :
                dataFile.delete()
            dataFile = cxFile(fileName)

        # call updateDataList
        import time

        if dataFile.isEmpty() == False :    # not empty
            # get last date time info from file
            lastDate = 19900101
            lastLine = dataFile.getLastLine()
            #####print u"'"+lastLine+u"'"
            #####print lastLine.split()
            if lastLine != None and lastLine != u'' :
                parsedDate = lastLine.split()[0]
                if parsedDate.isdigit() == True :
                    lastDate = common.getOneDayPlus(int(parsedDate))
            # request data from last date time to today.
            today = int(time.strftime('%Y%m%d'))
            todayTime = int(time.strftime('%H%M%S'))

            if (today > lastDate) or (today == lastDate and todayTime > 153000) :
                #오후 3시까지가 장 시간이지만,
                #데이타 정리가 될 때까지 기다리는 시간을 감안하여
                #오후 3시 30분까지 기다렸다가 update하려 함.
                requestArg = [lastDate, today]
                print '(',lastDate,'-',today,')',
                result = self.updateDataList( chartType.value,
                                              u'period',
                                              requestArg,
                                              0,
                                              self.fieldDic.keys(),
                                              argStockCode )
            else :
                result = cxReturnValue(None, u'invalid period (%d-%d)'%(lastDate,today))

            bFirstWrite = False

        else :  # empty file means new file
            # update all. (from 1900 ~ )
            reqType = u'period'
            requestArg = [19900101,int(time.strftime('%Y%m%d'))]
            
            if chartType.value == u'M' or chartType.value == u'W' :  # month
                reqType = u'count'
                requestArg = 2048
            
            print requestArg,
            result = self.updateDataList( chartType.value,
                                          reqType,
                                          requestArg,
                                          0,
                                          self.fieldDic.keys(),
                                          argStockCode )
            bFirstWrite = True

        # writing result to file

        if result.result != u'ok' :
            dataFile.close()
            del dataFile
            return cxReturnValue(result.value, result.result)
        else :
            fieldNameList = []
            lineList = []
            bFirst = True
            for resultList in result.value :
                #print common.getResultStringPortrait( resultList, 1, 1, 1, 1 )
                for itemDic in resultList[6] :
                    valueList = []
                    for key in itemDic.keys() :
                        if bFirst == True :
                            fieldNameList.append(itemDic[key][1])
                        valueList.append(itemDic[key][2])
                    lineList.append(valueList)
                    if bFirst == True :
                        bFirst = False

            if len(lineList) == 0 :
                dataFile.close()
                del dataFile
                return cxReturnValue(None,u'no data')

            print len(lineList),

            if bFirstWrite == True :
                for fieldName in fieldNameList :
                    dataFile.write(common.UNI(fieldName)+u' ')
                dataFile.write(u'\n')
                bFirstWrite = False

            for i in range(len(lineList)-1,-1,-1) :
                for value in lineList[i] :
                    dataFile.write(common.UNI(value) + u' ')
                dataFile.write(u'\n')

        # write results to file with reverse order.
        dataFile.close()
        del dataFile
        return cxReturnValue(fileName)
예제 #18
0
    def updateData(self,
                    argStockCode,
                    argChartType,
                    argFileName = u'') :
        import common
        import os
        cpStockCode = self.cpClsDic['cxCpStockCode']
        stockName = cpStockCode.CodeToName(argStockCode)
        if stockName == u'' :
            return E_FIND_STOCK_NAME
        chartType = self.getChartTypeParam(argChartType)
        if chartType == u'' :
            return E_FIND_CHART_TYPE
        if argFileName == u'' :
            path = u'log\\%s\\'%(chartType.lower())
            if os.path.exists(path) == False :
                os.makedirs(path)
            fileName = u'%s%s_%s.log' %\
                        ( path,
                          argStockCode,
                          stockName )
        else :
            fileName = argFileName
        if common.checkFileExist(fileName) == True :
            os.remove(fileName)
            #return W_FILE_EXIST
        
        fieldList = [
            0,  # 날짜
            1,  # 시간
            3,  # 고가
            4,  # 저가
            5,  # 종가
            8,  # 거래량
            9,  # 거래대금
        ]   # refer to CybosPlus manual
        
        paramList = [
            [   0,  argStockCode    ],
            [   1,  ord(u'1')       ],  # 기간요청
            [   3,  19500101        ],  # 1950.01.01 ~
#            [   3,  20121124        ],  # 1950.01.01 ~
            [   4,  len(fieldList)  ],
            [5] + fieldList          ,  # Field List
            [   6,  ord(chartType)  ],  # Chart Type
            [   9,  ord(u'1')       ],  # 수정주가
            [   10, ord(u'3')       ],  # 시간외 거래량 모두 제외
        ]
        stockChart = self.cpClsDic[u'cxStockChart']
        resultList = common.templateBlockRequest( stockChart,
                                                  paramList )
        if resultList == None :
            return E_BLOCKREQUEST_RESULT_NONE
        if len(resultList) == 0 :
            return E_BLOCKREQUEST_RESULT_BLANK
        
        
        #print common.dumpList(resultList)
        bFirstLoop = True
        dataNum = 0
        fieldNameList = []
        fileHeader = []
        fileData = []
        for result in resultList :
            #print common.getResultStringLandscape( result,
            #                                      statusOption=1,
            #                                      headerValue=1,
            #                                      dataValue=1,
            #                                      titleOption=1 )
            dibStatus = common.getResultDibStatus(result)
            if dibStatus != 0 :
                return E_DIB_STATUS
            dataList = common.getResultDataList(result)
            
            for dataDic in dataList :
                tempList = []
                for key in dataDic.keys() :
                    tempList.append(dataDic[key][2])
                    if bFirstLoop == True :
                        fieldNameList.append(dataDic[key][1])
                fileData.append(tempList)
                bFirstLoop = False
            fileHeader.append(fieldNameList)
        #end of 'for result in resultList :'
        #print common.dumpList(fieldNameList)
        #print common.dumpList(fileData)
        """
        [0] : field list
        [1] ~ : data
        """

        from cxFile import cxFile
        dataLogFile = cxFile(fileName)
        
        fieldNameString = u''
        for fieldName in fieldNameList :
            fieldNameString += fieldName + u' '
        fieldNameString += u'\n'
        dataLogFile.write(fieldNameString)
        #print fieldNameString
        
        for i in range(len(fileData)-1,-1,-1):
            itemString = u''
            itemList = fileData[i]
            for item in itemList :
                itemString += common.UNI(item) + u' '
            itemString += u'\n'
            dataLogFile.write(itemString)
            #print itemString
        dataLogFile.close()
        return 0 
예제 #19
0
    def makeLogData(self, stockCode, chartType ) :

        cpStockCode = self.cpClsDic['cxCpStockCode']
        stockName = cpStockCode.CodeToName(stockCode)
        #print '"%s"'%(stockName)
        if stockName == u'' :
            print 'Can not find stock name for stock code "%s".'%(stockCode)
            return False
        path = 'log\\%s\\'%(chartType.lower())
        fileName = u'%s%s_%s.log'%(path,stockCode,stockName)
        if checkFileExist(fileName) == True :
            return True
        try :
            ct = self.chartTypeDic[chartType]
        except KeyError :
            print 'ERROR: cxStockLogData.makeLogData : param chartType : "%s" is not valid.\n'%\
                    (chartType) 
            return False

        fieldList = [ 
            0, # 날짜
            1, # 시간
            3, # 고가
            4, # 저가
            5, # 종가
            8, # 거래량
            9, # 거래대금
            25, # 주식회전율
        ]

        #if ct == 'T' or ct == 'm' :
        #    fieldList += [1]  # 시간 - hhmm

        paramList = [
            [ 0,    stockCode       ],
            [ 1,    ord(u'1')       ],  # 기간요청
            [ 3,    19500101        ],
            [ 4,    len(fieldList)  ],
            [ 5 ] + fieldList,
            [ 6,    ord(ct)         ],  # 차트종류
            [ 9,    ord(u'1')       ],  # 수정주가
            [ 10,   ord(u'3')       ]   # 시간외거래량 모두 제외
        ]

        stockChart = getCybosPlusClassDic()[u'cxStockChart']

        resultList = templateBlockRequest( stockChart, paramList )

        if resultList == None :
            print 'templateBlockRequest("cxStockChart"): result is none.\n'
            return False

        if len(resultList) == 0 :
            print 'templateBlockRequest("cxStockChart") : result length is zero.\n'
            return False

        bFirst = 1
        fieldNum = 0
        storeList = []
        dataNum = 0

        for result in resultList :
            if getResultDibStatus(result) != 0 :
                break
            headerList = result[5]
            if len(headerList) == 0 :
                print 'header result is empty.'
                continue
            dataNum += headerList[0][3][2]
            print 'dataNum', dataNum, type(dataNum)
            if bFirst == 1 :
                fieldNum = headerList[0][1][2]
                fieldNameList = headerList[0][2][2]
                print 'fieldNum', fieldNum, type(fieldNum)
                print 'fieldNameList'
                for fieldName in fieldNameList :
                    print fieldName,
                print
                
                storeList.insert(3,fieldNum)
                storeList.insert(4,fieldNameList)

                bFirst = 0

            dataList = result[6]
            print 'len of dataList', len(dataList)

            if len(dataList) == 0 : 
                print 'failed to make data list for %s'%(stockCode)
                self.failedList.append([stockCode,chartType])
                return True
                #return False

            tmpList = []
            for dataDic in dataList :
                tmpList = [] 
                for fieldType in range( 0, fieldNum ) :
                    key = stockChart.fieldNameDic[fieldNameList[fieldType]]
                    tmpList.append( dataDic[key][2] )
                storeList.append(tmpList)


        storeList.insert(0,dataNum)
        storeList.insert(1,storeList[len(storeList)-1][0])
        storeList.insert(2,storeList[4][0])
        print 'len of storeList',len(storeList)
        #print storeList

        """
        [0] : dataNum
        [1] : start date
        [2] : end date
        [3] : fieldNum
        [4] : field Name List
        [5] ~ : data
        """

        print fileName 

        dataFile = cxFile(fileName)

        dataFile.write('%s\n'%(storeList[0]))
        dataFile.write('%s\n'%(storeList[1]))
        dataFile.write('%s\n'%(storeList[2]))
        dataFile.write('%s\n'%(storeList[3]))

        for fieldName in storeList[4] :
            dataFile.write('%s\t'%(fieldName))
        dataFile.write('\n')
        tmpList = storeList[5:]
        tmpList.reverse()
        for itemList in tmpList :
            for item in itemList :
                dataFile.write('%s\t'%(item))
            dataFile.write('\n')

        dataFile.close()
        del dataFile

        return True
예제 #20
0
def test_getStockDayData() :

    from cxCybosPlus import cxCpStockCode

    from cxFile import cxFile

    #stockCode = u'A000660'  #하이닉스
    #stockCode = u'A005930'  #삼성전자
    stockCode = u'A005380'  #현대자동차
    #stockCode = u'A004990'  #롯데제과

    cpStockCode = cxCpStockCode()

    stockName = cpStockCode.CodeToName(stockCode)

    chartType = u'D'

    fileName = u'%s_%s_%s.log'%(stockCode, stockName, chartType)

    refreshLog = 1 
    
    if refreshLog == 1 :

        resultFile = cxFile(fileName)
   
        fieldList = [ 
            0, # 날짜
            3, # 고가
            4, # 저가
            5, # 종가
            8, # 거래량
            9, # 거래대금
            25, # 주식회전율
        ]

        paramList = [
            [ 0, stockCode ],
            [ 1, ord(u'1') ],
            [ 3, 19920901 ],
            [ 4, len(fieldList) ],
            [ 5 ] + fieldList,
            [ 6, ord(chartType) ],
            [ 9, ord(u'1') ],        # 수정주가
            [ 10, ord(u'3') ]
        ]

        testBlockRequest(u'cxStockChart', paramList, 0, 0, 1, 1, resultFile )

        resultFile.close()
    
    
    resultFile = cxFile(fileName)

    lines = resultFile.readlines()

    """
    value = lines[1].split(u'\t')
    print value
    print value[0], value[3]
    """

    dataLog = []
    
    for i in range(0, len(lines)) :
        if i == 0 : continue
        value = lines[i].split(u'\t')
        #print value[0],value[3]
        dataLog.append( [ value[0], value[3] ] )
    
    resultFile.close()

    dataLogLen = len(dataLog)

    print dataLogLen
    flagBuy = False

    earningMoney = 0

    resultFile = cxFile()
    buyCount = 0
    buyedMoney = 0
    maxBuyedMoney = 0

    for i in range(dataLogLen -1 -20, -1, -1 ) :
        currentValue = int(dataLog[i][1])
        avr = 0
        total = 0
        maxValue = 0
        minValue = 10000000000
        #resultFile.write(u'%d\t'%(i))
        resultFile.write(u'%s\t'%(dataLog[i][0]))
        for j in range(i+20,i,-1) :
            oldValue = int(dataLog[j][1])
            #resultFile.write(u'%d(%s,%d),'%(j,dataLog[i][0],oldValue))
            total += oldValue
            if maxValue < oldValue :
                maxValue = oldValue
            if minValue > oldValue :
                minValue = oldValue
        resultFile.write(u' ')
        avr = int(total/20)
        resultFile.write(u'current:%d,avr:%d,20s min:%d,20s max:%d\n'%( currentValue,
                                                                      avr,
                                                                      minValue,
                                                                      maxValue))
        if (currentValue > maxValue) and (flagBuy == False) :
            resultFile.write(u'BUY at cv:%d for mv:%d in bm:%d (em:%d, bc:%d)\n'%( currentValue, 
                                                                maxValue, 
                                                                buyedMoney,
                                                                earningMoney,
                                                                buyCount))
            flagBuy = True
            buyedMoney += currentValue
            buyCount += 1
            maxBuyedMoney = max(maxBuyedMoney, buyedMoney)
        elif flagBuy == True and currentValue < minValue :
            earningMoney += (currentValue*buyCount)-buyedMoney
            resultFile.write(u'SELL at cv:%d for mv:%d in bm:%d (em:%d, bc:%d)\n'%( currentValue, 
                                                                 minValue, 
                                                                 buyedMoney,
                                                                 earningMoney,
                                                                 buyCount))
            flagBuy = False
            buyCount = 0
            buyedMoney = 0

    resultFile.write(u'earned Money :%d, max buyed money : %d, (%f)\n'%(earningMoney,
                                                                  maxBuyedMoney,
                                                                  float(earningMoney)/float(maxBuyedMoney)*(100.0)))
    resultFile.write(u'%s~%s:%d~%d(%d)\n'%( dataLog[dataLogLen-1][0],
                                            dataLog[0][0],
                                            int(dataLog[dataLogLen-1][1]),
                                            int(dataLog[0][1]),
                                            int(int(dataLog[0][1])/int(dataLog[dataLogLen-1][1]))))

    print
예제 #21
0
    def testStrategy006(self, dataList ) :

        resultFile = cxFile('log\\day\\st06.txt')
        dataListLen = len(dataList)

        if dataListLen == 0 :
            print 'data가 없습니다.'
            return

        desc = u'현재가가\n20일 고가의 75%에서 사서, 20일 저가의 125%에서 판다.\n'                     
        flagBuy = False
        earningMoney = 0
        buyCount = 0
        buyedMoney = 0
        maxBuyedMoney = 0

        for i in range( 20, dataListLen ) :
            data = dataList[i]
            date = data[0]
            currentValue = int(data[3])
            avr = 0
            total = 0
            maxValue = 0
            minValue = 10000000000
            for j in range( i - 20, i ) :
                oldValue = int(dataList[j][3])
                total += oldValue
                if maxValue < oldValue :
                    maxValue = oldValue
                if minValue > oldValue :
                    minValue = oldValue
            avr = int(total/20)
            resultFile.write(u'%s:current:%d,avr:%d,20s min:%d,20s max:%d\n'%(date,
                                                                      currentValue,
                                                                      avr,
                                                                      minValue,
                                                                      maxValue))
            buyValue = int(float(maxValue)*0.75)
            sellValue = int(float(minValue)*1.25)
            if (currentValue > buyValue )and (flagBuy == False ) :
                resultFile.write(u'BUY at cv:%d > bv:%d in bm:%d (em:%d, bc:%d)\n' \
                                                            %(currentValue,
                                                              buyValue,
                                                              buyedMoney,
                                                              earningMoney,
                                                              buyCount))
                flagBuy = True
                buyedMoney = currentValue
                buyCount += 1
                maxBuyedMoney = max(maxBuyedMoney, buyedMoney)

            elif flagBuy == True and  \
                 ( currentValue > sellValue ) :
                 #(currentValue < sellValue ) :
                earningMoney += (currentValue*buyCount)-buyedMoney
                resultFile.write(u'SELL at cv:%d < sv:%d in bm:%d (em:%d, bc:%d)\n'%
                                                               ( currentValue, 
                                                                 sellValue,
                                                                 buyedMoney,
                                                                 earningMoney,
                                                                 buyCount))
                flagBuy = False
                buyCount = 0
                buyedMoney = 0



        resultFile.write(u'earned Money :%d, max buyed money : %d, (%f)\n'%(earningMoney,
                                            maxBuyedMoney,
                                            float(earningMoney)/float(maxBuyedMoney)*(100.0)))
        resultFile.write(u'%s~%s:%d~%d(%d)\n'%( dataList[0][0],
                                            dataList[dataListLen-1][0],
                                            int(dataList[0][3]),
                                            int(dataList[dataListLen-1][3]),
                                int(int(dataList[dataListLen-1][3])/int(dataList[0][3]))))

        resultFile.write(desc)
        resultFile.close()
        print
예제 #22
0
    def testStrategy005(self, dataList ) :

        resultFile = cxFile('log\\day\\st05.txt')
        dataListLen = len(dataList)

        if dataListLen == 0 :
            print 'data가 없습니다.'
            return

        desc = u'현재가가\n산 가격의 20% 이상 오를 때 이익실현하고\n산 가격의 5% 이하일 때 청산한다.'                     
        flagBuy = False
        earningMoney = 0
        buyCount = 0
        buyedMoney = 0
        maxBuyedMoney = 0

        for i in range( 20, dataListLen ) :
            data = dataList[i]
            date = data[0]
            currentValue = int(data[3])
            avr = 0
            total = 0
            maxValue = 0
            minValue = 10000000000
            for j in range( i - 20, i ) :
                oldValue = int(dataList[j][3])
                total += oldValue
                if maxValue < oldValue :
                    maxValue = oldValue
                if minValue > oldValue :
                    minValue = oldValue
            avr = int(total/20)
            resultFile.write(u'%s:current:%d,avr:%d,20s min:%d,20s max:%d\n'%(date,
                                                                      currentValue,
                                                                      avr,
                                                                      minValue,
                                                                      maxValue))

            if (currentValue > maxValue) and (flagBuy == False ) :
                resultFile.write(u'BUY at cv:%d for mv:%d in bm:%d (em:%d, bc:%d)\n' \
                                                            %(currentValue,
                                                              maxValue,
                                                              buyedMoney,
                                                              earningMoney,
                                                              buyCount))
                flagBuy = True
                buyedMoney = currentValue
                buyCount += 1
                maxBuyedMoney = max(maxBuyedMoney, buyedMoney)

            elif flagBuy == True and  \
                 ( currentValue > int(float(buyedMoney)*1.2) ) :
                earningMoney += (currentValue*buyCount)-buyedMoney
                resultFile.write(u'SELL at cv:%d for av:%d in > bm:%d (em:%d, bc:%d)\n'%
                                                               ( currentValue, 
                                                                 avr, 
                                                                 int(float(buyedMoney)*1.2),
                                                                 earningMoney,
                                                                 buyCount))
                flagBuy = False
                buyCount = 0
                buyedMoney = 0

            elif flagBuy == True and \
                 ( currentValue < int(float(buyedMoney)*0.95) ):
                earningMoney += (currentValue*buyCount)-buyedMoney
                resultFile.write(u'SELL at cv:%d for av:%d in < bm:%d (em:%d, bc:%d)\n'%
                                                               ( currentValue, 
                                                                 avr, 
                                                                 int(float(buyedMoney)*0.95),
                                                                 earningMoney,
                                                                 buyCount))
                flagBuy = False
                buyCount = 0
                buyedMoney = 0

        resultFile.write(u'earned Money :%d, max buyed money : %d, (%f)\n'%(earningMoney,
                                            maxBuyedMoney,
                                            float(earningMoney)/float(maxBuyedMoney)*(100.0)))
        resultFile.write(u'%s~%s:%d~%d(%d)\n'%( dataList[0][0],
                                            dataList[dataListLen-1][0],
                                            int(dataList[0][3]),
                                            int(dataList[dataListLen-1][3]),
                                int(int(dataList[dataListLen-1][3])/int(dataList[0][3]))))

        resultFile.write(desc)
        resultFile.close()
        print
예제 #23
0
def test_getStockDayData() :

    from cxCybosPlus import cxCpStockCode

    from cxFile import cxFile

    #stockCode = u'A000660'  #하이닉스
    #stockCode = u'A005930'  #삼성전자
    stockCode = u'A005380'  #현대자동차
    #stockCode = u'A004990'  #롯데제과

    cpStockCode = cxCpStockCode()

    stockName = cpStockCode.CodeToName(stockCode)

    chartType = u'D'

    fileName = u'%s_%s_%s.log'%(stockCode, stockName, chartType)

    refreshLog = 1 
    
    if refreshLog == 1 :

        resultFile = cxFile(fileName)
   
        fieldList = [ 
            0, # 날짜
            3, # 고가
            4, # 저가
            5, # 종가
            8, # 거래량
            9, # 거래대금
            25, # 주식회전율
        ]

        paramList = [
            [ 0, stockCode ],
            [ 1, ord(u'1') ],
            [ 3, 19920901 ],
            [ 4, len(fieldList) ],
            [ 5 ] + fieldList,
            [ 6, ord(chartType) ],
            [ 9, ord(u'1') ],        # 수정주가
            [ 10, ord(u'3') ]
        ]

        testBlockRequest(u'cxStockChart', paramList, 0, 0, 1, 1, resultFile )

        resultFile.close()
    
    
    resultFile = cxFile(fileName)

    lines = resultFile.readlines()

    """
    value = lines[1].split(u'\t')
    print value
    print value[0], value[3]
    """

    dataLog = []
    
    for i in range(0, len(lines)) :
        if i == 0 : continue
        value = lines[i].split(u'\t')
        #print value[0],value[3]
        dataLog.append( [ value[0], value[3] ] )
    
    resultFile.close()

    dataLogLen = len(dataLog)

    print dataLogLen
    flagBuy = False

    earningMoney = 0

    resultFile = cxFile()
    buyCount = 0
    buyedMoney = 0
    maxBuyedMoney = 0

    for i in range(dataLogLen -1 -20, -1, -1 ) :
        currentValue = int(dataLog[i][1])
        avr = 0
        total = 0
        maxValue = 0
        minValue = 10000000000
        #resultFile.write(u'%d\t'%(i))
        resultFile.write(u'%s\t'%(dataLog[i][0]))
        for j in range(i+20,i,-1) :
            oldValue = int(dataLog[j][1])
            #resultFile.write(u'%d(%s,%d),'%(j,dataLog[i][0],oldValue))
            total += oldValue
            if maxValue < oldValue :
                maxValue = oldValue
            if minValue > oldValue :
                minValue = oldValue
        resultFile.write(u' ')
        avr = int(total/20)
        resultFile.write(u'current:%d,avr:%d,20s min:%d,20s max:%d\n'%( currentValue,
                                                                      avr,
                                                                      minValue,
                                                                      maxValue))
        if (currentValue > maxValue) and (flagBuy == False) :
            resultFile.write(u'BUY at cv:%d for mv:%d in bm:%d (em:%d, bc:%d)\n'%( currentValue, 
                                                                maxValue, 
                                                                buyedMoney,
                                                                earningMoney,
                                                                buyCount))
            flagBuy = True
            buyedMoney += currentValue
            buyCount += 1
            maxBuyedMoney = max(maxBuyedMoney, buyedMoney)
        elif flagBuy == True and currentValue < minValue :
            earningMoney += (currentValue*buyCount)-buyedMoney
            resultFile.write(u'SELL at cv:%d for mv:%d in bm:%d (em:%d, bc:%d)\n'%( currentValue, 
                                                                 minValue, 
                                                                 buyedMoney,
                                                                 earningMoney,
                                                                 buyCount))
            flagBuy = False
            buyCount = 0
            buyedMoney = 0

    resultFile.write(u'earned Money :%d, max buyed money : %d, (%f)\n'%(earningMoney,
                                                                  maxBuyedMoney,
                                                                  float(earningMoney)/float(maxBuyedMoney)*(100.0)))
    resultFile.write(u'%s~%s:%d~%d(%d)\n'%( dataLog[dataLogLen-1][0],
                                            dataLog[0][0],
                                            int(dataLog[dataLogLen-1][1]),
                                            int(dataLog[0][1]),
                                            int(int(dataLog[0][1])/int(dataLog[dataLogLen-1][1]))))

    print
예제 #24
0
    def testStrategy001(self, dataList ) :

        resultFile = cxFile('log\\day\\st01.txt')
        dataListLen = len(dataList)

        if dataListLen == 0 :
            print 'data가 없습니다.'
            return

        desc = u'현재가가\n20일 고가보다 높을 때 사고,\n20일 저가보다 낮을 때 판다.\n'                     
        flagBuy = False
        earningMoney = 0
        buyCount = 0
        buyedMoney = 0
        maxBuyedMoney = 0

        for i in range( 20, dataListLen ) :
            data = dataList[i]
            date = data[0]
            currentValue = int(data[4])
            avr = 0
            total = 0
            maxValue = 0
            minValue = 10000000000
            for j in range( i - 20, i ) :
                oldValue = int(dataList[j][3])
                total += oldValue
                if maxValue < oldValue :
                    maxValue = oldValue
                if minValue > oldValue :
                    minValue = oldValue
            avr = int(total/20)
            resultFile.write(u'%s:current:%d,avr:%d,20s min:%d,20s max:%d\n'%(date,
                                                                      currentValue,
                                                                      avr,
                                                                      minValue,
                                                                      maxValue))

            if (currentValue > maxValue) and (flagBuy == False ) :
                resultFile.write(u'BUY at cv:%d for mv:%d in bm:%d (em:%d, bc:%d)\n' \
                                                            %(currentValue,
                                                              maxValue,
                                                              buyedMoney,
                                                              earningMoney,
                                                              buyCount))
                flagBuy = True
                buyedMoney += currentValue
                buyCount += 1
                maxBuyedMoney = max(maxBuyedMoney, buyedMoney)
            elif flagBuy == True and currentValue < minValue :
                earningMoney += (currentValue*buyCount)-buyedMoney
                resultFile.write(u'SELL at cv:%d for mv:%d in bm:%d (em:%d, bc:%d)\n'%( currentValue, 
                                                                 minValue, 
                                                                 buyedMoney,
                                                                 earningMoney,
                                                                 buyCount))
                flagBuy = False
                buyCount = 0
                buyedMoney = 0

        resultFile.write(u'earned Money :%d, max buyed money : %d, (%f)\n'%(earningMoney,
                                            maxBuyedMoney,
                                            float(earningMoney)/float(maxBuyedMoney)*(100.0)))
        resultFile.write(u'%s~%s:%d~%d(%d)\n'%( dataList[0][0],
                                            dataList[dataListLen-1][0],
                                            int(dataList[0][4]),
                                            int(dataList[dataListLen-1][4]),
                                int(int(dataList[dataListLen-1][4])/int(dataList[0][4]))))
        resultFile.write(desc)
        resultFile.close()
        print
예제 #25
0
def save_data_of_turtle_trading_per_stock() :

    S1_entryCondition = 20
    S1_exitCondition = 10
    S2_entryCondition = 55
    S2_exitCondition = 20
    N_condition = 20

    stockDayData = cxStockDayData()

    print 'start : load stockDayData'
    rawDataList = stockDayData.loadLogDataFromFile(fileName = \
                                    u'cxStockDayDataRemovedNotTradingStock.dat')
    print 'end : load stockDayData'

    if rawDataList == None :
        print 'loading stockDayData : failed'
        return None

    #remove_not_trading_stocks(rawDataList)

    turtleDataPerStockFile = cxFile(u'turtleDataPerStockFile.txt')
    
    stockNum = len(rawDataList)

    #stockNum = 1

    for stockIndex in range(0,stockNum) :
        turtleDataPerStockFile.write(u'%s\n'%rawDataList[stockIndex][0])
        
        dayDataList = rawDataList[stockIndex][1]
        dayDataLen = len(dayDataList)

        for dayIndex in range(0, dayDataLen) :
            ( currentDate, currentMaxPrice, currentMinPrice, 
              currentClosingPrice, currentTradingVolumn, currentTradingCost ) = \
              dayDataList[dayIndex]

            S1_entryPrice = 0
            S1_exitPrice = 0
            S2_entryPrice = 0
            S2_exitPrice = 0
            n = 0               # 오늘의 변동성
            N = 0.0

            if dayIndex >= 1 :
                ( prevDate, prevMaxPrice, prevMinPrice, prevClosingPrice,
                    prevTradingVolumn, prevTradingCost ) = dayDataList[dayIndex-1]

                n = max( [ fabs( currentMaxPrice - currentMinPrice ),
                           fabs( currentMaxPrice - prevClosingPrice ),
                           fabs( prevClosingPrice - currentMinPrice ) ] )

            if dayIndex >= S1_entryCondition :
                S1_entryPrice = \
                    max( [ maxPrice 
                            for date, maxPrice, minPrice, closingPrice,
                                tradingVolumn, tradingCost 
                            in  dayDataList[(dayIndex-S1_entryCondition):dayIndex] ] )

            if dayIndex >= S1_exitCondition :
                S1_exitPrice = \
                    min( [ minPrice 
                            for date, maxPrice, minPrice, closingPrice,
                                tradingVolumn, tradingCost
                            in  dayDataList[(dayIndex-S1_exitCondition):dayIndex] ] )

            if dayIndex >= S2_entryCondition :
                S2_entryPrice = \
                    max( [ maxPrice
                            for date, maxPrice, minPrice, closingPrice,
                                tradingVolumn, tradingCost
                            in  dayDataList[(dayIndex-S2_entryCondition):dayIndex] ] )
            
            if dayIndex >= S2_exitCondition :
                S2_exitPrice = \
                    min( [ minPrice
                            for date, maxPrice, minPrice, closingPrice,
                                tradingVolumn, tradingCost
                            in  dayDataList[(dayIndex-S2_exitCondition):dayIndex] ] )

            if dayIndex >= ( N_condition + 1 ) :

                N = calculate_N( [ [ maxPrice, minPrice, closingPrice ]
                                   for date, maxPrice, minPrice, closingPrice,
                                       tradingVolumn, tradingCost
                                   #in  dayDataList[(dayIndex-N_condition-1):dayIndex] ] , 
                                   in  dayDataList[(dayIndex-N_condition):dayIndex+1] ] , 
                                 N_condition )

            turtleDataPerStockFile.write(u'\t%d %d %d %d %d %d %d %d %d %f\n' \
                    % ( currentDate, currentMaxPrice, currentMinPrice, currentClosingPrice,
                        S1_entryPrice, S1_exitPrice, S2_entryPrice, S2_exitPrice, n, N ) )
   
    del rawDataList
    turtleDataPerStockFile.close()
예제 #26
0
def loadSubscribeStockList() :
    #import os
    subFile = cxFile(u'subStockList.cfg')
    subStockList = [stock.rstrip(u'\r\n') for stock in filter(lambda x : x!=u'\r\n',subFile.readlines())]    
    # os.sep can be used.
    return subStockList
예제 #27
0
def RapidSnowBall() :
    reportQueue = Queue()
    conclusionQueue = Queue()
    resultFile = cxFile()

    cpTdUtil = gCybosPlusClassDic['cxCpTdUtil']
    result = cpTdUtil.TradeInit()

    if result != 0 :
        resultString = u'cpTdUtil.init failed'
        resultFile.write(resultString)
        return

    accountList = cpTdUtil.AccountNumber()
    goodsList = cpTdUtil.GoodsList(accountList[0],3)

    cpConclusion = gCybosPlusClassDic['cxCpConclusion']
    cpConclusion.open()
    cpConclusion.set_result_queue(conclusionQueue)
    cpConclusion.Subscribe()

    cpTd0311 = gCybosPlusClassDic['cxCpTd0311']
    cpTd0311.open()
    cpTd0311.set_result_queue(reportQueue)

    # TODO :initial subscribe
    subscribeStockList = loadSubscribeStockList()

    #if len(subscribeStockList) :
        

    while True :
        #if reportQueue.qsize() != 0 :
            #resultList = reportQueue.get()
            #resultString = getResultStringPortrait(resultList, 1, 1, 1, 1)
            #resultFile.write(resultString)

        # TODO : if it gets some value changes, 
        #           determines whether buy or sell.
        #           determines stockCode, amount, unitPrice, tradeCondition,
        #           tradType also.
        # TODO : if it determines to buy, buy it.
        # TODO : if it determines to sell, sell it.
            
            #cpTd0311.SetInputValue(0, 1 or 2 ) # 1 : sell, 2 : buy
            #cpTd0311.SetInputValue(1, accountList[0])
            #cpTd0311.SetInputValue(2, goodsList[0])
            #cpTd0311.SetInputValue(3, stockCode)       # stockCode
            #cpTd0311.SetInputValue(4, amount)          # amount
            #cpTd0311.SetInputValue(5, unitPrice)       # unitPrice
            #cpTd0311.SetInputValue(7, tradeCondition)  # tradeCondition
            #cpTd0311.SetInputValue(8, tradeType)       # tradeType

            #result = cpTd0311.Request()
            #print 'result', result
            #print 'GetDibStatus', cpTd0311.GetDibStatus()
            #print 'GetDibMsg1', cpTd0311.GetDibMsg1()
            #bContinue = cpTd0311.Continue()
            #print 'Continue', bContinue 
            #if bContinue == 1 :
            #   cpTd0311.Request()

        if conclusionQueue.qsize() != 0 :
            resultList = conclusionQueue.get()
            resultString = getResultStringPortrait(resultList, 1, 1, 1, 1)
            print resultString
            resultFile.write(resultString)
        
        # TODO : check the loop-end conditions.
        #           keystroke or some other conditions.

        win32gui.PumpWaitingMessages()
        #time.sleep(1) 
        time.sleep(0.01) #0.01  for 10 msec.

    resultFile.close()
    cpTd0311.close()

    cpConclusion.Unsubscribe()
    cpConclusion.close()
예제 #28
0
 def loadSubscribeStockList(self) :
     subFile = cxFile(u'subStockList.cfg')
     self.subStockList = [stock.rstrip(u'\r\n') for stock \
             in filter(lambda x : x!=u'\r\n', subFile.readlines())]
예제 #29
0
def test_turtle_trading_per_stock(fileName = u'turtleDataPerStockFile.txt') :
   
    initTotalAsset = 5000000
    totalAsset = initTotalAsset

    stockCode = u''
    bFirst = True

    wishList = cxList()
    purchasedList = cxList()
    goodsList = cxList()
    transactionList = cxList()

    resultFile = cxFile()

    for line in open(fileName) :
        strDataList = line.split()
        if len(strDataList) == 1 :
            if stockCode != strDataList[0] :
                if bFirst == True :
                    stockCode = strDataList[0]
                    bFirst = False
                else :
                    # calculating result of turtle trading for stockCode
                    # clean or reset the data for turtle trading
                    if purchasedList.has(stockCode) :
                        sellingList = purchasedList.getListOf(stockCode)
                        totalPurchasedNum = 0
                        totalPurchasedPrice = 0
                        for code, num, price, n_entryPrice, n_exitPrice in sellingList :
                            totalPurchasedNum += num
                        totalPurchasedPrice = totalPurchasedNum * closingPrice
                        totalAsset += totalPurchasedPrice
                        purchasedList.delete(stockCode,1)
                        resultFile.write( u'\t%s %s %s %d %d\n'% \
                                          ('now','total',stockCode,totalPurchasedPrice,totalAsset))
                    wishList.delete(stockCode)
                    goodsList.delete(stockCode)
                    stockCode = strDataList[0]
                    totalAsset = initTotalAsset

        else :  
            #print 'purchasedList len', purchasedList.len() 
            #for item in purchasedList.dataList :
            #    resultFile.write(u'%s %d %d %f %f\n'%(item[0],item[1],item[2],item[3],item[4]))
            # process turtle trading
            ( date, maxPrice, minPrice, closingPrice, S1_entryPrice, S1_exitPrice,
              S2_entryPrice, S2_exitPrice, n, N ) = strDataList
            maxPrice = int(maxPrice)
            minPrice = int(minPrice)
            closingPrice = int(closingPrice)
            S1_entryPrice = int(S1_entryPrice)
            S1_exitPrice = int(S1_exitPrice)
            S2_entryPrice = int(S2_entryPrice)
            S2_exitPrice = int(S2_exitPrice)
            n = int(n)
            N = float(N)

            #print stockCode,
            #print date,maxPrice,minPrice,closingPrice,
            #print S1_entryPrice,S1_exitPrice,S2_entryPrice,S2_exitPrice,n,N
            
            if wishList.has(stockCode) :
                entryPrice = wishList.getListOf(stockCode)[0][-2]
                condition = wishList.getListOf(stockCode)[0][-1]
                # calculate max trading cost
                maxTradingCost = 100000 #int(totalAsset * 0.02)
                # calculate unit for max risk cost
                unit = int(maxTradingCost * 0.02)
                # calculate stock num to buy.
                if N == 0 :
                    wishList.delete(stockCode,1)
                    continue
                stockNum = int(unit/N)
                # calculate transaction cost.
                #purchasedPrice = maxPrice
                purchasedPrice = closingPrice
                transactionCost = stockNum * purchasedPrice
                if transactionCost > maxTradingCost :
                    stockNum = int(maxTradingCost/purchasedPrice)
                    transactionCost = stockNum * purchasedPrice
                # add transaction info. to transaction list
                transactionList.add( [ 'buy', stockCode, stockNum, purchasedPrice,
                                        purchasedPrice + N,
                                        purchasedPrice - 2*N ] )
                purchasedList.add( [ stockCode, stockNum, purchasedPrice,
                                     purchasedPrice + N,
                                     purchasedPrice - 2*N ] )

                #wishList.pop(stockCode)
                wishList.delete(stockCode,1)
                totalAsset -= transactionCost

                resultFile.write( u'\t%s %s %s %d %s %dx%d=%d, %d, %d, %d\n'% \
                                    (date,'buy ', condition, entryPrice, stockCode,stockNum,purchasedPrice,
                                     transactionCost,unit,maxTradingCost,totalAsset) )
            # end of if wishList.has(stockCode)

            if goodsList.has(stockCode) :
                exitPrice = goodsList.getListOf(stockCode)[0][-2]
                condition = goodsList.getListOf(stockCode)[0][-1]
                # get stock list from purhcased list
                stockList = purchasedList.getListOf( stockCode )
                # get total stock num from stock list
                totalPurchasedNum = 0
                totalPurchasedPrice = 0
                for code, num, price, n_entryPrice, n_exitPrice in stockList :
                    totalPurchasedNum += num
                    totalPurchasedPrice += num * price
                # calculated total earning price by selling
                #sellPrice = minPrice
                sellPrice = closingPrice
                earningPrice = sellPrice * totalPurchasedNum
                # add transaction info. to transaction list
                transactionList.add( [ 'sell', stockCode, totalPurchasedNum, sellPrice ] )
                                          
                # delete stock in purchased list
                purchasedList.delete(stockCode,1)
                goodsList.delete(stockCode,1)
                totalAsset += earningPrice
                resultFile.write( u'\t%s %s %s %d %s %dx%d=%d, %d, %d\n'% \
                                    (date,'sell',condition,exitPrice,
                                     stockCode,totalPurchasedNum,sellPrice,
                                     earningPrice,earningPrice-totalPurchasedPrice,
                                     totalAsset) )
            # end of if goodsList.has(stockCode)

            if closingPrice > S1_entryPrice :
                wishList.add( [ stockCode, closingPrice, S1_entryPrice, 'S1_entry' ] )
            # end of if closingPrice > S1_entryPrice
            if closingPrice > S2_entryPrice :
                wishList.add( [ stockCode, closingPrice, S2_entryPrice, 'S2_entry' ] )
            # end of if closingPrice > S2_entryPrice


            if purchasedList.has( stockCode ) :
                stockDataList = purchasedList.getListOf( stockCode )
                #print purchasedList.has(stockCode)
                #print stockDataList[0]
                ( purchasedStockCode, purchasedStockNum, purchasedStockPrice,   \
                  purchasedN_entryPrice, purchasedN_exitPrice ) = stockDataList[-1]
                if closingPrice > purchasedN_entryPrice :
                    wishList.add( [ stockCode, closingPrice, purchasedN_entryPrice, 'N_entry' ] )
                if closingPrice < S1_exitPrice :
                    goodsList.add( [ stockCode, closingPrice, S1_exitPrice, 'S1_exit' ] )
                if closingPrice < S2_exitPrice :
                    goodsList.add( [ stockCode, closingPrice, S2_exitPrice, 'S2_exit' ] )
                if closingPrice < purchasedN_exitPrice  :
                    goodsList.add( [ stockCode, closingPrice, purchasedN_exitPrice, 'N_exit' ] )
            # end of if purchasedList.has(stockCode)

    # end of for statement

    resultFile.close()
예제 #30
0
    def makeLogData(self, stockCode, chartType ) :

        cpStockCode = self.cpClsDic['cxCpStockCode']

        stockName = cpStockCode.CodeToName(stockCode)
        #print '"%s"'%(stockName)
        if stockName == u'' :
            print 'Can not find stock name for stock code "%s".'%(stockCode)
            return False

        path = 'log\\%s\\'%(chartType.lower())

        fileName = u'%s%s_%s.log'%(path,stockCode,stockName)

        if checkFileExist(fileName) == True :
            return True

        try :
            ct = self.chartTypeDic[chartType]
        except KeyError :
            print 'ERROR: cxEmulator.makeLogData : param chartType : "%s" is not valid.\n'%\
                    (chartType) 
            return False

        fieldList = [ 
            0, # 날짜
            1, # 시간
            3, # 고가
            4, # 저가
            5, # 종가
            8, # 거래량
            9, # 거래대금
            25, # 주식회전율
        ]

        #if ct == 'T' or ct == 'm' :
        #    fieldList += [1]  # 시간 - hhmm

        paramList = [
            [ 0,    stockCode       ],
            [ 1,    ord(u'1')       ],  # 기간요청
            [ 3,    19500101        ],
            [ 4,    len(fieldList)  ],
            [ 5 ] + fieldList,
            [ 6,    ord(ct)         ],  # 차트종류
            [ 9,    ord(u'1')       ],  # 수정주가
            [ 10,   ord(u'3')       ]   # 시간외거래량 모두 제외
        ]

        stockChart = getCybosPlusClassDic()[u'cxStockChart']

        resultList = templateBlockRequest( stockChart, paramList )

        if resultList == None :
            print 'templateBlockRequest("cxStockChart"): result is none.\n'
            return False

        if len(resultList) == 0 :
            print 'templateBlockRequest("cxStockChart") : result length is zero.\n'
            return False

        bFirst = 1
        fieldNum = 0
        storeList = []
        dataNum = 0

        for result in resultList :
            if getResultDibStatus(result) != 0 :
                break
            headerList = result[5]
            if len(headerList) == 0 :
                print 'header result is empty.'
                continue
            dataNum += headerList[0][3][2]
            print 'dataNum', dataNum, type(dataNum)
            if bFirst == 1 :
                fieldNum = headerList[0][1][2]
                fieldNameList = headerList[0][2][2]
                print 'fieldNum', fieldNum, type(fieldNum)
                print 'fieldNameList'
                for fieldName in fieldNameList :
                    print fieldName,
                print
                
                storeList.insert(3,fieldNum)
                storeList.insert(4,fieldNameList)

                bFirst = 0

            dataList = result[6]
            print 'len of dataList', len(dataList)

            if len(dataList) == 0 : 
                print 'failed to make data list for %s'%(stockCode)
                self.failedList.append([stockCode,chartType])
                return True
                #return False

            tmpList = []
            for dataDic in dataList :
                tmpList = [] 
                for fieldType in range( 0, fieldNum ) :
                    key = stockChart.fieldNameDic[fieldNameList[fieldType]]
                    tmpList.append( dataDic[key][2] )
                storeList.append(tmpList)


        storeList.insert(0,dataNum)
        storeList.insert(1,storeList[len(storeList)-1][0])
        storeList.insert(2,storeList[4][0])
        print 'len of storeList',len(storeList)
        #print storeList

        """
        [0] : dataNum
        [1] : start date
        [2] : end date
        [3] : fieldNum
        [4] : field Name List
        [5] ~ : data
        """


        print fileName 

        dataFile = cxFile(fileName)

        dataFile.write('%s\n'%(storeList[0]))
        dataFile.write('%s\n'%(storeList[1]))
        dataFile.write('%s\n'%(storeList[2]))
        dataFile.write('%s\n'%(storeList[3]))

        for fieldName in storeList[4] :
            dataFile.write('%s\t'%(fieldName))
        dataFile.write('\n')
        tmpList = storeList[5:]
        tmpList.reverse()
        for itemList in tmpList :
            for item in itemList :
                dataFile.write('%s\t'%(item))
            dataFile.write('\n')

        dataFile.close()
        del dataFile

        return True
예제 #31
0
파일: testSim.py 프로젝트: ClarkOh/snowball
def testCalculateStochaostic() :
    from cxFile import cxFile
    dataPath = u'database\\day\\'
    data1FileName = u'A005930.data' #u'A000660.data' #u'A000020.data'
    data2FileName = u'A000660.data' #u'A005930.data' #u'A000060.data'
    #print dataPath + data1FileName
    #print 'what\'s happened'
    data1File = cxFile(dataPath + data1FileName)
    data2File = cxFile(dataPath + data2FileName)
    data1Lines = data1File.readlines()
    data2Lines = data2File.readlines()

    print len(data1Lines), len(data2Lines)
    #print data1Lines[1]
    #print data2Lines[1]

    #print data1Lines[0]
    
    srcDic = {}
    cmpDic = {}

    for i in range(1, len(data1Lines)) :
        data1FieldDataList = getFieldDataList(data1Lines[i])
        srcDic[data1FieldDataList[0]] = i

    for i in range(1, len(data2Lines)) :
        data2FieldDataList = getFieldDataList(data2Lines[i])
        cmpDic[data2FieldDataList[0]] = i

    #print srcDic
    #print cmpDic
    intersectionKeyList = list(set(srcDic.keys()) & set(cmpDic.keys()))
    #print len(intersectionKeyList)

    if len(intersectionKeyList) == 0 :
        print 'no intersection period'
        return
    #print intersectionKeyList
    intersectionKeyList.sort()
    #print intersectionKeyList

    srcAcc = 0
    cmpAcc = 0
    amount = 0
    UpUp = 0
    UpDown = 0
    DownUp = 0
    DownDown = 0


    for i in range(1, len(intersectionKeyList) ) :
        srcDate = intersectionKeyList[i-1]
        cmpDate = intersectionKeyList[i]
        srcIndex = srcDic[srcDate]
        cmpIndex = cmpDic[cmpDate]
        srcValue = int(getFieldDataList(data1Lines[srcIndex])[6])
        cmpValue = int(getFieldDataList(data2Lines[cmpIndex])[6])
        srcAcc += srcValue
        cmpAcc += cmpValue
        amount += 1

        #print srcDate, srcValue, u'|', cmpDate, cmpValue

        if srcValue > 0 and cmpValue > 0 :
            UpUp += 1
        elif srcValue < 0 and cmpValue > 0 :
            DownUp += 1
        elif srcValue > 0 and cmpValue < 0 :
            UpDown += 1
        elif srcValue < 0 and cmpValue < 0 :
            DownDown += 1

    print float(srcAcc)/amount, amount, u'A000660', u'A005930',
    print intersectionKeyList[0], u'~', intersectionKeyList[-1]
    print u'UpUp', UpUp, float(UpUp)/amount
    print u'DownUp', DownUp, float(DownUp)/amount
    print u'UpDown', UpDown, float(UpDown)/amount
    print u'DownDown', DownDown, float(DownDown)/amount

    """
    for date in intersectionKeyList :
        srcIndex = srcDic[date]
        cmpIndex = cmpDic[date]
        srcValue = int(getFieldDataList(data1Lines[srcIndex])[6])
        cmpValue = int(getFieldDataList(data2Lines[cmpIndex])[6])
        srcAcc += srcValue
        cmpAcc += cmpValue
        print date, srcValue, cmpValue

    print srcAcc, cmpAcc
    print intersectionKeyList[0], u'~', intersectionKeyList[-1]
    """
    return

    #print data1FieldDataList[6] #전일대비
    #print data2FieldDataList[6] #전일대비
    

    #for 아이템1 에 대해 (전체 주식아이템 리스트 중)
        #해당 아이템1의 파일을 읽는다.
        #for 아이템2 에 대해 (아이템1을 제외한 리스트 중)
            #해당 아이템2의 파일을 읽는다.
            #for yesterdayValue (전날의 전일대비값) in 아이템1 리스트
                # todayValue = 아이템2의 오늘의 전일대비값
                #if yesterdayValue > 0 and todayValue > 0 :
                # 아이템1이 어제 올랐을 때, 아이템2가 오늘 올랐다. 
                # 정확히는 아이템1이 오늘 올랐을 때, 내일 아이템2가 오를 확률은?의 뜻이다.
                #   데이타[아이템1][아이템2][UpUp] += 1
                #elif yesterdayValue > 0 and todayValue < 0 :
                # 아이템1이 어제 올랐을 때, 아이템2가 오늘 내렸다.
                # 정확히는 아이템1이 오늘 올랐을 때, 내일 아이템2가 내릴 확률은?의 뜻이다.
                #   데이타[아이템1][아이템2][UpDown] += 1
                #elif yesterdayValue < 0 and todayValue > 0 :
                # 아이템1이 어제 내렸을 때, 아이템2가 오늘 올랐다.
                # 정확히는 아이템1이 오늘 내렸을 때, 내일 아이템2가 오를 확률은?의 뜻이다.
                #   데이타[아이템1][아이템2][DownUp] += 1
                #elif yesterdayValue < 0 and todayValue > 0 :
                # 아이템1이 어제 내렸을 때, 아이템2가 오늘 내렸다.
                # 정확히는 아이템1이 오늘 내렸을 때, 내일 아이템2가 내릴 확률은?의 뜻이다.
                #   데이타[아이템1][아이템2][DownDown] += 1
                #elif => y = 0 and t = 0, y = 0 and t < 0, y = 0 and t > 0, 
                #     => y > 0 and t = 0, y < 0 and t = 0, y = 0 and t = 0.
                # 이 부분들이 어떤 의미가 있을까? 생략해도 될 듯...
                #전체 카운트 증가.
            #아이템2의 파일을 닫는다
        #해당 

    from cxStockMgr     import stockMgr
    stockList = stockMgr.getStockList()
    dataPath = u'database\\day\\'
    srcStockFileName = u''
    cmpStockFileName = u''
    fileType = u'.data'
    for srcStockCode, srcStockName, srcStockFullCode in stockList :
        srcStockFileName = dataPath + srcStockCode + fileType
        srcStockFile = cxFile(srcStockFileName)
        srcDataLines = srcStockFile.readlines()
        srcStockFile.close()
        del srcStockFile
        for cmpStockCode, cmpStockName, cmpStockFullCode in stockList :
            if srcStockCode == cmpStockCode :
                continue
            cmpStockFileName = dataPath + cmpStockCode + fileType
            cmpStockFile = cxFile(cmpStockFileName)
            cmpDataLines = cmpStockFile.readlines()
            cmpStockFile.close()
            del cmpStockFile
            # find starting offset time for comparing each other.
            # or
            # travel reverse order from recent day time to most old day time.
            #for day in dayList[startingDay, lastDay] :
            srcFieldDataList = []
            cmpFieldDataList = []
            if len(srcDataLines) >= len(cmpDataLines) :
                numLines = len(cmpDataLines)
            else : numLines = len(srcDataLines)
            # src >= cmp , cmp
            # src < cmp, src

            # +++++++++++++++++++++++++++                       (src)
            #                 ++++++++++++++++++++++++++++++    (cmp)
            #                 |         |
            #                 Offset    (Offset+num) 


            #              ++++++++++++++++++++++++++++++++     (src)
            # ++++++++++++++++++++++++                          (cmp)
            #              |         |
            #              Offset    (Offset+num)


            #              +++++++++++++++++                    (src)
            # ++++++++++++++++++++++++++++++++++++++            (cmp)
            #              |               |
            #              Offset          (Offset+num)


            for i in range(1, numLines) :
                srcFieldDataList.append([ data for data in filter(lambda x : x!= u'\n', \
                                                            srcDataLines[i].split(u' '))])
                cmpFieldDataList.append([ data for data in filter(lambda x : x!= u'\n', \
                                                            cmpDataLines[i].split(u' '))])
            offset = 0
            num = 0
            i = 0
            minLen = numLines - 1

            while i < minLen :
                if int(srcFieldDataList[i][0]) > int(cmpFieldDataList[i][0]) :
                    for j in range(i, numLines) :
                        if int(srcFieldDataList[i][0]) == int(cmpFieldDataList[j][0]) :
                            offset = j
                            i = j
                            break
                elif int(srcFieldDataList[i][0]) < int(cmpFieldDataList[i][0]) :
                    for j in range(i, numLines) :
                        if int(srcFieldDataList[j][0]) == int(cmpFieldDataList[i][0]) :
                            offset = j
                            i = j
                            break
                else : num += 1
                i += 1

            print offset, num + offset
            for i in range(offset, offset + num) :
                print srcFieldDataList[i][0], cmpFieldDataList[i][0],
                if srcFieldDataList[i][0] != cmpFieldDataList[i][0] :
                    print 'Different!!'
                else : print
예제 #32
0
파일: testCP.py 프로젝트: ClarkOh/snowball
def testBuy() :
    from Queue          import Queue
    from cxCybosPlus    import gCybosPlusClassDic
    import win32gui
    import time
    from common         import getResultStringPortrait
    from cxFile         import cxFile

    reportQueue = Queue()
    conclusionQueue = Queue()

    cpTdUtil = gCybosPlusClassDic['cxCpTdUtil']
    result = cpTdUtil.TradeInit()

    if result != 0 :
        print 'cpTdUtil.init failed'
        return
    accountList = cpTdUtil.AccountNumber()
    goodsList = cpTdUtil.GoodsList(accountList[0], 3)

    cpConclusion = gCybosPlusClassDic['cxCpConclusion']
    cpConclusion.open()
    cpConclusion.set_result_queue(conclusionQueue)
    cpConclusion.Subscribe()

    cpTd0311 = gCybosPlusClassDic['cxCpTd0311']
    cpTd0311.open()
    cpTd0311.set_result_queue(reportQueue)

    cpTd0311.SetInputValue(0, 2)        # 1 : sell, 2 : buy
    cpTd0311.SetInputValue(1, accountList[0])
    cpTd0311.SetInputValue(2, goodsList[0])

    stockCode = u'A005180'      #빙그레
    amount = 1
    unitPrice = 1
    tradeCondition = 0
    tradeType = '03'

    cpTd0311.SetInputValue(3, stockCode)
    cpTd0311.SetInputValue(4, amount)
    cpTd0311.SetInputValue(5, unitPrice)
    cpTd0311.SetInputValue(7, tradeCondition)
    cpTd0311.SetInputValue(8, tradeType)

#    result = cpTd0311.BlockRequest()
    result = cpTd0311.Request()
    print 'result', result
    print 'GetDibStatus',cpTd0311.GetDibStatus()
    print 'GetDibMsg1', cpTd0311.GetDibMsg1()
    print 'Continue', cpTd0311.Continue()
    #print cpTd0311.get_header_value_list()

    cntConclusion = 0
    resultFile = cxFile()

    while True :
        if reportQueue.qsize() != 0 :
            print reportQueue.qsize()
            resultList = reportQueue.get()
            resultString = getResultStringPortrait(resultList, 1, 1, 1, 1 )
            print resultString
            resultFile.write(resultString)
            print resultList[0]
            print resultList[4]
            if ( resultList[0] == -1 ) and ( resultList[4] == u'cxCpTd0311' ) :
                del resultList
                del resultString
                break
            del resultList
            del resultString

        if conclusionQueue.qsize() != 0 :
            resultList = conclusionQueue.get()
            resultString = getResultStringPortrait(resultList, 1, 1, 1, 1)
            print resultString
            resultFile.write(resultString)
            print resultList[0]
            print resultList[4]

            cntConclusion += 1
            
            if cntConclusion >= 2 :
                break

        win32gui.PumpWaitingMessages()
        time.sleep(0.5)

    resultFile.close()
    cpConclusion.Unsubscribe()
    cpConclusion.close()