TQDB API 範例 (Python版)

首先我們自定義連結TQDB取出報價資料的函數

  • 預設Series作為資料輸出格式,也可以選擇DataFrame
  • 資料主機的位置,我們先預設為本機IP:127.0.0.1

In [1]:
%matplotlib inline
import math
import matplotlib.pyplot as plt
import requests
import datetime
import urllib
from  pandas import DataFrame,Series
# Define function to fetch remote data # demonstartion only #
def TQDB(symbol='DEMO1',startDate='2014-6-30',endDate='2035-7-01',type='Series',server='127.0.0.1'):
    querystr={'symbol':symbol, 'BEG':startDate, 'END': endDate}
    url = "http://"+server+"/cgi-bin/q1min.py?"+urllib.urlencode(querystr)
    r = requests.get(url)
    lines = r.content.split('\n')
    x = []
    H=[]
    L=[]
    C=[]
    O=[]
    Vol=[]
    i=0
    for line in lines:
        i=i+1
        items=line.split(',')
        if len(items) < 5:
            continue
        dt=datetime.datetime.strptime(items[0]+items[1], '%Y%m%d%H%M%S')
        x.append(dt)

        C.append(float(items[5]))
        L.append(float(items[4]))
        H.append(float(items[3]))
        O.append(float(items[2]))
        Vol.append(float(items[6]))
    d = {'O' :O,'H':H,'L':L,'C':C,'Vol':Vol}
    if len(O)==0:
        print "no data available. Please select different date"
        return
    if type=="DataFrame":
        return DataFrame(d,index=x, columns=['O','H','L','C','Vol'])
    elif type=="Series":
        return Series(C,index=x)
    else:
        print 'type is not defined'

In [2]:
s='2015-07-1'
e='2035-12-1'
a=TQDB("DEMO1",type='Series',startDate=s,endDate=e)
b=TQDB("DEMO2",type='Series',startDate=s,endDate=e)
c=TQDB("DEMO3",type='Series',startDate=s,endDate=e)

In [3]:
# (a)['C'].plot()#blue
ee="2015-10-23"
a[ee].plot()
b[ee].plot()
c[ee].plot()
#a.to_csv('SPY.csv')
# b.plot()#Green
# c.plot()#red


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-7c66ea307b0c> in <module>()
      1 # (a)['C'].plot()#blue
      2 ee="2015-10-23"
----> 3 a[ee].plot()
      4 b[ee].plot()
      5 c[ee].plot()

/usr/local/lib/python2.7/dist-packages/pandas/core/series.pyc in __getitem__(self, key)
    555     def __getitem__(self, key):
    556         try:
--> 557             result = self.index.get_value(self, key)
    558 
    559             if not np.isscalar(result):

/usr/local/lib/python2.7/dist-packages/pandas/tseries/index.pyc in get_value(self, series, key)
   1320                 return self.get_value_maybe_box(series, key)
   1321             except (TypeError, ValueError, KeyError):
-> 1322                 raise KeyError(key)
   1323 
   1324     def get_value_maybe_box(self, series, key):

KeyError: '2015-10-23'

In [4]:
(a-b).plot()#blue
#b.plot()#Green


Out[4]:
<matplotlib.axes._subplots.AxesSubplot at 0x7fda70a42750>

In [5]:
s='2014-5-2'
e='2035-7-3'
stw=TQDB("DEMO1",type='Series',startDate=s,endDate=e)
tx=TQDB("DEMO2",type='Series',startDate=s,endDate=e)

In [6]:
p=1.5*30*stw-tx*2

In [7]:
p


Out[7]:
2016-02-18 04:01:00    429433
2016-02-18 04:02:00    428582
2016-02-18 04:03:00    426260
2016-02-18 04:04:00    426238
dtype: float64

In [8]:
p.plot()


Out[8]:
<matplotlib.axes._subplots.AxesSubplot at 0x7fda7091c850>

In [ ]: