2017年8月2日 星期三

群益api in python 取得歷史kline報價

今天來用群益API取得歷史報價,群益API可以取得從上市櫃開始到今日的所有日K歷史報價,有了歷史報價就可以做很多樣回測。一分K歷史報價目前可以取得約 60000 根的資料,且幾秒鐘內就可以取回來,相當便利喔!

到目前2021年,kline 改變了不少,目前定位為 "歷史kline",只能取得當日以前的kline,若要取得當日kline,需要自己收集 tick 資料,自己組成 kline
可以參考:
  1. 群益api 使用python 取得 tick 報價
  2. tick data 轉換成 k Bar

################SKCOMAPI 2.13.17 以上版本適用##################
# 本範例要用 jupyter 來跑, 如果要在console 下跑,要加pythoncom來處理eventloop
# Eventloop 參考這幾篇的用法,或是像群益官方範例建立GUI方式產生

# skcomapi 2.13.23 以上適用
from comtypes.client import GetModule, CreateObject, GetEvents
# 將sckcom轉成python package
# GetModule 只要執行一次就好,除非有更新API,再參考官網範例,清除comtypes.gen 
# 下的檔案,再重新呼叫 GetModule 包裝
GetModule('C:\\skcom\\CapitalAPI_2.13.23\\x64\\SKCOM.dll')
import comtypes.gen.SKCOMLib as sk
import pythoncom
#config #ID and Password ID = "" PW = "" #request stock stockName='TSEA' #建立物件,避免重複 createObject #登錄物件 if 'skC' not in globals(): skC=CreateObject(sk.SKCenterLib, interface=sk.ISKCenterLib) #報價物件 if 'skQ' not in globals(): skQ=CreateObject(sk.SKQuoteLib, interface=sk.ISKQuoteLib) #回報物件 if 'skR' not in globals(): skR=CreateObject(sk.SKReplyLib , interface=sk.ISKReplyLib) #建立事件類別 class skR_events: def OnReplyMessage(self, bstrUserID, bstrMessage, sConfirmCode=0xFFFF): print('OnReplyMessage', bstrMessage) return sConfirmCode class skQ_events: def __init__(self): self.KlineData = [] def OnConnection(self, nKind, nCode): if nKind == 3003: print("skQ連線成功, nkind= ", nKind) nCode=skQ.SKQuoteLib_RequestKLine(stockName, sKLineType=4, sOutType=1) else: print('please check, nCode, nKind=', nCode, nKind) def OnNotifyKLineData(self, bstrStockNo, bstrData): self.KlineData.append([bstrStockNo] + bstrData.split(',')) #Event sink, 事件實體 EventR=skR_events() EventQ=skQ_events() #make connection to event sink ConnR = GetEvents(skR, EventR) ConnQ = GetEvents(skQ, EventQ) print('load module and event handler') #########在新 cell 執行 ############ # magic function to get event loop, 只有jupyter 可以用,
# console 介面要用 pythoncom.PumpWaitingMessages(1)
%matplotlib auto
 
#登入,連線報價主機
nCode=skC.SKCenterLib_Login(ID, PW)
print("Login,", skC.SKCenterLib_GetReturnCodeMessage(nCode))
 
#Enter quote server
nCode=skQ.SKQuoteLib_EnterMonitor()
print('SKQuoteLib_EnterMonitor()', skC.SKCenterLib_GetReturnCodeMessage(nCode))


######以下為 2.13.17以下版本 年久失修僅供參考#################################
#群益api in python 取得歷史報價
import pythoncom, time, os
import comtypes.client as cc
cc.GetModule(r'C:\SKCOM\x86\SKCOM.dll')
import comtypes.gen.SKCOMLib as sk
#建立COM物件
skC=cc.CreateObject(sk.SKCenterLib, interface=sk.ISKCenterLib)
skQ=cc.CreateObject(sk.SKQuoteLib, interface=sk.ISKQuoteLib)

#Some Configuration
ID='身分證'
PW='密碼'

#顯示 event 事件, t 秒內,每隔一秒,檢查有沒有 event 發生
def pumpwait(t=1):
    for i in range(t):
        time.sleep(1)
        pythoncom.PumpWaitingMessages()

#建立事件類別
class skQ_events:
    def __init__(self):
        self.KlineData=[]
    def OnConnection(self, nKind, nCode):
        if nCode == 0 :
            if nKind == 3001 :
                print("連線中, nkind= ", nKind)
            elif nKind == 3003:
                print("連線成功, nkind= ", nKind)
    def OnNotifyKLineData(self, bstrStockNo, bstrData):
        self.KlineData.append(bstrData.split(','))
                    
#Event sink, 事件實體  
EventQ=skQ_events()
#make connection to event sink
ConnectionQ = cc.GetEvents(skQ, EventQ)        

#登入,連線報價主機
nCode=skC.SKCenterLib_Login(ID, PW)
print("Login,", skC.SKCenterLib_GetReturnCodeMessage(nCode))
nCode=skQ.SKQuoteLib_EnterMonitor()
print("EnterMonitor,", skC.SKCenterLib_GetReturnCodeMessage(nCode))

#讀取加權日k歷史報價
#bstrStockNo 放股票代碼
#sKLineType,0 = 1分鐘線, 3 =日線288天, 4 =完整日線, 5 =週線, 6 =月線。
#sOutType, 0=舊版輸出格式, 1=新版輸出格式。新版格式一分日期與分時資料是各自一個欄位
#將data 佔存至  EventQ.KlineData
EventQ.KlineData=[]
#請求歷史報價,參數可能有出入,請自行參考最新官方 API 文件
nCode=skQ.SKQuoteLib_RequestKLine('TSEA',, sKLineType=4, sOutType=1)
#data 輸出
EventQ.KlineData[0:2]
#取1分k歷史報價
EventQ.KlineData=[]
tic=time.time()
nCode=skQ.SKQuoteLib_RequestKLine('TSEA', sKLineType=0, sOutType=1)
toc=time.time()
print('取得', len(EventQ.KlineData),  '筆1分k報價, 花費', round(toc-tic,2), '秒')


2017年8月1日 星期二

comtypes error 'tuple' object has no attribute '__ctypes_from_outparam__'

最近使用comtypes 需要使用到pythoncom功能,可以用
pip install pypiwin32

這樣就會附帶安裝pythoncom了

#2018年更新,這個問題在 comtypes 1.1.4 版中已經被修正了
使用comtypes 有時候會出現

將 comtypes 裡的 __init__.py  第 658 行程式碼做些修改可以修正這個bug
路徑大概類似這樣
~python\Lib\site-packages\comtypes\__init__.py
    657             # be iterable.
    658             if len(outargs) == 1:  # rescode is not iterable
--> 659                 return rescode.__ctypes_from_outparam__()
    660 
    661             rescode = list(rescode)
改成
            # be iterable.
            if len(outargs) == 1:  # rescode is not iterable
                try:
                    return rescode.__ctypes_from_outparam__()
                except: #somtimes rescode is tuple
                    return rescode

            rescode = list(rescode)

即可修正


Ref:



2017年7月31日 星期一

用 pywin32 COM makpy utiltiy 找群益api com 元件 GUID 碼

安裝pywin32
裝好後會在 python目錄/lib/site-pacjages/pythonwin 下看到一個 pythonwin IDE,執行後如下
選擇 Tools => COM makpy Uitility => Select library 選SKCOMlib後,會在 ~/lib\site-packages\win32com\gen_py\ 產生一長串檔名的.py
打開後找 class ISKCenterLib, ISKOSQuoteLib 等的 coclass_clsid,像是SKCenterLib的class_clsid是 
{AC30BAB5-194A-4515-A8D3-6260749F8577}
之後就可以用這些class_clsid 給 comtypes.client.CreatObject 串接COM元件,請參考