def loop(self,code):
name=self.bases[self.bases['code']==code]['name'].values[0]
print name
while 1:
time.sleep(2)
df_t1=ts.get_realtime_quotes(code)
v1=long(df_t1['volume'].values[0])
p1=float(df_t1['price'].values[0])
#print df_t1
time.sleep(2)
df_t2=ts.get_realtime_quotes(code)
v2=long(df_t2['volume'].values[0])
p2=float(df_t2['price'].values[0])
delta_v= (v2-v1)/100
#???
#????
price_v=p2-p1
if delta_v >1000:
print datetime.datetime.now().strftime('%H:%M:%S')
print "Big deal on %s" %name,
print delta_v,'price diff',price_v
python类get_realtime_quotes()的实例源码
def break_ceil(self, code):
print threading.current_thread().name
while 1:
#print code
time.sleep(2)
try:
df = ts.get_realtime_quotes(code)
except:
time.sleep(5)
continue
v = long(df['b1_v'].values[0])
if v <= 1000:
print datetime.datetime.now().strftime("%H:%M:%S")
print u"?????????"
print self.bases[self.bases['code']==code]['name'].values[0]
if self.send==True:
self.push_msg('break', 10, 10, 'down')
#???????????????s
def break_ceil(code):
while 1:
time.sleep(2)
try:
df=ts.get_realtime_quotes(code)
except:
time.sleep(5)
continue
v=long(df['b1_v'].values[0])
print datetime.datetime.now().strftime("%H:%M:%S")
print v
#print type(v)
if v<=10000 :
print u"?????????"
push_msg('break',10,10,'down')
#???????????????
def GET_OPEN_DAY(self, context, security, ref=0):
if ref==0:
dfreal = ts.get_realtime_quotes(security)
if dfreal.empty == True:
return np.nan
return float(dfreal['open'][0])
else:
dataCount = ref + 1
df_data = ts.get_k_data(security, index=False, ktype='D').tail(dataCount)
if df_data.empty == True:
print "security:%s in context:%s NO GET_OPEN_DAY!" %(str(security),str(context))
return np.nan
if len(df_data['open']) < ref:
return np.nan
return df_data['open'].values[-ref]
# ???????????
def getStkListNowQuotes(self, stockList):
''' ???????? '''
atOneTime = 30 # ????????????
nowDict = {}
while len(stockList) > atOneTime:
thisTime = stockList[:atOneTime]
stockList = stockList[atOneTime:]
data = ts.get_realtime_quotes(thisTime)
nowPrice = data['price'].values
nowVolume = data['volume'].values
for index,code in enumerate(thisTime):
nowDict[code] = {'price':eval(nowPrice[index]), 'vol':eval(nowVolume[index])}
# ?????
if len(stockList)>0:
data = ts.get_realtime_quotes(stockList)
nowPrice = data['price'].values
nowVolume = data['volume'].values
for index,code in enumerate(stockList):
nowDict[code] = {'price':eval(nowPrice[index]), 'vol':eval(nowVolume[index])}
return nowDict
def stock():
time = datetime.datetime.now() # ??????
now = time.strftime('%H:%M:%S')
data = ts.get_realtime_quotes(stock_symbol) # ??????
r1 = float(data['price'])
r2 = str(stock_symbol) + ' ?????? ' + str(r1)
content = now + '\n' + r2
itchat.send(content, toUserName='filehelper')
print(content)
# ?????????????
if r1 <= float(price_low):
itchat.send('????????', toUserName='filehelper')
print('????????')
elif r1 >= float(price_high):
itchat.send('????????', toUserName='filehelper')
print('????????')
else:
itchat.send('????', toUserName='filehelper')
print('????')
# ? 3 ?????
def stock():
time = datetime.datetime.now() # ??????
now = time.strftime('%H:%M:%S')
data = ts.get_realtime_quotes(stock_symbol) # ??????
r1 = float(data['price'])
r2 = str(stock_symbol) + ' ?????? ' + str(r1)
content = now + '\n' + r2
itchat.send(content, toUserName='filehelper')
print(content)
# ?????????????
if r1 <= float(price_low):
itchat.send('????????', toUserName='filehelper')
print('????????')
elif r1 >= float(price_high):
itchat.send('????????', toUserName='filehelper')
print('????????')
else:
itchat.send('????', toUserName='filehelper')
print('????')
# ?????????
def get_realtime_quotes(code_list, open_only=False):
import tushare as ts
max_len = 800
loop_cnt = int(math.ceil(float(len(code_list)) / max_len))
total_df = reduce(lambda df1, df2: df1.append(df2),
[ts.get_realtime_quotes([code for code in code_list[i::loop_cnt]])
for i in range(loop_cnt)])
total_df["is_index"] = False
index_symbol = ["sh", "sz", "hs300", "sz50", "zxb", "cyb"]
index_df = ts.get_realtime_quotes(index_symbol)
index_df["code"] = index_symbol
index_df["is_index"] = True
total_df = total_df.append(index_df)
total_df = total_df.set_index("code").sort_index()
columns = set(total_df.columns) - set(["name", "time", "date"])
# columns = filter(lambda x: "_v" not in x, columns)
for label in columns:
total_df[label] = total_df[label].map(lambda x: 0 if str(x).strip() == "" else x)
total_df[label] = total_df[label].astype(float)
total_df["chg"] = total_df["price"] / total_df["pre_close"] - 1
total_df["order_book_id"] = total_df.index
total_df["order_book_id"] = total_df["order_book_id"].apply(tushare_code_2_order_book_id)
total_df["datetime"] = total_df["date"] + " " + total_df["time"]
total_df["datetime"] = total_df["datetime"].apply(lambda x: convert_dt_to_int(datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S")))
total_df["close"] = total_df["price"]
if open_only:
total_df = total_df[total_df.open > 0]
return total_df
def realtime(self, id):
# all_stock=ts.get_today_all()
# print all_stock
df = ts.get_realtime_quotes(id)
# print df[['time','name','price','bid','ask','volume']]
# print df.head()
# price_change = ts.get_today_ticks(id)
# print price_change[['time','change','type','volume']]
big_share = ts.get_sina_dd(id, date=self.date)
print big_share[['time', 'code', 'price', 'preprice', 'volume', 'type']]
print big_share.sort(columns='volume')
def realtime(self, id):
# all_stock=ts.get_today_all()
# print all_stock
df = ts.get_realtime_quotes(id)
# print df[['time','name','price','bid','ask','volume']]
# print df.head()
price_change = ts.get_today_ticks(id)
print price_change[['time', 'change', 'type', 'volume']]
big_share = ts.get_sina_dd(id, date='2016-04-01')
print big_share[['time', 'code', 'price', 'preprice', 'volume', 'type']]
def realtime(self, id):
# all_stock=ts.get_today_all()
# print all_stock
df = ts.get_realtime_quotes(id)
# print df[['time','name','price','bid','ask','volume']]
# print df.head()
price_change = ts.get_today_ticks(id)
print price_change[['time', 'change', 'type', 'volume']]
big_share = ts.get_sina_dd(id, date='2016-04-01')
print big_share[['time', 'code', 'price', 'preprice', 'volume', 'type']]
def meet_percent(code, percent_up, percent_down,type):
try:
df = ts.get_realtime_quotes(code)
except Exception, e:
print e
time.sleep(5)
return 0
real_price = df['price'].values[0]
name = df['name'].values[0]
real_price = float(real_price)
pre_close = float(df['pre_close'].values[0])
real_percent = (real_price - pre_close) / pre_close * 100
# print percent
# percent=df['']
# print type(real_price)
if real_percent >= percent_up:
print '%s percent higher than %.2f , %.2f' % (name, real_percent, real_price),
if type=='msn':
push_msg(name, real_price, real_price, 'up')
return 1
elif type=='wechat':
push_wechat(name, real_price, real_percent, 'down')
return 1
if real_percent <= percent_down:
print '%s percent lower than %.2f , %.2f' % (name, real_percent, real_price),
print '%'
if type=='mns':
push_msg(name, real_price, real_percent, 'down')
return 1
elif type=='wechat':
push_wechat(name, real_price, real_percent, 'down')
return 1
# ?????????
def GET_ALL_SECURITIES(self,filtPaused=True, filtSt=True, filtMarketcap=0):
l_stocks = self.__df_allsecurities__.index.get_values().tolist()
print "l_stocks %s in all", len(l_stocks)
if filtPaused or filtSt or filtMarketcap > 0:
filtresult = []
for s in l_stocks:
isfilted = False
try:
dfreal = ts.get_realtime_quotes(s)
except Exception,e:
print Exception,":",e
dfreal = None
if not dfreal is None and filtPaused:
if float(str(dfreal['volume'][0])) == 0 and float(str(dfreal['bid'][0])) == 0 and float(str(dfreal['ask'][0])) == 0:
isfilted = True
if not dfreal is None and filtSt:
if str(dfreal['name'][0]).find('ST') > -1:
isfilted = True
if filtMarketcap > 0:
outstanding = self.GET_SECURITY_INFO(s)['outstanding']
price = self.GET_CLOSE_DAY(None, s)
markCap = outstanding * price
if markCap > filtMarketcap:
print "security %s isfilted,markCap:%s" % (str(s),str(markCap))
isfilted = True
if isfilted:
print "security %s isfilted" % str(s)
pass
else:
filtresult.append(s)
l_stocks = filtresult
print "l_stocks %s after filter", len(l_stocks)
return l_stocks
# ??????
#security
def GET_AMOUNT_DATA_DAY(self, context, security,isLastest=True,data={},dataCount=20):
#TODO get_k_data has no amount data, get_h_data no support index
try:
df_data = ts.get_h_data(security, index=False)
except Exception,e:
print e
df_data = None
if df_data is None or df_data.empty == True:
print "security:%s in context:%s NO GET_AMOUNT_DATA_DAY!" %(str(security),str(context))
return np.array([np.nan])
df_data = df_data.iloc[::-1].tail(dataCount)
amountData = df_data['amount'].values
try:
dfreal = ts.get_realtime_quotes(security)
except Exception,e:
print Exception,":",e
dfreal = None
if not dfreal is None:
data = dfreal.date[0]
time = dfreal.time[0]
dateStr = data + ' ' + time
current_dt = self.__getdatetime__(dateStr)
runtime = SecurityDataSrcBase.GET_RUN_MINUTES(TsContext(current_dt))
if runtime < 240:
amountLast = float(dfreal.amount[0])
amountData = np.append(amountData, amountLast)
return amountData
# overide
def getStkSingleNowPrice(self, code, flag): # -> float flag: 'ask' ???;'bid' ???;'price' ??
''' ????????????/??? '''
price = ts.get_realtime_quotes(code).T[0][flag]
return round(float(price),2)
# ??????
def get_today_open_price(code):
'''
:param code:????
:return:?????
'''
import tushare as ts
return ts.get_realtime_quotes(code)['open']
def get_today_close_price(code):
'''
:param code:????
:return: ?????
'''
import tushare as ts
return ts.get_realtime_quotes(code)['close']
def repo(self):
security = '131810'
quote_df = ts.get_realtime_quotes(security)
order = {
'action': 'SELL',
'symbol': security,
'type': 'LIMIT',
'price': float(quote_df['bid'][0]),
'amountProportion': 'ALL'
}
for trader in self._traders.values():
try:
trader.execute(**order)
except:
self._logger.exception('[%s] ?????', trader.id)
def __call__(self):
df = ts.get_realtime_quotes(self._symbol)
order = {
'action': 'SELL',
'symbol': self._symbol,
'type': 'LIMIT',
'price': float(df['bid'][0]),
'amountProportion': 'ALL'
}
for client_alias in self._client_aliases:
try:
client = self._client_aliases[client_alias]
self._client.execute(client, **order)
except:
self._logger.exception('???[%s]?????', client_alias)
def get_stock_quotes():
# Get real time quotes of the stock list
global sched_time
while True:
now = dt.datetime.now().time()
#now = dt.time(9, 25, 1)
if is_market_open(now):
try:
raw_data = ts.get_realtime_quotes(stock_list)
raw_data = process_raw_data(raw_data)
#print(raw_data)
for index, row in raw_data.iterrows():
data_list[index] = pd.concat([data_list[index], raw_data[index:index + 1]])
#print(data_list[index])
print('Get real time quotes of stock list done!')
time.sleep(seconds_per_tick_data)
except KeyboardInterrupt:
print('Interrupt occur!')
break
except Exception:
print('Error in reading!')
continue
else:
if now > market_close_time3:
break
else:
sleep_time = (sched_time.hour - now.hour) * 60 * 60 + (sched_time.minute - now.minute) * 60 + (sched_time.second - now.second)
print(sleep_time)
time.sleep(sleep_time)
save_to_csv(data_list)
def get_realtime_quotes(code_list, open_only=False):
import tushare as ts
max_len = 800
loop_cnt = int(math.ceil(float(len(code_list)) / max_len))
total_df = reduce(lambda df1, df2: df1.append(df2),
[ts.get_realtime_quotes([code for code in code_list[i::loop_cnt]])
for i in range(loop_cnt)])
total_df["is_index"] = False
index_symbol = ["sh", "sz", "hs300", "sz50", "zxb", "cyb"]
index_df = ts.get_realtime_quotes(index_symbol)
index_df["code"] = index_symbol
index_df["is_index"] = True
total_df = total_df.append(index_df)
total_df = total_df.set_index("code").sort_index()
columns = set(total_df.columns) - set(["name", "time", "date"])
# columns = filter(lambda x: "_v" not in x, columns)
for label in columns:
total_df[label] = total_df[label].map(lambda x: 0 if str(x).strip() == "" else x)
total_df[label] = total_df[label].astype(float)
total_df["chg"] = total_df["price"] / total_df["pre_close"] - 1
total_df["order_book_id"] = total_df.index
total_df["order_book_id"] = total_df["order_book_id"].apply(tushare_code_2_order_book_id)
total_df["datetime"] = total_df["date"] + " " + total_df["time"]
total_df["datetime"] = total_df["datetime"].apply(lambda x: convert_dt_to_int(datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S")))
total_df["close"] = total_df["price"]
if open_only:
total_df = total_df[total_df.open > 0]
return total_df
def get_realtime_quotes(code_list, open_only=False):
import tushare as ts
max_len = 800
loop_cnt = int(math.ceil(float(len(code_list)) / max_len))
total_df = reduce(lambda df1, df2: df1.append(df2),
[ts.get_realtime_quotes([code for code in code_list[i::loop_cnt]])
for i in range(loop_cnt)])
total_df["is_index"] = False
index_symbol = ["sh", "sz", "hs300", "sz50", "zxb", "cyb"]
index_df = ts.get_realtime_quotes(index_symbol)
index_df["code"] = index_symbol
index_df["is_index"] = True
total_df = total_df.append(index_df)
columns = set(total_df.columns) - set(["name", "time", "date", "code"])
# columns = filter(lambda x: "_v" not in x, columns)
for label in columns:
total_df[label] = total_df[label].map(lambda x: 0 if str(x).strip() == "" else x)
total_df[label] = total_df[label].astype(float)
total_df["chg"] = total_df["price"] / total_df["pre_close"] - 1
total_df["order_book_id"] = total_df["code"]
total_df["order_book_id"] = total_df["order_book_id"].apply(tushare_code_2_order_book_id)
total_df = total_df.set_index("order_book_id").sort_index()
total_df["datetime"] = total_df["date"] + " " + total_df["time"]
total_df["datetime"] = total_df["datetime"].apply(lambda x: convert_dt_to_int(datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S")))
total_df["close"] = total_df["price"]
total_df["last"] = total_df["price"]
total_df["limit_up"] = total_df.apply(lambda row: row.pre_close * (1.1 if "ST" not in row["name"] else 1.05), axis=1).round(2)
total_df["limit_down"] = total_df.apply(lambda row: row.pre_close * (0.9 if "ST" not in row["name"] else 0.95), axis=1).round(2)
if open_only:
total_df = total_df[total_df.open > 0]
return total_df
def get_realtime_quotes(order_book_id_list, open_only=False, include_limit=False):
import tushare as ts
code_list = [order_book_id_2_tushare_code(code) for code in order_book_id_list]
max_len = 800
loop_cnt = int(math.ceil(float(len(code_list)) / max_len))
total_df = reduce(lambda df1, df2: df1.append(df2),
[ts.get_realtime_quotes([code for code in code_list[i::loop_cnt]])
for i in range(loop_cnt)])
total_df["is_index"] = False
index_symbol = ["sh", "sz", "hs300", "sz50", "zxb", "cyb"]
index_df = ts.get_realtime_quotes(index_symbol)
index_df["code"] = index_symbol
index_df["is_index"] = True
total_df = total_df.append(index_df)
columns = set(total_df.columns) - set(["name", "time", "date", "code"])
# columns = filter(lambda x: "_v" not in x, columns)
for label in columns:
total_df[label] = total_df[label].map(lambda x: 0 if str(x).strip() == "" else x)
total_df[label] = total_df[label].astype(float)
total_df["chg"] = total_df["price"] / total_df["pre_close"] - 1
total_df["order_book_id"] = total_df["code"]
total_df["order_book_id"] = total_df["order_book_id"].apply(tushare_code_2_order_book_id)
total_df = total_df.set_index("order_book_id").sort_index()
total_df["order_book_id"] = total_df.index
total_df["datetime"] = total_df["date"] + " " + total_df["time"]
# total_df["datetime"] = total_df["datetime"].apply(
# lambda x: convert_dt_to_int(datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S")))
total_df["close"] = total_df["price"]
total_df["last"] = total_df["price"]
total_df = total_df.rename(columns={
"{}{}_p".format(base_name, i): "{}{}".format(base_name, i)
for i in range(1, 6) for base_name in ["a", "b"]
})
total_df = total_df.rename(columns={"pre_close": "prev_close"})
del total_df["code"]
del total_df["is_index"]
del total_df["date"]
del total_df["time"]
if include_limit:
total_df["limit_up"] = total_df.apply(
lambda row: row.prev_close * (1.1 if "ST" not in row["name"] else 1.05), axis=1).round(2)
total_df["limit_down"] = total_df.apply(
lambda row: row.prev_close * (0.9 if "ST" not in row["name"] else 0.95), axis=1).round(2)
if open_only:
total_df = total_df[total_df.open > 0]
return total_df