def gjzq(file): df = pd.read_table(file, encoding='gbk', dtype={'证券代码': np.str}) del df['Unnamed: 15'] code_list = list(df['证券代码'].values) api = ts.get_apis() # 移除非法证券代码 中签 t=[code_list.remove(i) for i in code_list.copy() if i.startswith('7') or i[:2] == '07'] price_df = ts.quotes(code_list, conn=api) # 去除不合法的数据 price_df=price_df.dropna() filter_df = price_df[price_df['last_close'] != 0] filter_df = filter_df.reset_index(drop=True) filter_df['percent'] = (filter_df['price'] - filter_df['last_close']) / filter_df['last_close'] * 100 filter_df['percent'] = filter_df['percent'].map(lambda x: round(x, 2)) ret_df = filter_df[(filter_df['percent'] > ALERT_PERCENTAGE) | (filter_df['percent'] < ALERT_PERCENTAGE*-1)] d = dict(zip(list(df['证券代码'].values), list(df['证券名称']))) ret_df['name']=ret_df['code'].map(lambda x:d.get(x)) ret_df['amount']=ret_df['amount'].map(lambda x:round(x/10000,1)) rename_column = {'code':'证券代码','name':'证券名称','price':'当前价格','percent':'涨幅','amount':'成交金额(万)'} ret_df=ret_df.rename(columns=rename_column) ret = ret_df[list(rename_column.values())] ret=ret.reset_index(drop=True) # 发送推送 print(ret) ts.close_apis(api)
def get_realtime_info(self, codes, has_sent, types, stock, yjl, percent): try: price_df = ts.quotes(codes, conn=self.api) except Exception as e: logger.error('获取可转债异常 >>>> {}'.format(e)) try: self.api = ts.get_apis() except Exception as e: logger.error('异常中存在异常{}'.format(e)) time.sleep(EXECEPTION_TIME) else: if len(price_df) != 0: price_df = price_df[price_df['cur_vol'] != 0] price_df['percent'] = (price_df['price'] - price_df['last_close']) / price_df[ 'last_close'] * 100 price_df['percent'] = price_df['percent'].map(lambda x: round(x, 2)) ret_dt = \ price_df[ (price_df['percent'] > percent) | (price_df['percent'] < -1 * percent)][ ['code', 'price', 'percent']] if len(ret_dt) > 0: # 提醒一次后,下一次的间隔为DELTA_TIME分钟后 # sent_list = [] for i in ret_dt['code']: if has_sent[i] <= datetime.datetime.now(): name_list = [] yjl_list = [] name_list.append(stock[i]) yjl_list.append(yjl[i]) has_sent[i] = datetime.datetime.now() + datetime.timedelta(minutes=DELTA_TIME) ret_dt1 = ret_dt[ret_dt['code'] == i] ret_dt1['名称'] = name_list ret_dt1['溢价率'] = yjl_list name=ret_dt1['名称'].values[0] price=ret_dt1['price'].values[0] percent=ret_dt1['percent'].values[0] yjl_v = ret_dt1['溢价率'].values[0] now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') content0='{t}\n{name}:价格:{price} 涨幅:{percent},溢价率:{yjl}'.format(name=name,price=price,percent=percent,yjl=yjl_v,t=now) logger.info(content0) try: wechat.send_content(content0) except Exception as e: logger.info('发送微信失败') logger.info(e)
def get_price_diff(self, codes, has_sent_, types): # 针对可转债 try: df = ts.quotes(codes, conn=self.api) except Exception as e: logger.error('获取可转债异常 >>>> {}'.format(e)) try: self.api = ts.get_apis() except Exception as e: logger.error('异常中存在异常{}'.format(e)) time.sleep(EXECEPTION_TIME) else: df['bid1'] = df['bid1'].astype(float) df['ask1'] = df['ask1'].astype(float) df['diff'] = np.abs(df['bid1'] - df['ask1']) result = df[df['diff'] >= DIFF_V] if result.empty: # continue return else: for j in result['code']: if has_sent_[j] <= datetime.datetime.now(): has_sent_[j] = datetime.datetime.now()+ datetime.timedelta(minutes=DIFF_DELTA_TIME) name_list = [] yjl_list = [] name_list.append(self.kzz_stocks[j]) yjl_list.append(self.kzz_stocks_yjl[j]) ret_dt1 = result[result['code'] == j] ret_dt1['名称']=name_list ret_dt1['溢价率']=yjl_list # ret_dt1 = ret_dt1.set_index('code', drop=True) code=j name = ret_dt1['名称'].values[0] price = ret_dt1['price'].values[0] bid = ret_dt1['bid1'].values[0] ask = ret_dt1['ask1'].values[0] diff = round(ret_dt1['diff'].values[0],2) now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') content0 = '{t}\n{code}::{name}:价格:{price} 买1:{bid} 卖1:{ask}差价:{diff}'.format(code=code,name=name, price=price, bid=bid, ask=ask, diff=diff, t=now) logger.info(content0) try: wechat.send_content(content0) except Exception as e: logger.info('发送微信失败') logger.info(e)
def monitor(): engine = DB.get_engine('db_zdt', 'qq') table = '20180409zdt' api = ts.get_apis() df = pd.read_sql(table, engine, index_col='index') price_list = [] percent_list = [] amplitude_list = [] start = datetime.datetime.now() for i in df['代码'].values: try: curr = ts.quotes(i, conn=api) last_close = curr['last_close'].values[0] curr_price = curr['price'].values[0] amplitude = round( ((curr['high'].values[0] - curr['low'].values[0]) * 1.00 / last_close) * 100, 2) # if last_close>=curr_price: # print(i,) # print(df[df['代码']==i]['名称'].values[0],) # print( percent) except Exception as e: print('this point') print(e) api = ts.get_apis() curr_price = 0 if last_close == 0: percent = np.nan percent = round((curr_price - last_close) * 100.00 / last_close, 2) percent_list.append(percent) price_list.append(curr_price) amplitude_list.append(amplitude) df['今日价格'] = price_list df['今日涨幅'] = percent_list df['今日振幅'] = amplitude_list df['更新时间'] = datetime.datetime.now().strftime('%Y %m %d %H:%M%S') end = datetime.datetime.now() print('time use {}'.format(end - start)) df.to_sql(table + 'monitor', engine, if_exists='replace') ts.close_apis(api)
def monitor(self): while 1: current = trading_time() if current == 0: # if True: try: price_df = ts.quotes(self.code_list, conn=self.api) price_df = price_df[price_df['cur_vol'] != 0] price_df['percent'] = ( price_df['price'] - price_df['last_close']) / price_df['last_close'] * 100 price_df['percent'] = map(lambda x: round(x, 2), price_df['percent']) ret_dt = price_df[(price_df['percent'] > 2) | (price_df['percent'] < -2)][[ 'code', 'price', 'percent' ]] if len(ret_dt) > 0: name_list = [] # 只会提醒一次,下次就不会再出来了 for i in ret_dt['code']: name_list.append(self.stocks[i]) self.code_list.remove(i) # name_list =[self.stocks[i] for i in ret_dt['code'] ] ret_dt['name'] = name_list ret_dt = ret_dt.sort_values(by='percent', ascending=False) ret_dt = ret_dt.reset_index(drop=True) # print ret_dt # print datetime.datetime.now() try: sendmail(ret_dt.to_string(), u'波动的可转债') logger.log("Send mail successfully at {}".format( datetime.datetime.now())) except Exception, e: logger.log('sending mail failed') logger.log(e) time.sleep(LOOP__TIME) except Exception, e: logger.log(e) self.api = ts.get_apis() time.sleep(EXECEPTION_TIME)
def gjzq(file): df = pd.read_table(file, encoding='gbk', dtype={'证券代码': np.str}) del df['Unnamed: 15'] code_list = list(df['证券代码'].values) api = ts.get_apis() # 移除非法证券代码 中签 t = [ code_list.remove(i) for i in code_list.copy() if i.startswith('7') or i[:2] == '07' ] price_df = ts.quotes(code_list, conn=api) # 去除不合法的数据 price_df = price_df.dropna() filter_df = price_df[price_df['last_close'] != 0] filter_df = filter_df.reset_index(drop=True) filter_df['percent'] = (filter_df['price'] - filter_df['last_close'] ) / filter_df['last_close'] * 100 filter_df['percent'] = filter_df['percent'].map(lambda x: round(x, 2)) ret_df = filter_df[(filter_df['percent'] > ALERT_PERCENTAGE) | (filter_df['percent'] < ALERT_PERCENTAGE * -1)] d = dict(zip(list(df['证券代码'].values), list(df['证券名称']))) ret_df['name'] = ret_df['code'].map(lambda x: d.get(x)) ret_df['amount'] = ret_df['amount'].map(lambda x: round(x / 10000, 1)) rename_column = { 'code': '证券代码', 'name': '证券名称', 'price': '当前价格', 'percent': '涨幅', 'amount': '成交金额(万)' } ret_df = ret_df.rename(columns=rename_column) ret = ret_df[list(rename_column.values())] ret = ret.reset_index(drop=True) # 发送推送 print(ret) ts.close_apis(api)
def monitor(): engine = get_engine('db_zdt') table = '20180409zdt' api = ts.get_apis() df = pd.read_sql(table, engine, index_col='index') price_list = [] percent_list = [] amplitude_list = [] start = datetime.datetime.now() for i in df['代码'].values: try: curr = ts.quotes(i, conn=api) last_close = curr['last_close'].values[0] curr_price = curr['price'].values[0] amplitude = round(((curr['high'].values[0] - curr['low'].values[0]) * 1.00 / last_close) * 100, 2) # if last_close>=curr_price: # print(i,) # print(df[df['代码']==i]['名称'].values[0],) # print( percent) except Exception as e: print('this point') print(e) api=ts.get_apis() curr_price = 0 if last_close == 0: percent = np.nan percent = round((curr_price - last_close) * 100.00 / last_close, 2) percent_list.append(percent) price_list.append(curr_price) amplitude_list.append(amplitude) df['今日价格'] = price_list df['今日涨幅'] = percent_list df['今日振幅'] = amplitude_list df['更新时间'] = datetime.datetime.now().strftime('%Y %m %d %H:%M%S') end = datetime.datetime.now() print('time use {}'.format(end - start)) df.to_sql(table + 'monitor', engine, if_exists='replace') ts.close_apis(api)
def test_message(): print('receive') # print(message) # 定时任务 zg_code_dict = get_zg_code() code_list = list(zg_code_dict.keys()) conn = ts.get_apis() each_batch = math.ceil(len(code_list) / 5) # 分批 3批 while 1: for i in range(5): code_list_ = code_list[i * each_batch:each_batch * (i + 1)] try: df = ts.quotes(code_list_, conn=conn) except Exception as e: socketio.sleep(10) continue df = df[['code', 'price', 'last_close']] df['percent'] = df.apply(lambda row: round((row['price'] - row[ 'last_close']) / row['last_close'] * 100, 2), axis=1) df = df[(df['percent'] > 8) | (df['percent'] < -8)] df = df.sort_values(by='percent') df['name'] = df['code'].map(lambda x: zg_code_dict.get(x)) if len(df) > 0: result = df.to_dict(orient='records') print('send---') # print(result) # for item in result: socketio.emit('start_response', { 'data': result, 'num': i + 1 }, namespace="/test")
def update_daily(self): add_cols = u'ALTER TABLE `{}` ADD `{}` FLOAT;'.format(self.table_name, self.today) self._exe(add_cols) # self.conn.commit() api = ts.get_apis() cmd = 'SELECT * FROM `{}`'.format(self.table_name) cur = self._exe(cmd) for i in cur.fetchall(): (code, name, safe_price, count, profit_ratio, profit, values, current_price,earn) = i[:9] df = ts.quotes(code, conn=api) current_price = round(float(df['price'].values[0]), 2) values = current_price * count last_close = df['last_close'].values[0] earn = (current_price - last_close) * count profit = (current_price - safe_price) * count profit_ratio = round(float(current_price - safe_price) / safe_price * 100, 2) update_cmd = u'UPDATE {} SET `盈亏比例`={} ,`盈亏`={}, `市值` ={}, `现价` = {},`{}`={} where `证券代码`= {};'.format( self.table_name, profit_ratio, profit, values, current_price, self.today, earn,code) print update_cmd self._exe(update_cmd) ts.close_apis(api)
def fund_info(): form_fund = QueryFund() form_cb = QueryCB() form_update_cb_code = UpdateCBCode() if form_fund.search.data and form_fund.validate_on_submit(): code = form_fund.code.data name, price, percent = fetch(code) return render_template('fund.html', form_fund=form_fund, form_cb=form_cb, form_update_cb_code=form_update_cb_code, price=price, name=name, percent=percent) elif form_cb.search_bt1.data and form_cb.validate_on_submit(): text = form_cb.cb_code.data bond_id_list = code_dict.get(text) bond_name_dict = {} if text.isdigit(): bond_list = [text] for item in bond_list: k = list(item.keys())[0] bond_list.append(k) v = list(item.values())[0] bond_name_dict[k] = v else: # pinyin if bond_id_list is None: flash('No dict found!') return render_template('fund.html', form_fund=form_fund, form_cb=form_cb, form_update_cb_code=form_update_cb_code, cb_percent='', cb_price='', ask1='', bid1='', diff='') bond_list = [] for item in bond_id_list: k = list(item.keys())[0] bond_list.append(k) v = list(item.values())[0] bond_name_dict[k] = v try: df = ts.quotes(bond_list, conn=conn) except Exception as e: print(e) return render_template('fund.html', form_fund=form_fund, form_cb=form_cb, form_update_cb_code=form_update_cb_code, cb_percent='', cb_price='', ask1='', bid1='', diff='') result_list = [] for index, row in df.iterrows(): last_close = row['last_close'] / 10 cb_price = round(row['price'] / 10, 1) cb_percent = round((cb_price - last_close) / last_close * 100, 1) ask1 = row['ask1'] bid1 = row['bid1'] try: diff = round((ask1 - bid1) / bid1 * 100, 1) except: diff = 0 d = {} d['cb_price'] = cb_price d['cb_percent'] = cb_percent d['ask1'] = round(ask1 / 10, 1) d['bid1'] = round(bid1 / 10, 1) d['diff'] = diff d['bond_name'] = bond_name_dict.get(row['code']).replace('转债', '') result_list.append(d) return render_template('fund.html', form_fund=form_fund, form_cb=form_cb, form_update_cb_code=form_update_cb_code, bond_lists=result_list) elif form_update_cb_code.update_bt.data and form_update_cb_code.validate_on_submit( ): # 更新代码 result = update_cb_code_fun() # print('updating coding') with open('codes.cfg', 'w') as f: json.dump(result, f, ensure_ascii=False) flash('Update code succussfully!') return render_template( 'fund.html', form_fund=form_fund, form_cb=form_cb, form_update_cb_code=form_update_cb_code, ) else: return render_template('fund.html', form_fund=form_fund, form_cb=form_cb, form_update_cb_code=form_update_cb_code)
__author__ = 'Administrator' import tushare as ts import sys import time sys.path.append("C:\\quanttime\\src\\auto_hunter") import getSinaquotation1 as getsina data = getsina.getQuotation(["sz128014", "sz128014"]) cons = ts.get_apis() df = ts.new_cbonds() #df_head = df.head(5) #print df_head start = time.time() real_price = ts.quotes('128016', conn=cons) elapsed_per = (time.time() - start) / 10 print "ts.quotes comsume: %r" % (elapsed_per) ''' ([u'code', u'price', u'last_close', u'open', u'high', u'low', u'vol', u'cur_vol', u'amount', u's_vol', u'b_vol', u'bid1', u'ask1', u'bid_vol1', u'ask_vol1', u'bid2', u'ask2', u'bid_vol2', u'ask_vol2', u'bid3', u'ask3', u'bid_vol3', u'ask_vol3', u'bid4', u'ask4', u'bid_vol4', u'ask_vol4', u'bid5', u'ask5', u'bid_vol5', u'ask_vol5'], dtype='object') ''' real_price = real_price.loc[:, [ 'code', 'price', 'bid1', 'bid_vol1', 'ask1', 'ask_vol1' ]] data = getsina.getQuotation(["sz128016"]) data = data.loc[:, ['code', 'bid', 'b1', 'b1_v', 'a1', 'a1_v']]
def monitor(self): while 1: current = trading_time() if current == MARKET_OPENING: try: price_df = ts.quotes(self.code_list, conn=self.api) except Exception as e: logger.info(e) self.api = ts.get_apis() time.sleep(EXECEPTION_TIME) else: price_df = price_df[price_df['cur_vol'] != 0] price_df['percent'] = ( price_df['price'] - price_df['last_close']) / price_df['last_close'] * 100 price_df['percent'] = price_df['percent'].map( lambda x: round(x, 2)) ret_dt = price_df[(price_df['percent'] > 2) | (price_df['percent'] < -2)][[ 'code', 'price', 'percent' ]] if len(ret_dt) > 0: name_list = [] yjl_list = [] # 只会提醒一次,下次就不会再出来了 for i in ret_dt['code']: name_list.append(self.stocks[i]) yjl_list.append(self.stocks_yjl[i]) self.code_list.remove(i) ret_dt['name'] = name_list ret_dt[u'溢价率'] = yjl_list ret_dt = ret_dt.sort_values(by='percent', ascending=False) ret_dt = ret_dt.reset_index(drop=True) try: sendmail(ret_dt.to_string(), '波动的可转债') logger.info("Send mail successfully at {}".format( datetime.datetime.now())) except Exception as e: logger.info('sending mail failed') logger.info(e) time.sleep(LOOP__TIME) elif current == -1: time.sleep(LOOP__TIME) elif current == 1: try: ts.close_apis(self.api) except Exception as e: logger.info('fail to stop monitor {}'.format( datetime.datetime.now())) logger.info(e) exit(0)
def monitor(self): while 1: current = trading_time() if current == MARKET_OPENING: # 持仓 try: price_df = ts.quotes(self.code_lists, conn=self.api) except Exception as e: logger.error('获取持仓数据异常>>> {}'.format(e)) try: self.api = ts.get_apis() except Exception as e: logger.error('重新启动get_api出错 {}'.format(e)) else: # 去除不合法的数据 price_df = price_df.dropna() filter_df = price_df[price_df['last_close'] != 0] filter_df = filter_df.reset_index(drop=True) filter_df['percent'] = (filter_df['price'] - filter_df['last_close'] ) / filter_df['last_close'] * 100 filter_df['percent'] = filter_df['percent'].map( lambda x: round(x, 2)) ret_df = filter_df[ (filter_df['percent'] > ALERT_PERCENTAGE) | (filter_df['percent'] < ALERT_PERCENTAGE * -1)] if len(ret_df) > 0: d = dict( zip(list(self.df['证券代码'].values), list(self.df['证券名称']))) ret_df['name'] = ret_df['code'].map(lambda x: d.get(x)) ret_df['amount'] = ret_df['amount'].map( lambda x: round(x / 10000, 1)) rename_column = { 'code': '证券代码', 'name': '证券名称', 'price': '当前价格', 'percent': '涨幅', 'amount': '成交金额(万)' } ret_df = ret_df.rename(columns=rename_column) ret = ret_df[list(rename_column.values())] ret = ret.reset_index(drop=True) content = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') + '\n' + ret.to_string() try: wechat.send_content(content) except Exception as e: logger.error('微信发送失败 {}'.format(e)) # 可转债 try: price_df = ts.quotes(self.kzz_code_list, conn=self.api) except Exception as e: logger.error('获取可转债异常 >>>> {}'.format(e)) try: self.api = ts.get_apis() except Exception as e: logger.error('异常中存在异常{}'.format(e)) # continue time.sleep(EXECEPTION_TIME) # continue else: if len(price_df) != 0: # continue price_df = price_df[price_df['cur_vol'] != 0] price_df['percent'] = (price_df['price'] - price_df['last_close'] ) / price_df['last_close'] * 100 price_df['percent'] = price_df['percent'].map( lambda x: round(x, 2)) ret_dt = price_df[(price_df['percent'] > ALERT_PERCENT) | (price_df['percent'] < -1 * ALERT_PERCENT)][[ 'code', 'price', 'percent' ]] if len(ret_dt) > 0: name_list = [] yjl_list = [] # 只会提醒一次,下次就不会再出来了 for i in ret_dt['code']: name_list.append(self.stocks[i]) yjl_list.append(self.stocks_yjl[i]) self.kzz_code_list.remove(i) ret_dt['name'] = name_list ret_dt[u'溢价率'] = yjl_list ret_dt = ret_dt.sort_values(by='percent', ascending=False) ret_dt1 = ret_dt.reset_index(drop=True) content0 = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S' ) + '\n' + ret_dt1.to_string() try: wechat.send_content(content0) except Exception as e: logger.info('发送微信失败') logger.info(e) # 自选池 try: price_pool = ts.quotes(self.pool_list, conn=self.api) except Exception as e: logger.error('获取自选错误 >>> {}'.format(e)) try: self.api = ts.get_apis() except Exception as e: logger.error('异常中出现异常 {}'.format(e)) time.sleep(EXECEPTION_TIME) # continue # continue else: if len(price_pool) == 0: continue price_pool = price_pool[price_pool['cur_vol'] != 0] price_pool['percent'] = (price_pool['price'] - price_pool['last_close'] ) / price_pool['last_close'] * 100 price_pool['percent'] = price_pool['percent'].map( lambda x: round(x, 2)) ret_dt_pool = price_pool[ (price_pool['percent'] > ALERT_PERCENT_POOL) | (price_pool['percent'] < -1 * ALERT_PERCENT_POOL)][[ 'code', 'price', 'percent' ]] if len(ret_dt_pool) > 0: name_list_pool = [] # 只会提醒一次,下次就不会再出来了 for i in ret_dt_pool['code']: name_list_pool.append(self.pool_dict[i]) self.pool_list.remove(i) ret_dt_pool['name'] = name_list_pool ret_dt_pool = ret_dt_pool.sort_values(by='percent', ascending=False) ret_dt_pool = ret_dt_pool.reset_index(drop=True) content1 = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S' ) + '\n' + ret_dt_pool.to_string() try: wechat.send_content(content1) except Exception as e: logger.error('微信发送异常{}'.format(e)) time.sleep(LOOP_TIME) elif current == -1: time.sleep(LOOP_TIME) elif current == 1: try: ts.close_apis(self.api) except Exception as e: logger.info('fail to stop monitor {}'.format( datetime.datetime.now())) logger.info(e) exit(0)
from setting import get_engine import pandas as pd import tushare as ts import numpy as np engine = get_engine('db_zdt') table = '20180328zdt' api = ts.get_apis() df = pd.read_sql(table, engine, index_col='index') # print df price_list = [] percent_list = [] amplitude_list = [] start = datetime.datetime.now() for i in df[u'代码'].values: try: curr = ts.quotes(i, conn=api) last_close = curr['last_close'].values[0] curr_price = curr['price'].values[0] amplitude = round(((curr['high'].values[0] - curr['low'].values[0]) * 1.00 / last_close) * 100, 2) # if last_close>=curr_price: # print i, # print df[df[u'代码']==i][u'名称'].values[0], # print percent except Exception, e: print e curr_price = 0 if last_close == 0: percent = np.nan percent = round((curr_price - last_close) * 100.00 / last_close, 2) percent_list.append(percent)
def get_premium(self): ''' 获得实时折溢价情况 :return: ''' if self.df_convertbond_basic_info.empty: print("先获取可转债基本信息表!") return columns_name = [ "bond_code", "bond_name", "convert_price", "stock_code", "stock_name" ] record_list = [] for i in range(self.ui.tableWidget.rowCount()): item = self.ui.tableWidget.cellWidget(i, 0).checkState() if item == QtCore.Qt.Checked: # 转债代码,转债名称,正股代码,正股名称 tmp = [ self.ui.tableWidget.item(i, 1).text(), self.ui.tableWidget.item(i, 2).text(), self.ui.tableWidget.item(i, 7).text(), self.ui.tableWidget.item(i, 4).text(), self.ui.tableWidget.item(i, 3).text() ] record_list.append(tmp) # 获取转债实时价格,正股价格所需要的code以及算折溢价需要的convert_price df_premium = pd.DataFrame(data=record_list, columns=columns_name) bond_codes = df_premium["bond_code"] # 获取转债实时价格 """ Index(['code', 'price', 'last_close', 'open', 'high', 'low', 'vol', 'cur_vol', 'amount', 's_vol', 'b_vol', 'bid1', 'ask1', 'bid_vol1', 'ask_vol1', 'bid2', 'ask2', 'bid_vol2', 'ask_vol2', 'bid3', 'ask3', 'bid_vol3', 'ask_vol3', 'bid4', 'ask4', 'bid_vol4', 'ask_vol4', 'bid5', 'ask5', 'bid_vol5', 'ask_vol5'], dtype='object') """ bond_rt_price = ts.quotes(bond_codes, conn=self.cons) # print(type(bond_rt_price)) print(bond_rt_price) if bond_rt_price.empty: print("获取转债实时行情为空") return # 只取一些列 bond_rt_columns = [ 'code', 'price', 'bid1', 'bid_vol1', 'ask1', 'ask_vol1', 'bid2', 'bid_vol2', 'ask2', 'ask_vol2' ] bond_rt_price = bond_rt_price.loc[:, bond_rt_columns] dic_rename = { 'code': 'bond_code', 'price': 'bond_price', 'bid1': 'bond_bid1', 'bid_vol1': 'bond_bid_vol1', 'ask1': 'bond_ask1', 'ask_vol1': 'bond_ask_vol1', 'bid2': 'bond_bid2', 'bid_vol2': 'bond_bid_vol2', 'ask2': 'bond_ask2', 'ask_vol2': 'bond_ask_vol2' } bond_rt_price = bond_rt_price.rename(columns=dic_rename) df_premium["stock_code"] = df_premium["stock_code"].map( self.standard_code) # 获取对应的正股股价 """ Index(['name', 'open', 'pre_close', 'price', 'high', 'low', 'bid', 'ask', 'volume', 'amount', 'b1_v', 'b1_p', 'b2_v', 'b2_p', 'b3_v', 'b3_p', 'b4_v', 'b4_p', 'b5_v', 'b5_p', 'a1_v', 'a1_p', 'a2_v', 'a2_p', 'a3_v', 'a3_p', 'a4_v', 'a4_p', 'a5_v', 'a5_p', 'date', 'time', 'code'], dtype='object') """ stock_rt_price = ts.get_realtime_quotes(df_premium["stock_code"]) pd.set_option('display.max_columns', None) if stock_rt_price.empty: print("获取正股实时行情为空") return stock_columns = [ 'code', 'name', 'price', 'bid', 'ask', 'b2_p', 'b2_v', 'a2_p', 'a2_v', 'a1_v', 'b1_v' ] stock_rt_price = stock_rt_price.loc[:, stock_columns] dic_stock_rename = { 'code': "stock_code", "price": "stock_price", "bid": "stock_bid", 'ask': "stock_ask", 'b2_p': "stock_b2_p", 'b2_v': 'stock_b2_v', 'a2_p': 'stock_a2_p', 'a2_v': 'stock_a2_v' } stock_rt_price = stock_rt_price.rename(columns=dic_stock_rename) # 1 基本信息表与bond实时数据的合并 bond = pd.merge(df_premium, bond_rt_price, on="bond_code") # 2 上面合并信息与stock实时数据的合并 bond_total = pd.merge(bond, stock_rt_price, on="stock_code") columns_need_2_float = [ "convert_price", "bond_price", "bond_bid1", "bond_ask1", "bond_bid2", "bond_ask2", "stock_price", "stock_bid", "stock_ask", "stock_b2_p", "stock_a2_p" ] bond_total[columns_need_2_float] = bond_total[ columns_need_2_float].apply(pd.to_numeric) bond_total["bond2amount"] = bond_total["convert_price"].map( self.amount) # stockbid2bondprice > bond 价格才有套利价值,此时买入转债,卖出正股,可以实现无风险实时套利 # 将正股买一价折算成转债价格 bond_total = bond_total[bond_total["stock_price"] != 0] bond_total["stockbid2bondprice"] = bond_total[ "bond2amount"] * bond_total["stock_price"] * 10 for i in range(len(bond_total)): if bond_total.iloc[ i, bond_total.columns.get_loc("stockbid2bondprice")] == 0: print("正股价折算成债券价格为0,return,原因可能是没有获取到正股价格,在刷新一遍") return bond_total["premium"] = (bond_total["bond_bid1"] - bond_total["stockbid2bondprice"]) / \ bond_total["stockbid2bondprice"] # 按照折溢价情况排序 bond_total = bond_total.sort_values(by=["premium"]) self.df_bond_total = bond_total
def get_bond_stock_tick(self): ''' 在获取到premium信息后,双击premium表的某行,获取转债与正股的bid-ask信息,判断是否进行套利 :return: ''' bond_code = self.ui.lineEdit_2.text() stock_code = self.kezhuanzhai.loc[bond_code, ["stock_code"]].stock_code self.ui.lineEdit_3.setText(stock_code) self.ui.lineEdit_5.setText( self.kezhuanzhai.loc[bond_code, ["bond_name"]].bond_name) self.ui.lineEdit_4.setText( self.kezhuanzhai.loc[bond_code, ["stock_name"]].stock_name) bond_realtime_price = ts.quotes(bond_code, conn=self.cons) bond_realtime_price = bond_realtime_price.set_index("code") stock_realtime_price = ts.get_realtime_quotes(stock_code) #print("stock rt price:%r "%stock_realtime_price) stock_realtime_price = stock_realtime_price.set_index("code") if not bond_realtime_price.empty: #bond bid2 item = str( round(bond_realtime_price.loc[bond_code, ["bid2"]].bid2 / 10, 3)) newItem1 = QtWidgets.QTableWidgetItem(item) self.ui.tableWidget.setItem(3, 0, newItem1) #bond bid1 item = str( round(bond_realtime_price.loc[bond_code, ["bid1"]].bid1 / 10, 3)) newItem1 = QtWidgets.QTableWidgetItem(item) self.ui.tableWidget.setItem(2, 0, newItem1) #bond ask1 item = str( round(bond_realtime_price.loc[bond_code, ["ask1"]].ask1 / 10, 3)) newItem1 = QtWidgets.QTableWidgetItem(item) self.ui.tableWidget.setItem(1, 0, newItem1) #bond ask2 item = str( round(bond_realtime_price.loc[bond_code, ["ask2"]].ask2 / 10, 3)) newItem1 = QtWidgets.QTableWidgetItem(item) self.ui.tableWidget.setItem(0, 0, newItem1) # bond bid_vol2 item = str( int(bond_realtime_price.loc[bond_code, ["bid_vol2"]].bid_vol2)) newItem1 = QtWidgets.QTableWidgetItem(item) self.ui.tableWidget.setItem(3, 1, newItem1) # bond bid_vol1 item = str( int(bond_realtime_price.loc[bond_code, ["bid_vol1"]].bid_vol1)) newItem1 = QtWidgets.QTableWidgetItem(item) self.ui.tableWidget.setItem(2, 1, newItem1) # bond ask_vol1 item = str( int(bond_realtime_price.loc[bond_code, ["ask_vol1"]].ask_vol1)) newItem1 = QtWidgets.QTableWidgetItem(item) self.ui.tableWidget.setItem(1, 1, newItem1) # bond ask_vol2 item = str( int(bond_realtime_price.loc[bond_code, ["ask_vol2"]].ask_vol2)) newItem1 = QtWidgets.QTableWidgetItem(item) self.ui.tableWidget.setItem(0, 1, newItem1) if not stock_realtime_price.empty: #stock ask2 #print(stock_realtime_price) item = str(stock_realtime_price.loc[stock_code, ["a2_p"]].a2_p) newItem1 = QtWidgets.QTableWidgetItem(item) self.ui.tableWidget.setItem(0, 3, newItem1) # stock ask1 item = str(stock_realtime_price.loc[stock_code, ["a1_p"]].a1_p) newItem1 = QtWidgets.QTableWidgetItem(item) self.ui.tableWidget.setItem(1, 3, newItem1) # stock bid1 item = str(stock_realtime_price.loc[stock_code, ["b1_p"]].b1_p) newItem1 = QtWidgets.QTableWidgetItem(item) self.ui.tableWidget.setItem(2, 3, newItem1) # stock bid2 item = str(stock_realtime_price.loc[stock_code, ["b2_p"]].b2_p) newItem1 = QtWidgets.QTableWidgetItem(item) self.ui.tableWidget.setItem(3, 3, newItem1) # stock ask_vol2 item = str(stock_realtime_price.loc[stock_code, ["a2_v"]].a2_v) newItem1 = QtWidgets.QTableWidgetItem(item) self.ui.tableWidget.setItem(0, 4, newItem1) # stock ask_vol1 item = str(stock_realtime_price.loc[stock_code, ["a1_v"]].a1_v) newItem1 = QtWidgets.QTableWidgetItem(item) self.ui.tableWidget.setItem(1, 4, newItem1) # stock bid_vol1 item = str(stock_realtime_price.loc[stock_code, ["b1_v"]].b1_v) newItem1 = QtWidgets.QTableWidgetItem(item) self.ui.tableWidget.setItem(2, 4, newItem1) # stock bid_vol2 item = str(stock_realtime_price.loc[stock_code, ["b2_v"]].b2_v) newItem1 = QtWidgets.QTableWidgetItem(item) self.ui.tableWidget.setItem(3, 4, newItem1) position = self.user.position max_sell_amount = 0 print(position) for stock in position: if stock['证券代码'] == self.ui.lineEdit_3.text(): print("可用余额: %s" % stock['可用余额']) if stock['可用余额'] > 0: max_sell_amount = stock['可用余额'] stock_bid1 = float(self.ui.tableWidget.item(2, 3).text()) max_buy_bond_amount = stock_bid1 * int( max_sell_amount) / float( self.ui.tableWidget.item(1, 0).text()) self.ui.lineEdit_7.setText(str(int(max_buy_bond_amount)))
def stockPrice(self, code): stock_df = ts.quotes(code, conn=self.conn) price = float(stock_df['price'].values[0]) print(code, price) return price
# -*- coding: utf-8 -*- """ Created on Wed Dec 06 14:30:39 2017 @author: zack zhang """ import tushare as ts import os import pandas as pd from pandas import Series from pandas import DataFrame as df import tushare as ts import datetime import time from collections import OrderedDict from decimal import getcontext, Decimal from threading import Timer cons = ts.get_apis() df1 = ts.new_cbonds(default=0) #转债列表,dataframe df2 = ts.new_cbonds(default=1) dfk = ts.bar('128016', conn=cons) #转债日K线,dataframe dftick = ts.tick('128016', conn=cons, date='20171206') #转债tick行情,dataframe dfquotes = ts.quotes('128016', conn=cons) #转债实时切片行情,一行 print dfquotes ''' 1、搞清正股和转债的联动内在逻辑关系(下调转股价等) 2、设定实时行情信号提醒参数 3、技术上实现实时提醒(首选微信) '''
''' kezhuanzhai = pd.read_csv("C:\\quanttime\\src\\convertbond\\kezhuanzhai.csv") bond_codes = kezhuanzhai['bcode'].map(str) #get convertible bond code from csv stock_codes = kezhuanzhai['scode'].map(standard_code) conversion_price = kezhuanzhai[ 'convertprice'] #get convertible bond conversion_price bond2amount = 100 / conversion_price #get every bond(100yuan) transfer to amount of stock #print stock_codes #print bond_codes kezhuanzhai['scode'] = kezhuanzhai['scode'].map(standard_code) kezhuanzhai['bond2amount'] = kezhuanzhai['convertprice'].map(amount) cons = ts.get_apis() #tushare connect context while True: bond_realtime_price = ts.quotes(bond_codes, conn=cons) bond_realtime_price=bond_realtime_price.loc[:,['code','price','bid1','bid_vol1','ask1','ask_vol1',\ 'bid2','bid_vol2','ask2','ask_vol2']] bond_realtime_price.index = pd.RangeIndex(len(kezhuanzhai.index)) stock_realtime_price = ts.get_realtime_quotes(stock_codes) stock_realtime_price = stock_realtime_price.loc[:, [ 'code', 'name', 'price', 'bid', 'ask', 'b2_p', 'b2_v', 'a2_p', 'a2_v' ]] stock_realtime_price = stock_realtime_price.rename(columns={"price":"stockprice",\ "bid":"stockbid",\ 'ask':"stockask",\ 'b2_p':"stockb2_p",\ 'b2_v':'stockb2_v',\ 'a2_p':'stocka2_p',\ 'a2_v':'stocka2_v'})
def init_get_premium(self): """ 获取可转债的实时折溢价情况 可转债csv的columns: stock_name bond_code stock_code bond_name convert_price pb shuishou_price qiangshu_price expire year_to_end """ bond_codes = self.kezhuanzhai['bond_code'].map(str) # get convertible bond code from csv stock_codes = self.kezhuanzhai['stock_code'].map(self.standard_code) conversion_price = self.kezhuanzhai['convert_price'] # get convertible bond conversion_price self.kezhuanzhai['bond_code'] = self.kezhuanzhai['bond_code'].map(str) self.kezhuanzhai['stock_code'] = self.kezhuanzhai['stock_code'].map(self.standard_code) self.kezhuanzhai['bond2amount'] = self.kezhuanzhai['convert_price'].map(self.amount) # 获取转债实时价格 """ Index(['code', 'price', 'last_close', 'open', 'high', 'low', 'vol', 'cur_vol', 'amount', 's_vol', 'b_vol', 'bid1', 'ask1', 'bid_vol1', 'ask_vol1', 'bid2', 'ask2', 'bid_vol2', 'ask_vol2', 'bid3', 'ask3', 'bid_vol3', 'ask_vol3', 'bid4', 'ask4', 'bid_vol4', 'ask_vol4', 'bid5', 'ask5', 'bid_vol5', 'ask_vol5'], dtype='object') """ bond_realTime_price = ts.quotes(bond_codes, conn=self.cons) bond_rt_columns = ['code', 'price', 'bid1', 'bid_vol1', 'ask1', 'ask_vol1', 'bid2', 'bid_vol2', 'ask2', 'ask_vol2'] bond_realTime_price = bond_realTime_price.loc[:, bond_rt_columns] dic_rename = { 'price': 'bond_price', 'bid1': 'bond_bid1', 'bid_vol1': 'bond_bid_vol1', 'ask1': 'bond_ask1', 'ask_vol1': 'bond_ask_vol1', 'bid2': 'bond_bid2', 'bid_vol2': 'bond_bid_vol2', 'ask2': 'bond_ask2', 'ask_vol2': 'bond_ask_vol2' } bond_realTime_price = bond_realTime_price.rename(columns=dic_rename) bond_realTime_price.index = pd.RangeIndex(len(self.kezhuanzhai.index)) # 获取对应的正股股价 """ Index(['name', 'open', 'pre_close', 'price', 'high', 'low', 'bid', 'ask', 'volume', 'amount', 'b1_v', 'b1_p', 'b2_v', 'b2_p', 'b3_v', 'b3_p', 'b4_v', 'b4_p', 'b5_v', 'b5_p', 'a1_v', 'a1_p', 'a2_v', 'a2_p', 'a3_v', 'a3_p', 'a4_v', 'a4_p', 'a5_v', 'a5_p', 'date', 'time', 'code'], dtype='object') """ stock_realTime_price = ts.get_realtime_quotes(stock_codes) stock_realTime_price = stock_realTime_price.loc[:, ['code', 'name', 'price', 'bid', 'ask', 'b2_p', 'b2_v', 'a2_p', 'a2_v', \ 'a1_v', 'b1_v']] stock_realTime_price = stock_realTime_price.rename(columns={"price": "stock_price", \ "bid": "stock_bid", \ 'ask': "stock_ask", \ 'b2_p': "stockb2_p", \ 'b2_v': 'stockb2_v', \ 'a2_p': 'stocka2_p', \ 'a2_v': 'stocka2_v'}) # stock_realtime_price.head(2) bond = pd.merge(self.kezhuanzhai, bond_realTime_price, left_on="bond_code", right_on="code") bond = bond.drop(columns=["code"]) # 去掉一个重复的code列,这个code是可转债实时行情的code ''' bond:index stock_name bond_code stock_code bond_name convert_price pb shuishou_price qiangshu_price expire year_to_end ['price', 'last_close', 'open', 'high', 'low', 'vol', 'cur_vol', 'amount', 's_vol', 'b_vol', 'bid1', 'ask1', 'bid_vol1', 'ask_vol1', 'bid2', 'ask2', 'bid_vol2', 'ask_vol2', 'bid3', 'ask3', 'bid_vol3', 'ask_vol3', 'bid4', 'ask4', 'bid_vol4', 'ask_vol4', 'bid5', 'ask5', 'bid_vol5', 'ask_vol5'] ''' bond[["pb", "convert_price", "shuishou_price", "bond2amount", "bond_price", "bond_bid1", "bond_bid_vol1", "bond_ask1", "bond_ask_vol1", \ "bond_bid2", "bond_bid_vol2", "bond_ask2", "bond_ask_vol2"]] = bond[ ["pb", "convert_price", "shuishou_price", "bond2amount", \ "bond_price", "bond_bid1", "bond_bid_vol1", "bond_ask1", "bond_ask_vol1", \ "bond_bid2", "bond_bid_vol2", "bond_ask2", "bond_ask_vol2"]].convert_objects(convert_numeric=True) # bond.set_index("scode") # stock_realTime_price.set_index("code") # print("bond index:%r"%bond.index) # print("stock_realTime_price index:%r"%stock_realTime_price.index) ''' bond:index stock_name bond_code stock_code bond_name convert_price pb shuishou_price qiangshu_price expire year_to_end ['price', 'last_close', 'open', 'high', 'low', 'vol', 'cur_vol', 'amount', 's_vol', 'b_vol', 'bid1', 'ask1', 'bid_vol1', 'ask_vol1', 'bid2', 'ask2', 'bid_vol2', 'ask_vol2', 'bid3', 'ask3', 'bid_vol3', 'ask_vol3', 'bid4', 'ask4', 'bid_vol4', 'ask_vol4', 'bid5', 'ask5', 'bid_vol5', 'ask_vol5'] Index(['name', 'open', 'pre_close', 'price', 'high', 'low', 'bid', 'ask', 'volume', 'amount', 'b1_v', 'b1_p', 'b2_v', 'b2_p', 'b3_v', 'b3_p', 'b4_v', 'b4_p', 'b5_v', 'b5_p', 'a1_v', 'a1_p', 'a2_v', 'a2_p', 'a3_v', 'a3_p', 'a4_v', 'a4_p', 'a5_v', 'a5_p', 'date', 'time', 'code'], dtype='object') ''' bond = pd.merge(bond, stock_realTime_price, left_on="stock_code", right_on="code") bond = bond.drop(columns=["code"]) # 去掉一个重复的code列,这个code是正股实时行情的code # print("========") # print(stock_realTime_price) bond[["stock_price", "stock_bid", "stock_ask", "stockb2_p", "stockb2_v", "stocka2_p", "stocka2_v"]] \ = bond[["stock_price", "stock_bid", "stock_ask", "stockb2_p", "stockb2_v", "stocka2_p", "stocka2_v"]].convert_objects(convert_numeric=True) # print(bond) # stockbid2bondprice > bond 价格才有套利价值,此时买入转债,卖出正股,可以实现无风险实时套利 bond["stockbid2bondprice"] = bond["bond2amount"] * bond["stock_bid"] * 10 # 将正股买一价折算成转债价格 # bond[["bcode","bid1","stockbid2bondprice","name"]] # print("bond index:%r" % bond.index) bond["premium"] = (bond["bond_bid1"] - bond["stockbid2bondprice"]) / bond["stockbid2bondprice"] # 将premium < 0 有套利机会的选出来,作为重点观察对象 #!!!!!!!!通过修改bond.premium < -0.0X来调整选择的溢价范围!!!!!!!! self.selected_kezhuanzhai = bond[bond.premium < -0.01] print(self.selected_kezhuanzhai) bond["premium"] = bond["premium"].map(self.display_percent_format) bond = bond.round(4) ''' 需要显示的折价情况,为了减少显示的内容,当前只显示'bond_name', 'bond_code', 'stock_code', 'premium','stock_name' 需要增加可以自由添加 display_table_columns = ['bond_name', 'bond_code', 'stock_code', 'premium', 'bond_bid1', 'bond_ask1', 'stock_bid', 'stock_ask', 'stock_name',…………] ''' display_table_columns = ['bond_name', 'bond_code', 'premium', 'stock_code', 'stock_name'] #table = PrettyTable(table_columns) display_df = self.selected_kezhuanzhai.loc[:, display_table_columns] #self.premium_info.emit(display_df.to_dict('index')) self.premium_info.emit(display_df)
def getRealTimePremium(self): kezhuanzhai = pd.read_csv( "kezhuanzhai.csv") #kezhuanzhai.csv与程序放到同一目录下,不再读路径 bond_codes = kezhuanzhai['bcode'].map( str) #get convertible bond code from csv stock_codes = kezhuanzhai['scode'].map(self.standard_code) conversion_price = kezhuanzhai[ 'convertprice'] #get convertible bond conversion_price bond2amount = 100 / conversion_price #get every bond(100yuan) transfer to amount of stock kezhuanzhai['scode'] = kezhuanzhai['scode'].map(self.standard_code) kezhuanzhai['bond2amount'] = kezhuanzhai['convertprice'].map( self.amount) #获取转债实时价格 bond_realtime_price = ts.quotes(bond_codes, conn=self.cons) bond_realtime_price=bond_realtime_price.loc[:, ['code','price','bid1','bid_vol1','ask1','ask_vol1',\ 'bid2','bid_vol2','ask2','ask_vol2']] bond_realtime_price.index = pd.RangeIndex(len(kezhuanzhai.index)) #获取对应的正股股价 stock_realtime_price = ts.get_realtime_quotes(stock_codes) stock_realtime_price = stock_realtime_price.loc[:, [ 'code', 'name', 'price', 'bid', 'ask', 'b2_p', 'b2_v', 'a2_p', 'a2_v' ]] stock_realtime_price = stock_realtime_price.rename(columns={"price":"stockprice",\ "bid":"stockbid",\ 'ask':"stockask",\ 'b2_p':"stockb2_p",\ 'b2_v':'stockb2_v',\ 'a2_p':'stocka2_p',\ 'a2_v':'stocka2_v'}) #stock_realtime_price.head(2) bond = pd.merge(kezhuanzhai, bond_realtime_price, left_on="bcode", right_on="code") kezhuanzhai.set_index("bcode") bond_realtime_price.set_index("code") bond = pd.merge(kezhuanzhai, bond_realtime_price, left_index=True, right_index=True) bond[["pb","convertprice","huishoujia","bond2amount","price","bid1","bid_vol1","ask1","ask_vol1",\ "bid2","bid_vol2","ask2","ask_vol2"]]=bond[["pb","convertprice","huishoujia","bond2amount",\ "price","bid1","bid_vol1","ask1","ask_vol1",\ "bid2","bid_vol2","ask2","ask_vol2"]].convert_objects(convert_numeric=True) bond.set_index("scode") stock_realtime_price.set_index("code") bond = pd.merge(bond, stock_realtime_price, left_index=True, right_index=True) bond[["stockprice","stockbid","stockask","stockb2_p","stockb2_v","stocka2_p","stocka2_v"]] = \ bond[["stockprice","stockbid","stockask","stockb2_p","stockb2_v","stocka2_p","stocka2_v"]].convert_objects(convert_numeric=True) bond["stockbid2bondprice"] = bond["bond2amount"] * bond[ "stockbid"] * 10 #将正股买一价折算成转债价格 bond[["bcode", "bid1", "stockbid2bondprice", "name"]] bond["premium"] = (bond["bid1"] - bond["stockbid2bondprice"] ) / bond["stockbid2bondprice"] #bond[["bcode","bid1","bid1_discount","name","premium"]] select_bond = bond[bond["premium"] > 0.25] for j in range(9): for i in range(7): value = select_bond.iloc[j, i] newItem = QtWidgets.QTableWidgetItem(str(value)) self.setItemContext(j, i, newItem)
def get_realtime_info(self, codes, has_sent, types, stock, yjl, percent): try: price_df = ts.quotes(codes, conn=self.api) except Exception as e: logger.error('获取可转债异常 >>>> {}'.format(e)) try: self.api = ts.get_apis() except Exception as e: logger.error('异常中存在异常{}'.format(e)) time.sleep(EXECEPTION_TIME) else: if len(price_df) != 0: price_df = price_df[price_df['cur_vol'] != 0] price_df['percent'] = ( price_df['price'] - price_df['last_close']) / price_df['last_close'] * 100 price_df['percent'] = price_df['percent'].map( lambda x: round(x, 2)) ret_dt = \ price_df[ (price_df['percent'] > percent) | (price_df['percent'] < -1 * percent)][ ['code', 'price', 'percent']] if len(ret_dt) > 0: # 提醒一次后,下一次的间隔为DELTA_TIME分钟后 # sent_list = [] for i in ret_dt['code']: if has_sent[i] <= datetime.datetime.now(): name_list = [] yjl_list = [] name_list.append(stock[i]) yjl_list.append(yjl[i]) has_sent[i] = datetime.datetime.now( ) + datetime.timedelta(minutes=DELTA_TIME) ret_dt1 = ret_dt[ret_dt['code'] == i] ret_dt1['名称'] = name_list ret_dt1['溢价率'] = yjl_list name = ret_dt1['名称'].values[0] price = ret_dt1['price'].values[0] percent = ret_dt1['percent'].values[0] yjl_v = ret_dt1['溢价率'].values[0] now = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') content0 = '{t}\n{name}:价格:{price} 涨幅:{percent},溢价率:{yjl}'.format( name=name, price=price, percent=percent, yjl=yjl_v, t=now) logger.info(content0) try: wechat.send_content(content0) except Exception as e: logger.info('发送微信失败') logger.info(e)
def stockPrice(self,code): stock_df = ts.quotes(code,conn=self.conn) price = float(stock_df['price'].values[0]) print(code,price) return price