def fetch_realtime(self, codeList = None): if codeList is None: codeList = self.codeList i = 0 while ( self.codeList[i:i+500] != [] ): if (i==0): realtime = ts.get_realtime_quotes( self.codeList[i : i+500] ) else: realtime = realtime.append( ts.get_realtime_quotes( self.codeList[i : i+500] ), ignore_index=True ) i += 500 # Get the datetime data_time = datetime.strptime( realtime.iloc[0]["date"] + " " + realtime.iloc[0]["time"] , '%Y-%m-%d %H:%M:%S') code = realtime["code"] realtime["time"] = data_time # Drop Useless colulmns realtime = realtime.drop( realtime.columns[[0,6,7,30]] ,axis = 1) # Convert string to float realtime = realtime.convert_objects(convert_dates=False,convert_numeric=True,convert_timedeltas=False) # update self.basicInfo & self.outstanding self.self_updated(code) # Compute turn_over_rate realtime["turn_over_ratio"] = realtime["volume"]/self.outstanding/100 realtime["code"] = code return realtime
def getRealData_sk(): klist=cp.get_gplb() tempnum=0 templist=[] partdf=[] alldf=[] for k in klist: tempnum=tempnum+1 templist.append(k) if tempnum==200: try: df = ts.get_realtime_quotes(templist) partdf.append(df) tempnum=0 templist=[] except Exception: print(u'数据读取超时,结束线程') realDate_stop() ''' df = ts.get_realtime_quotes(templist) partdf.append(df) tempnum=0 templist=[] ''' #把最后的数据加入 try: partdf.append(ts.get_realtime_quotes(templist)) alldf=pa.concat(partdf) except Exception: print(u'最后数据读取超时,结束线程') realDate_stop() return alldf
def sellIt(self, code, percent=0, price=0, t_type=None, am=0, av=0): ''' Get Amnt and ask price and sell percentage of all ''' if percent <= 0: return 0 if av == 0: amount, avamnt = self.availableSecurity(code) else: amount = am avamnt = av # 取100之倍數 ceil(autoAmnt(code,fidBroker) * percent) if amount < 100 and percent < 1: # 少於100股就不賣了 print('{'+'"info":"{code}可用證券{x}, 少於100股"'.format(code=code, x=amount)+'}') return 0 autoAmnt = min(avamnt, (amount * percent // 100 * 100)) if 101 > autoAmnt > -1: autoAmnt = 100 # 若未制定賣出價格則自動決定,否則根據制定價格提交 try: if price == 0: #dfq = quote126(code) #bidp = dfq.bid1[code[:-3]] bidp = float(ts.get_realtime_quotes(code).b1_p[0]) bidv = float(ts.get_realtime_quotes(code).b1_v[0]) if bidv > autoAmnt/100: bidprice = bidp else: # 未解決 bidprice = bidp # bidp - 0.001 # bug here! 股票委託價格只能兩位數!基金只能3位數! else: bidprice = price #print(self.briefOrderInfo().tail(3))#.to_string()) ''' 由於經常出現賣不出情況,故降低賣出價位, 最好是採用買一價位,有空時改寫.總之確保賣出 ''' if t_type == 'itc': #如果採用對方限價 result = self.sellAt(code, price=0, amount=autoAmnt) else: result = self.sellAt(code, price=bidprice, amount=autoAmnt) self.db_insert(self.tradings, {'acc_id':self.liveId,'代碼': code, \ '報價': price, '比重': percent,'數量': autoAmnt, '操作': '賣出'}) return result except Exception as e: #dfCancel() print('WebTrader sellAt:') print(e)
def main_7(): # main_4(year=2015, # month=12, # day=10, # date_diff=0, # max_shrink_period=10, # min_shrink_period=3, # code_list_file='all_stocks', # result_file='result_file_4') code_list = read_shrink_code_list('result_file_4') # print "enter here" # 上证指数涨幅: pd = ts.get_realtime_quotes('sh') p_shangzheng = round((float(pd.iloc[0, 1]) - float(pd.iloc[0, 2])) / float(pd.iloc[0, 2]) * 100, 2) # 深圳成指涨幅: pd = ts.get_realtime_quotes('sz') p_shenzhen = round((float(pd.iloc[0, 1]) - float(pd.iloc[0, 2])) / float(pd.iloc[0, 2]) * 100, 2) # 中小板: pd = ts.get_realtime_quotes('zxb') p_zhongxiaoban = round((float(pd.iloc[0, 1]) - float(pd.iloc[0, 2])) / float(pd.iloc[0, 2]) * 100, 2) # print "p_shangzheng", p_shangzheng # print "p_shenzhen", p_shenzhen # print "p_zhongxiaoban", p_zhongxiaoban for key in code_list: for code in code_list[key]: if code[0] == '3': continue df = ts.get_realtime_quotes(code) open = df.iloc[0, 1] pre_close = df.iloc[0, 2] price = df.iloc[0, 3] low = df.iloc[0, 5] p_change = round((float(price) - float(pre_close)) / float(pre_close), 2) if open > pre_close or low > pre_close: # print "p_change", p_change print_string = "" if open > price: print_string += "高开绿柱," else: print_string += "高开红柱," if code[0] == '6' and p_change > p_shangzheng: print_string += "强于大盘," print print_string, str(key), code elif code[:3] == '000' and p_change > p_shenzhen: print_string += "强于大盘," print print_string, str(key), code elif code[:3] == '002' and p_change > p_zhongxiaoban: print_string += "强于大盘," print print_string, str(key), code else: pass
def get_realtime_all_st(symbols=[], retry=60): start = time.time() if len(symbols) < 1: riclist = getcodelist(True) symbols = riclist['code'].values full_df = pd.DataFrame() length = len(symbols) loops = int(length / 300 + 1) for idx in range(0, loops, 1): sublist = symbols[idx * 300:(idx + 1) * 300] for _ in range(retry): try: df = ts.get_realtime_quotes(sublist.tolist()) except Exception as e: err = 'Error %s' % e print('Error %s' % e) time.sleep(1) else: # print('get daily data for %s successfully' % row.code.encode("utf-8")) break full_df = full_df.append(df) finish = time.time() print (finish - start) full_df.date = pd.to_datetime(full_df.date) full_df.open = full_df.open.astype(np.float64) full_df.pre_close = full_df.pre_close.astype(np.float64) full_df.price = full_df.price.astype(np.float64) full_df.high = full_df.high.astype(np.float64) full_df.low = full_df.low.astype(np.float64) full_df.volume = full_df.volume.astype(np.int64) full_df.amount = full_df.amount.astype(np.float64) return full_df
def set_realtime_quotes(code=['sh'],pause = 10): """ 获取当日所选股票代码的实时数据,code为股票代码列表,pause为每隔多少秒请求一次.从当前时间开始,未测试 将数据存储到数据库中,若当前时间在9:00--15:00之间则实时获取并存入dic{code:dataFrame}中,否则进入睡眠状态 目前睡眠,未考虑是否为交易日 Parameters ------ return list[DataFrame] """ engine = create_engine(ct._ENGINE_) curTime = datetime.now() startTime = curTime.replace(hour=9, minute=0, second=0, microsecond=0) endTime = curTime.replace(hour=15, minute=0, second=0, microsecond=0) delta_s = startTime - curTime delta_e = endTime - startTime if delta_s > timedelta(0, 0, 0): time.sleep(delta_s.total_seconds()) elif delta_e <timedelta(0, 0, 0): time.sleep(delta_s.total_seconds()+86400) _data_ = {} for items in code: _data_[items] = DataFrame() while(curTime<endTime): for item in code: df = ts.get_realtime_quotes(item) #Single stock symbol _data_[item].append(df) time.sleep(pause) curTime = datetime.now() for ite in code: _data_[ite].to_sql('realtime_data',engine,if_exists='append') return _data_
def calc(): all_vest = 0 for stock in all_stocks: code = stock['code'] dg = ts.get_realtime_quotes(stock['code']) df = None d = date.today() count = 0 while (df is None or df.empty) and count < 10: count += 1 d = d - timedelta(days=1) datestr = d.strftime('%Y-%m-%d') log_status('Getting hist data for %s at %s' % (code, datestr)) df = ts.get_hist_data(stock['code'], datestr, datestr) log_status('Done hist data for %s at %s' % (code, datestr)) stock['name'] = dg['name'][0] if (df is None or df.empty) or df.get('turnover') is None: stock['marketvalue'] = 0 else: stock['marketvalue'] = float(df['close'][0]) * float(df['volume'][0]) * 100 / (float(df['turnover'][0] / 100)) / 100000000 group = stock['group'] = group_stock(stock) vest = stock['vest'] = calc_stock(stock) if not group_data.has_key(group): group_data[group] = vest else: group_data[group] += vest all_vest += vest for data in group_data.keys(): print '%s:\t\t%4.1f%%\t\t%s' % (data, group_data[data] * 100 / all_vest, str(group_data[data])) display_stock_group(data, all_vest) print 'all: ' + str(all_vest)
def run(self): print('running ...') i = 0 update = False df_list = [] while(True): #now = datetime.now().strftime('%H:%M:%S') now = datetime.now() pull = (now > active_time[0] and now < active_time[1]) or \ (now > active_time[2] and now < active_time[3]) pull = True if(i == 0 and pull): try: list_temp = [] for ss in slist: df = ts.get_realtime_quotes(ss) list_temp.append(df) df_list = list_temp update = True print('get_realtime_quotes update') except Exception as e: print('get_realtime_quotes: %s' % e) s = '' for x in range(i): s = s + '.' wx.CallAfter(self.context.updateUI, s, df_list, update) ostm.sleep(1) if(i > 0): i = i - 1 else: i = 19 update = False
def run(self): print "Starting " + self.name f_out=open("result/live_hit_line_%s" % (datetime.today().date().strftime('%Y%m%d')), 'a') while True: code = get_code() if not code: return try: current_data = ts.get_realtime_quotes('%s' % (code)) peak_data = pd.read_csv('pd_5days/%s.csv' % (code)).head(1) if current_data.empty or peak_data.empty: continue ph = float(current_data['high'].values[0]) cl = float(current_data['low'].values[0]) price = float(current_data['price'].values[0]) #ma5 = float(peak_data['ma5'].values[0]) #ma10 = float(peak_data['ma10'].values[0]) #ma20 = float(peak_data['ma20'].values[0]) #ma30 = get_ma30(code) ma5, ma10, ma20, ma30 = get_mas_live(code, price) if (ma5 > ma10) and (ma10 > ma20) and (ma20 > ma30) and (ph < 20): if ((cl<=ma10) or (cl<=ma20) or (abs(cl-ma10)<(ma10*0.01)) or (abs(cl-ma20)<(ma20*0.01))): # print code print code, ma5, ma10, ma20, ma30, ph, cl except Exception as e: print 'something wrong with code: %s, %s' % (code, str(e)) f_out.close()
def stock_today_ditail(request, code): """ name,股票名字 open,今日开盘价 pre_close,昨日收盘价 price,当前价格 high,今日最高价 low,今日最低价,竞买价,即“买一”报价 ask,竞卖价,即“卖一”报价 volume,成交量 maybe you need do volume/100 amount,成交金额(元 CNY) date,日期; time,时间; """ context = {} df = ts.get_realtime_quotes(code) context['name'] = df.iloc[0]['name'] context['open'] = df.iloc[0]['open'] context['pre_close'] = df.iloc[0]['pre_close'] context['price'] = df.iloc[0]['price'] context['high'] = df.iloc[0]['high'] context['low'] = df.iloc[0]['low'] context['ask'] = df.iloc[0]['ask'] context['volume'] = df.iloc[0]['volume'] context['amount'] = df.iloc[0]['amount'] context['time'] = df.iloc[0]['amount'] context['date'] = df.iloc[0]['amount'] return JsonResponse(context)
def get_today_tick_ave(code, ave=None): try: dtick = ts.get_today_ticks(code) df = dtick if len(dtick.index) > 0: p_now = dtick['price'].values[0] * 100 ep = dtick['amount'].sum() / dtick['volume'].sum() if not ave == None: if p_now > ave and ep > ave: print ("GOLD:%s ep:%s UP:%s!!! A:%s %s !!!" % (code, ep, p_now, ave, get_now_time())) elif p_now > ave and ep < ave: print ("gold:%s ep:%s UP:%s! A:%s %s !" % (code, ep, p_now, ave, get_now_time())) elif p_now < ave and ep > ave: print ("down:%s ep:%s Dow:%s? A:%s %s ?" % (code, ep, p_now, ave, get_now_time())) else: print ("DOWN:%s ep:%s now:%s??? A:%s %s ???" % (code, ep, p_now, ave, get_now_time())) else: if ep > ave: print ("GOLD:%s ep:%s UP:%s!!! A:%s %s !!!" % (code, ep, p_now, ave, get_now_time())) else: print ("down:%s ep:%s now:%s??? A:%s %s ?" % (code, ep, p_now, ave, get_now_time())) else: df = ts.get_realtime_quotes(code) print "name:%s op:%s price:%s" % (df['name'].values[0], df['open'].values[0], df['price'].values[0]) # print df return df except (IOError, EOFError, KeyboardInterrupt) as e: print("Except:%s" % (e))
def monitortrade(self): conn = pymongo.MongoClient('192.168.222.188', port=27017) # for item in conn.mystock.trade.find({'buytime':re.compile('2016-05-27')}): # for item in conn.mystock.yjbtrade.find({'tradestatus':0}).sort('buytime',pymongo.ASCENDING): # for item in conn.mystock.yjbtrade.find().sort('buytime', pymongo.DESCENDING): # print item['buytime'] # df = ts.get_realtime_quotes(item['code']) # df1 = ts.get_hist_data(item['code']).head(1) # # status = item['detailtype'] # # open = df1['open'][0] # nowprice = df['price'][0] # profit = (float(nowprice) - float(item['buyprice'])) / float(item['buyprice']) * 100 # nowprofit = (float(nowprice) - float(item['buyprice'])) / float(item['buyprice']) * 100 # maxprofit = (float(item['maxprice']) - float(item['buyprice'])) / float(item['buyprice']) * 100 # maxprofit = 0 #已经卖出的股票的收益 # if item['tradestatus']==1: # profit = (float(item['sellprice'])-float(item['buyprice']))/float(item['buyprice'])*100 # # # if profit < 8: # # continue # print '[',status,'] ', item['code'], item['name'], item['buytime'], ' buy price ', item['buyprice'], 'and now price ', nowprice, '最大收益', round(maxprofit, 2), '%', '当前收益:', round(nowprofit,2), '%', '总收益:', round(profit, 2), '%', '持股状态:', item['tradestatus'] df = ts.get_realtime_quotes('603159') nowprice = df['price'][0] profit = (float(nowprice) - 57) / 57 * 100 print '[hand] ', '603159', '上海亚虹', ' buy price ', 57, 'and now price ', nowprice, '当前收益:', round(profit, 2), '%', print '\n'
def getLowestGrowth(startDate, endDate,stockList): result = {} while len(stockList) > 0: try: stockCode = stockList[-1] print stockCode,'is started' #取当天有交易的股票 if float(ts.get_realtime_quotes(stockCode).price) > 0: df_tran = ts.get_h_data(stockCode, start=startDate, end=endDate) #将收盘价转化为数值 df_tran['close'] = df_tran['close'].convert_objects(convert_numeric=True) #按日期由远及近进行排序 df_tran = df_tran.sort_index() stock = {} stock['maxPxAll'] = max(df_tran.close) stock['minPxAll'] = min(df_tran.close) stock['maxGrowthRate'] = (stock['maxPxAll'] - stock['minPxAll'])/stock['minPxAll'] result[stockCode] = stock print stockCode,'is finished' stockList.pop() else: stockList.pop() except URLError,e: print 'Error',stockCode,str(e) continue except BaseException, e: print 'Error',stockCode,str(e) stockList.pop() continue
def k_day_sina_one_stock(_stock_id, _db): # get from web(by tushare) begin = get_micro_second() try: df = ts.get_realtime_quotes(_stock_id) except Exception: log_error("warn:error: %s get_k_data exception!", _stock_id) return -4 # calc cost time log_info("get_k_data [%s] costs %d us", _stock_id, get_micro_second()-begin) if df is None : log_error("warn: stock %s is None, next", _stock_id) return -1 if df.empty: log_error("warn: stock %s is empty, next", _stock_id) return -2 begin = get_micro_second() k_day_sina_one_to_db(_stock_id, df,_db) log_info("one_to_db costs %d us", get_micro_second() - begin) return
def run(self): print "Starting " + self.name f_out=open("result/follower_%s" % (datetime.today().date().strftime('%Y%m%d')), 'a') while True: code = get_code() if not code: return try: current_data = ts.get_realtime_quotes('%s' % (code)) csv_file = 'qfq_data/%s.csv' % (code) if not os.path.exists(csv_file): continue peak_data = pd.read_csv(csv_file) if current_data.empty or peak_data.empty: continue ph_today = float(current_data['high'].values[0]) price = float(current_data['price'].values[0]) if price > 15: continue pre_close = float(current_data['pre_close'].values[0]) pl_today = float(current_data['low'].values[0]) po_today = float(current_data['open'].values[0]) ma5, ma10, ma20, ma30 = get_mas_live_qfq(code, price) if (ma5 < ma10) or (ma10 < ma20): continue if pl_today > ( po_today * 0.96 ) or pl_today > (ma5 * 1.3): continue if hist_zt_qfq(peak_data.head(3), code): print code, ma5, ma10, ma20, ma30 f_out.write('%s\n' % (code)) except Exception as e: print 'something wrong with code: %s, %s' % (code, str(e)) f_out.close()
def updateData(self): self.stk_quotes = ts.get_realtime_quotes(self.stk_code) self.stk_ticks = ts.get_today_ticks(self.stk_code).sort_values(by="time") #df = df.sort("time") #df = ts.get_realtime_quotes(self.stk_code) self.setWindowTitle(str(self.stk_quotes['date'][0] + ' 分笔明细图')) self.repaint()
def puttl(): """" 策略1:认沽期权定价错误套利 k-s-p>3% 认沽期权定价不合理,导致K-S的空间大过权利金,导致可以套利 操作: 买入1张行权价为K,到期日为T的认沽期权,其价格为p,取买二价b2_p 买入1张合约对应数量的标的股票,其价格为s,取当卖二价 平仓:认沽期权行权,卖出股票 市场利率 r=0.057 套利空间 pl=3% """ s = ts.get_realtime_quotes('510050').iloc[0]['price'] r = 0.057 pl = 0.03 fee = 30 do = update_contracts() now =dt.datetime.today() grouped = do.groupby(['strikePrice','expDate']) for name,group in grouped: k, expDate = name p = group[group['contractType']=='PO'].iloc[0]['a1_p'] #买入认沽,采用卖二价 p_id = group[group['contractType']=='PO'].iloc[0]['optID'] T = dt.datetime.strptime(expDate,'%Y-%m-%d')-now gain = (k-float(s)-float(p))*10000 gain_per = gain /(float(s)*10000+float(p)*10000) if gain_per>pl : print('=======================================================================================\n') print('认沽套利:对手价买入',p_id,"对手价买入510050","行权价:",k,"到期日期:",expDate,"剩余天数:",T.days) print('认沽套利:strike=',k,'50etf=',s,'买入认沽=',p,'gain=',gain,'gain%=',gain_per,'expDate=',expDate[:-3],'还剩天数',T.days) return
def meet_price(code, price_up, price_down,type): try: df = ts.get_realtime_quotes(code) except Exception, e: print e time.sleep(5) return 0
def get_stock_data(stock_code): stock_data = [] df = ts.get_realtime_quotes(stock_code) # print(df) stock_data.append(df['name'][0]) stock_data.append(float(df['price'][0])) return stock_data
def realtimetick(code): df = ts.get_realtime_quotes(code) df.insert(0,'uploadtime',nowtime) #df.insert(0,'code',code) df.to_sql('mkt_tickrealtime',engine,if_exists='append') def insertid(): sql = """ALTER TABLE mkt_tickrealtime ADD realtimetick_id int(20) not null auto_increment , ADD primary key (realtimetick_id)""" cursor.execute(sql) countfq = cursor.execute('show columns from mkt_tickrealtime like \'realtimetick_id\'') if countfq == 0: insertid() sql = """create table temp_id as (select realtimetick_id, code,date,time,count(distinct code,date,time) from mkt_tickrealtime group by code,date,time) """ cursor.execute(sql) sql = """ delete from mkt_tickrealtime where realtimetick_id not in(select realtimetick_id from temp_id) """ cursor.execute(sql) sql = """ drop table temp_id """ cursor.execute(sql) '''sql = """
def main(): strategyDir = os.path.join(sys.path[0], 'strategy') codes=[] strategies = [] for child in os.listdir(strategyDir): path = os.path.join(strategyDir, child) if os.path.isdir(path): if not os.path.exists(os.path.join(path, 'strategy.py')): continue strategyScript = '.'.join(['strategy', child, 'strategy']) module = __import__(strategyScript, {}, {}, ['any']) if 'getStockList' in dir(module): codes.extend(module.getStockList()) strategies.append(module) codes = ['%06d' %(int(code)) for code in set(codes)] global price_df price_df = ts.get_realtime_quotes(codes).set_index('code') price_df = price_df.rename_axis(mapper= lambda a: int(a), axis=0) #merge stock info to stock price DataFrame. Drop column 'name' of sotck basics before merge, because it's duplicated in price_df price_df = pd.concat([price_df, stockBasics_df.drop('name', 1).loc[np.intersect1d(stockBasics_df.index, price_df.index)]], axis=1) printStockPrice(price_df) for s in strategies: print utils.getSeperateLine() s.run(price_df)
def monitortrade(self): conn = pymongo.MongoClient('192.168.222.188', port=27017) # for item in conn.mystock.trade.find({'buytime':re.compile('2016-05-27')}): for item in conn.mystock.yjbtrade.find(): # print item['buytime'] df = ts.get_realtime_quotes(item['code']) df1 = ts.get_hist_data(item['code']).head(1) status = item['detailtype'] open = df1['open'][0] nowprice = df['price'][0] profit = (float(nowprice) - float(item['buyprice'])) / float(item['buyprice']) * 100 nowprofit = (float(nowprice) - float(item['buyprice'])) / float(item['buyprice']) * 100 #已经卖出的股票的收益 if item['tradestatus']==1: continue profit = (float(item['sellprice'])-float(item['buyprice']))/float(item['buyprice'])*100 if(status=='lowopencross0'): print '[lowopencross0] ',item['code'],item['buytime'],'buy price ',item['buyprice'],'and now price ',nowprice ,'总收益:',round(profit,2),'%','当前收益:',round(nowprofit,2),'%','持股状态:',item['tradestatus'] if (status == 'highopenlowhigh'): print '[highopenlowhigh] ',item['code'],item['buytime'],' buy price ', item['buyprice'],'and now price ', nowprice,'总收益:',round(profit,2),'%','当前收益:',round(nowprofit,2),'%''持股状态:',item['tradestatus']
def order_place(self): table = self.tableWidget count = table.rowCount() orders = [] for x in xrange(count): ticker = unicode(table.item(x, 0).text()) side = unicode(table.item(x, 2).text()) amount = unicode(table.item(x, 3).text()) price = float(ts.get_realtime_quotes(ticker).price) percent = self.percent price = round(price*(side==u'买' and 1.+percent or 0.99-percent), 2) amount = int(round((int(amount)/100)*100, -2)) orders.append((side, ticker, str(amount), str(price))) message = '\r\n'.join([u'%s %s: %s@%s'%order for order in orders]) reply = QtGui.QMessageBox.question(self, u'下单确认', message, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply != QtGui.QMessageBox.Yes: return for side, ticker, amount, price in orders: if side == u'买': self.account_instance.buy(ticker, price, amount) else: self.account_instance.sell(ticker, price, amount)
def meet_price(code, price_up, price_down,type): try: df = ts.get_realtime_quotes(code) except Exception as 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]) percent = (real_price - pre_close) / pre_close * 100 # print(percent) # percent=df[''] # print(type(real_price)) if real_price >= price_up: print('%s price higher than %.2f , %.2f' % (name, real_price, percent),) print('%') if type=='msn': push_msg(name, real_price, percent, 'up') return 1 elif type=='wechat': push_wechat(name, real_price, percent, 'up') if real_price <= price_down: print('%s price lower than %.2f , %.2f' % (name, real_price, percent),) print('%') if type=='msn': push_msg(name, real_price, percent, 'down') return 1 elif type=='wechat': push_wechat(name, real_price, percent, 'down')
def start(self): size = len(self.feed) try: balance = self.user.balance err_log = self.LOGPATH + 'err.log' trade_log = self.LOGPATH + 'trade.log' start_time = time.strftime("%Y-%m-%d %H:%M",time.localtime()) reserve_amount = balance[0]['enable_balance'] ERR_LOG = open(err_log, 'a') TRADE_LOG = open(trade_log, 'a') if reserve_amount < size * 10000: MASSAGE = '"%s": There is no enough to start the trade\n' %(start_time) ERR_LOG.write(MASSAGE) ERR_LOG.close() else: share = reserve_amount / size for stock in self.feed.load(): quotes = ts.get_realtime_quotes(stock) price = float(quotes.loc[[0], 'price']) * 100 # the price for one hand, 100 share last_price = price / 100 quantity = int(share // price * 100) self.user.buy(stock, price=last_price, amount=quantity) MASSAGE = '%s,%s,%f,%d,buy\n' %(start_time, stock, last_price, quantity) TRADE_LOG.write(MASSAGE) TRADE_LOG.close() except: pass
def stop(self): try: position = self.user.position err_log = self.LOGPATH + 'err.log' trade_log = self.LOGPATH + 'trade.log' ERR_LOG = open(err_log, 'a') TRADE_LOG = open(trade_log, 'a') balance = self.user.balance trade_log = self.LOGPATH + 'trade.log' stop_time = time.strftime("%Y-%m-%d %H:%M",time.localtime()) account_amount = balance[0]['asset_balance'] market_value = balance[0]['market_value'] TRADE_LOG = open(trade_log, 'a') if market_value / account_amount * 100 < 3: MASSAGE = '"%s": stocks have been clearred\n' %(stop_time) ERR_LOG.write(MASSAGE) ERR_LOG.close() else: for term in position: if term['stock_code'] in self.feed.load(): quotes = ts.get_realtime_quotes(term['stock_code']) price = float(quotes.loc[[0], 'price']) * 100 # the price for one hand, 100 share last_price = price / 100 quantity = int(term['enable_amount']) self.user.sell(term['stock_code'], price=last_price, amount=quantity) MASSAGE = '%s,%s,%f,%d,sell\n' %(stop_time, term['stock_code'], last_price, quantity) TRADE_LOG.write(MASSAGE) TRADE_LOG.close() except: pass
def deal(self): conn = self.conn for item in conn.mystock.yjbtrade.find({'tradestatus':0}): try: df = ts.get_realtime_quotes(item['code']) # 取得开始时间开始的最大值 starttime = item['buytime'].split(' ')[0] # 最大值需要替换前面程序 maxprice = round(float(item['maxprice']), 2) nowprice = round(float(df['price'][0]), 2) if nowprice == 0.0: continue preclose = round(float(df['pre_close'][0]), 2) lossprice = round(float(df['low'][0]), 2) #如果当天,更新最大价格 if starttime == self.today: # 更新最大收益价格值 if (nowprice > maxprice): conn.mystock.yjbtrade.update({'code': item['code'],'buytime':item['buytime']}, {'$set': {'maxprice': nowprice}}) # 更新最低价格 if (nowprice < lossprice): conn.mystock.yjbtrade.update({'code': item['code'],'buytime':item['buytime']}, {'$set': {'lossprice': lossprice}}) continue # 更新最大收益价格值 if (nowprice > maxprice): conn.mystock.yjbtrade.update({'code': item['code'],'buytime':item['buytime']}, {'$set': {'maxprice': nowprice}}) # 当前收益 profit = round((float(nowprice) - float(item['buyprice'])) / float(item['buyprice']) * 100, 2) # 最大收益 maxprofit = round((float(maxprice) - float(item['buyprice'])) / float(item['buyprice']) * 100, 2) # 当天收益 todayprofit = round((float(nowprice) - float(preclose)) / float(preclose) * 100, 2) # 坑爹的卖出价格计算 sellprice = round(float(nowprice) * 0.98, 2) #可以卖出标识 if item['tradestatus']==0: #止损卖出 sellcount = item['stockcount'] # if nowprice < item['lossprice']: # print "nowprice",nowprice," item['lossprice']",item['lossprice'] # self.sellStock(item['code'].encode("utf-8"), sellprice, sellcount, 'zhisun', item['buytime']) #止盈卖出= if self.ifSell(profit, maxprofit, todayprofit, 0): self.sellStock(item['code'].encode("utf-8"), sellprice, sellcount, 'zhiying', item['buytime']) except Exception as e: print e continue
def get_realtime_detail(code): try: df = ts.get_realtime_quotes(code) field_dict = json.loads(df.to_json(orient='records'))[0] except IOError: pass from models import StockDetail return StockDetail(field_dict)
def download(self): codes = self.stockBasics.index.values fqFactorDF = DataFrame() codeDF = DataFrame() for code in codes: descStr = " (%s, %s) "%(code, self.date) _intervalFactor = 2 _interval = self.interval _retryCount = 0 while _retryCount < self.retryTimes: _retryCount += 1 logging.info("Downloading daily %s trying %d times."%(descStr, _retryCount)) _interval *= _intervalFactor try: # a brand new code into market may cause '_parase_fq_factor' raise exceptions _df = ts.get_realtime_quotes(code) if _df is None: # if the code is off the market, this could happen break _df = _df[['code','open','high','pre_close','price','low','volume','amount','date']].set_index('date') _df.rename(columns={'price':'close'},inplace=True) # a brand new code into market, could also like this, the get_realtime_quotes may return something if ((float(_df['high']) == 0) & (float(_df['low'])==0)): break # no need to store _fqDF = ts.stock.trading._parase_fq_factor(code,'','') _fqDF.insert(0,"code",code,True) _fqDF = _fqDF.drop_duplicates('date').set_index('date').sort_index(ascending=False) #_fqDF = _fqDF.ix[self.date] _fqDF = _fqDF.head(1) # stock may exit the market or just pause if ((float(_df['high']) == 0) & (float(_df['low'])==0)): break # no need to store #_rate = float(_fqDF['factor'])/float(_df['pre_close']) else: _rate = float(_fqDF['factor'])/float(_df['close']) _df = _df.drop('pre_close',axis=1) for label in ['open', 'high', 'close', 'low']: _df[label] = float(_df[label]) * _rate #_df[label] = _df[label].map(lambda x:'%.2f'%x) _df[label] = _df[label].astype(float) except Exception, e: if _retryCount + 1 == self.retryTimes or conf.DEBUG: raise e logging.info("Download error, waiting for %d secs."%_interval) time.sleep(_interval) continue fqFactorDF = pd.concat([fqFactorDF,_fqDF]) codeDF = pd.concat([codeDF, _df]) break if conf.DEBUG: break
def realtime_write(): con=sql.connect(workdir+'concept1.db') concept_all_stock=sql2.read_sql('select * from concept',con) con.close() con=sql.connect(workdir+'realtime_'+datetime.now().date().strftime('%Y%m%d')+'.db') con.execute('PRAGMA journal_mode=WAL') #con.execute('PRAGMA cache_size =80000') #con.execute('PRAGMA synchronous = off') #con.execute('PRAGMA page_size = 8192') #con.execute('PRAGMA temp_store = MEMORY') #con.execute('PRAGMA wal_autocheckpoint=10000000') creat_table_command='create table if not exists realtime(open,pre_close,price,high,low,volume,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,time,code)' insert_table_command='INSERT INTO realtime VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)' con.execute(creat_table_command) #con.execute('create index if not exists code on realtime(code)') concept_name=list(set(concept_all_stock.c_name)) stock_code=list(set(concept_all_stock.code)) #all_time=pd.DataFrame() last_time=pd.DataFrame() n=0 #time1=time.clock() while True : try: one_time=pd.DataFrame() for i in range(5): temp=ts.get_realtime_quotes(stock_code[i*500:(i+1)*500]) temp=temp.drop(['name','date','bid','ask','amount'],axis=1) one_time=one_time.append(temp) except: continue new_one_time=last_time.append(one_time).drop_duplicates()[len(last_time.index):] if len(new_one_time)==0: print 'no new data' continue #sql2.to_sql(new_one_time,'realtime',con,if_exists='append',index=True) time1=time.clock() con.executemany(insert_table_command,new_one_time.values) con.commit() time2=time.clock() #new_one_time=new_one_time.set_index([pd.to_datetime(new_one_time.time),new_one_time.code]) #all_time=all_time.append(new_one_time) last_time=one_time #print len(all_time.index) n+=1 print n,len(new_one_time.index),time2-time1
def getAllChinaStock2(): df_list = pd.read_csv(cm.DownloadDir + cm.TABLE_STOCKS_BASIC + '.csv') stockList = df_list['code'].values stockList_group = util.group_list(stockList, 20) print len(stockList_group) print stockList_group[1] stockList = [] for group in stockList_group: df = ts.get_realtime_quotes(group) for se in df.get_values(): stock = st.Stock('') stock.code = se[0] stock.name = se[1] stock.current = se[3] stock.open = se[4] stock.high = se[5] stock.low = se[6] stock.close = se[7] stock.dealAmount = se[8] / 100 stock.time = time.localtime(time.time()) #时间 #print stock stockList.append(stock) return stockList
def stock(): time = datetime.datetime.now() # 获取当前时间 now = time.strftime('%H:%M:%S') data = ts.get_realtime_quotes(stock_symbol) # 获取股票信息 r1 = float(data['price']) name = data['name'] r2 = name + ' ' + str(stock_symbol) + ' 的当前价格为 ' + str(r1) content = now + '\n' + r2 itchat.send(content, toUserName='******') # print itchat.get_contact() # flist = itchat.get_friends() # for item in flist: # print item # print(content) # 设置预警价格并发送预警信息 if r1 <= float(price_low): itchat.send('低于最低预警价格', toUserName='******') print('低于最低预警价格') elif r1 >= float(price_high): itchat.send('高于最高预警价格', toUserName='******') print('高于最高预警价格') else: itchat.send('价格正常', toUserName='******') print('价格正常')
def get_predict_data(file_name): f = open(file_name) (filepath, temp_file_name) = os.path.split(file_name) (stock_code, extension) = os.path.splitext(temp_file_name) f = pd.read_csv(f) data_now = time.strftime('%Y-%m-%d', time.localtime(time.time())) hist_data = f[-args.time_step + 1:] real_data = ts.get_realtime_quotes(stock_code) real_data = real_data[['open', 'high', 'price', 'low', 'volume']] real_data.insert(0, 'date', data_now) p_change = (float(real_data.iloc[-1, 3]) - float(hist_data.iloc[-1, 3])) / float(hist_data.iloc[-1, 3]) real_data['p_change'] = p_change real_data.rename(index=str, columns={"price": "close"}, inplace=True) real_data[['open', 'high', 'close', 'low', 'volume', 'p_change']] = \ real_data[['open', 'high', 'close', 'low', 'volume', 'p_change']].astype('float') hist_data = hist_data.append(real_data) print("---------数据更新完成-----------") pre_data = hist_data.iloc[:, 1:].values x = (pre_data - np.mean(pre_data, axis=0)) / np.std(pre_data, axis=0) # 标准化 x = [x.tolist()] print(np.shape(x)) return x, stock_code
def getStockData(): """ 获取股票实时数据 :return:股票实时数据 """ global stock_codes code_name_price = [] try: df = ts.get_realtime_quotes(stock_codes) df_len = len(df) for stock_code in stock_codes: is_found = False for i in range(df_len): actual_code = df['code'][i] if stock_code == actual_code: code_name_price.append( (actual_code, df['name'][i], float(df['price'][i]))) is_found = True break if is_found is False: code_name_price.append(('', '', 0)) except: code_name_price = [('', '', 0)] * NUM_OF_STOCKS # 网络不行,返回空 return code_name_price
def continuous(ticket, growthRate=0.02, opentVSclosey=0.98): # dateToday = datetime.datetime.today().strftime('%Y-%m-%d') # Notice: the value of two function is not same, get_hist_data, get_realtime_quotes Point80 = '' Point90 = '' Point95 = '' history = ts.get_hist_data(ticket) op = history['open'] close = history['close'] low = history['low'] thisYesterday = ts.get_hist_data(ticket) closeYesterday = thisYesterday['close'][0] openYesterday = thisYesterday['open'][0] highYesterday = thisYesterday['high'][0] closeBeforeY = thisYesterday['close'][1] openBeforeY = thisYesterday['open'][1] thisToday = ts.get_realtime_quotes(ticket) openToday = thisToday['open'][0] priceToday = thisToday['price'][0] lowToday = thisToday['low'][0] openTodayValue = float(openToday) priceTodayValue = float(priceToday) lowTodayValue = float(lowToday) if (close[0] - op[0]) / op[0] >= growthRate or (low[0] > close[1] and low[0] > op[1]): if openTodayValue / closeYesterday >= opentVSclosey and lowTodayValue >= openYesterday: Point80 = ticket if lowTodayValue >= closeYesterday and ( closeBeforeY - openBeforeY) / openBeforeY >= 0.01: Point90 = ticket if lowTodayValue > highYesterday: Point95 = ticket return Point80, Point90, Point95
def flushStockInformation(): dbo = DataBaseOperator() # dbo.delete(StockInformation, StockInformation.stock_name, "API缺少该股信息") stock_list = dbo.searchAll(StockInformation) for stock in stock_list: try: df = ts.get_realtime_quotes(stock.stock_id) stock.stock_name = df['name'][0] stock.now_price = float(df['price']) stock.flush_time = datetime.strptime( df['date'][0] + " " + df['time'][0], '%Y-%m-%d %H:%M:%S') try: stock.up_down_rate = 100 * (float(df['price'][0]) - float( df['pre_close'][0])) / float(df['pre_close'][0]) except: stock.up_down_rate = 0 except: pass dbo.update() time.sleep(3) flushAliveOrders() global timer timer = threading.Timer(global_flush_time * 60, flushStockInformation) timer.start()
def get_real_time_info(): all_info = None stock_infos = get_classified_stocks() stock_nums = len(stock_infos) i = 0 start_index = 0 while start_index < stock_nums: if start_index + 800 > stock_nums: end_index = stock_nums - 1 else: end_index = start_index + 800 - 1 stock_codes = stock_infos['code'][start_index:end_index] _info = ts.get_realtime_quotes(stock_codes) if start_index == 0: all_info = _info else: frames = [all_info, _info] all_info = pd.concat(frames, ignore_index=True) start_index = end_index + 1 outstandings = [] for index, code_id in all_info['code'].iteritems(): outstanding = stock_infos.query( 'code=="%s"' % code_id).outstanding.values[0] * 1000000 outstandings.append(outstanding) all_info['limit-up-time'] = 0 all_info['limit-dowm-time'] = 0 all_info['date'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S') all_info['outstanding'] = outstandings all_info = all_info[(all_info['volume'].astype(float) > 0) & (all_info['outstanding'] > 0)] all_info['turnover'] = all_info['volume'].astype(float).divide( all_info['outstanding']) all_info['p_change'] = 100 * (all_info['price'].astype(float) - all_info['pre_close'].astype(float)).divide( all_info['pre_close'].astype(float)) return all_info
def get_data_ts(self): #获取开始数据 try: self.code_data = ts.get_k_data( self.code, self.startDate, end=self.endDate) except ValueError: print('Input code is wrong/输入代码错误.') else: self.code_data = self.code_data.sort_index(ascending=True) # 从后倒序 self.code_data.date = self.code_data.date.apply( lambda x: datetime.datetime.strptime(x, "%Y-%m-%d")) #self.code_data.date=self.code_data.date.apply(lambda x:matplotlib.dates.date2num(x)) self.code_data = self.code_data.set_index('date') if self.endDate == '%s' % self.today: todat_realtime = ts.get_realtime_quotes(self.code) realtime_price = float(todat_realtime.price) realtime_high = float(todat_realtime.high) realtime_low = float(todat_realtime.low) realtime_open = float(todat_realtime.open) realtime_volume = float(todat_realtime.volume) self.code_data.loc['%s' % self.today, 'code'] = '%s' % self.code self.code_data.loc['%s' % self.today, 'volume'] = '%s' % realtime_volume self.code_data.loc['%s' % self.today, 'open'] = '%s' % realtime_open self.code_data.loc['%s' % self.today, 'high'] = '%s' % realtime_high self.code_data.loc['%s' % self.today, 'low'] = '%s' % realtime_low self.code_data.loc['%s' % self.today, 'close'] = realtime_price self.df = self.code_data return self.code_data
def updateMarketlist(): sh = ts.get_realtime_quotes('sh') sz = ts.get_realtime_quotes('sz') hs300 = ts.get_realtime_quotes('hs300') sz50 = ts.get_realtime_quotes('sz50') zxb = ts.get_realtime_quotes('zxb') cyb = ts.get_realtime_quotes('cyb') conn = ms.connect(host='localhost', port=3306, user='******', passwd='123456', db='websql', charset="utf8") cur = conn.cursor() s = [sh, sz, hs300, sz50, zxb, cyb] values = [] for x in s: data = pd.DataFrame(x) data1 = Series(list(data['code'])) data2 = Series(list(data['name'])) data3 = Series(list(data['open'])) data4 = Series(list(data['pre_close'])) data5 = Series(list(data['price'])) data6 = Series(list(data['high'])) data7 = Series(list(data['low'])) data8 = Series(list(data['volume'])) data9 = Series(list(data['amount'])) data10 = Series(list(data['time'])) values.append((data1[0].encode("utf-8"), data2[0].encode('utf-8'), data3[0].encode("utf-8"), data4[0].encode("utf-8"), data5[0].encode("utf-8"), data6[0].encode("utf-8"), data7[0].encode("utf-8"), data8[0].encode("utf-8"), data9[0].encode("utf-8"), data10[0].encode("utf-8"))) cur.execute('delete from marketlist') cur.executemany( 'insert into marketlist (code,name,open,pre_close,price,high,low,volume,amount,time) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)', values) conn.commit() cur.close() conn.close()
def greet(name): print("--- hello,%s ---" % name) data = tushare.get_realtime_quotes('600000') print(data)
def __init__(self, code): self.df = ts.get_realtime_quotes(code)
def get_stock_name(stocknumber): realtimeData = ts.get_realtime_quotes(stocknumber) realtimeData = realtimeData.to_dict('record') stock_name = realtimeData[0]['name'] return stock_name
#最高价的比率 high_price_rate = 0.97 #涨幅最大比率 up_price_high = 1.07 #上影线比率 up_line_rate = 0.3 #读取所有股票代码 df_stock = pd.DataFrame(pd.read_csv('C:/stock_data/all_code.csv', index_col=None)) print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) #日期格式化 for stockCode in df_stock.code: # print('code-------------'+"%06d"%stockCode) try: df_today = ts.get_realtime_quotes("%06d"%stockCode) # 获取股票实时数据 # print(df_today) # 实时成交量 volume_today = int(df_today.iloc[0].volume)/100 # print('volume_today-----------'+str(volume_today)) # 今日最高价 high_today = df_today.iloc[0].high # 今日时价 price_today = df_today.iloc[0].price # print('high_today-----------'+str(high_today)) #从csv文件中获取历史的股票数据 df_history = pd.DataFrame(pd.read_csv('C:/stock_data/' + var_date + '/' + "%06d" % stockCode + '.csv', index_col=None)) # 历史成交量 volume_yestoday_1 = df_history.iloc[0].volume
def get_price(self): df = ts.get_realtime_quotes(self.stock_code) price = float(df['b1_p'].tolist()[0]) return price
ts.get_report_data(2017, 2).to_sql('report', engine, if_exists='append') print('basic information over ....') basic_information() @retry(tries=5, delay=2) def get_today(): today_all = ts.get_today_all() print(today_all[:5]) get_today() realtime = ts.get_realtime_quotes("603618") realtime2 = ts.get_realtime_quotes(["sh", "zs", "hs300", "sz50", "zxb", "cyb"]) # get news # ts.guba_sina().to_sql('guba_sina',engine,if_exists='append') print('guba_sina') # ts.get_notices().to_sql('notices',engine,if_exists='append') print('notices') ts.get_latest_news().to_sql('latest_news', engine, if_exists='append') print('latest_news') # save all stock to mysql # open high close low volume p_change # conn = pymysql.connect('localhost','root','caicai520','quantist') # cursor = conn.cursor() # cursor.execute("select distinct good1 from t_good limit 5")
def bars(codes): """获取codes的实时quotes""" return ts.get_realtime_quotes(codes)
def getAmt(): df = ts.get_realtime_quotes(ss) print(df[['name', 'price']])
# -*-coding=utf-8-*- import tushare as ts pingan_code='601318' shangqi_code='600104' icbc_code='601398' huada_genic='300676' real_time=ts.get_realtime_quotes([pingan_code,shangqi_code,icbc_code,huada_genic]) need_data=real_time[['name','open','price','high','low','bid','volume','date','time']] print(need_data)
# -×- coding: utf-8 -×- __author__ = 'xlyang0211' import tushare as ts df = ts.get_realtime_quotes(['000581', '601299']) print df print df.iloc[0, 1], df.iloc[0, 2], df.iloc[0, 5]
def test3(): ts_pro = ls.get_ts_pro() df = ts.get_realtime_quotes('601318') print(df)
# Load stock real-time data import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties import tushare as ts import datetime as dt print('Tushare Version ' + ts.__version__) code_num = '000636' try: rdf = ts.get_realtime_quotes(code_num) # Realtime DF print(rdf) tdf = ts.get_today_ticks(code_num) # Tick DF print(tdf) except: print('Download exception') # rdf.index = pd.to_datetime(rdf.date,format="%Y-%m-%d %H:%M") # stk_today = rdf[rdf.index.date==dt.datetime(2018,8,7).date()].copy() # tdf.index = pd.to_datetime(tdf.time,format="%H:%M:%S") tdf = tdf[tdf['time'] > '09:26:00'] tdf.index = pd.to_timedelta(tdf['time']) mdf = tdf.resample('1Min', closed='left').mean().dropna() if True: font_set = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=16) fig, ax = plt.subplots(figsize=(20, 16)) plt.subplot(211) mdf['price'].plot(use_index=True, style='r-',
import tushare as ts del ts # 历史分笔 a = ts.get_tick_data('000005', date='2018-12-24') help(ts) # 当日历史分 b = ts.get_today_ticks('601333', date='2017-01-09') # 实时分笔 ts.get_realtime_quotes('000581') # 历史分笔 和 当日历史分 返回结果 time:时间 price:成交价格 pchange:涨跌幅 change:价格变动 volume:成交手 amount:成交金额(元) type:买卖类型【买盘、卖盘、中性盘】 import easyquotation import tf from urllib.request import urlretrieve f = open('SHA.csv', 'r') for line in f:
#读取所有股票代码 # df_all_code = pd.DataFrame(pd.read_csv(stock_data_path + df_all_code_file, index_col=None)) df_all_code = pd.DataFrame(pd.read_csv(stock_data_path + var_date +'_T_1.csv', index_col=None)) #历史数据日期yyyymmdd文件夹 index_stock = 0 # ,code #直接保存 out = open(stock_data_path + var_date + '_T_1_PM2.csv','a', newline='') csv_write = csv.writer(out,dialect='excel') csv_write.writerow(['',"code","price"]) for stock_code in df_all_code.code: # print('>>>>>>>>>>>'+ "%06d"%stock_code +'>>>>>>>>>') try: # 获取股PM2点的实时数据 df_today = ts.get_realtime_quotes("%06d"%stock_code) # 今日实时(PM2点)价 price_today = df_today.iloc[0].price print("%06d"%stock_code) csv_write.writerow([index_stock,"%06d"%stock_code,price_today]) index_stock += 1 except IndexError: # print("%06d" % stock_code + 'IndexError') continue except FileNotFoundError: # print("%06d" % stock_code + 'FileNotFoundError') continue except urllib.error.URLError: continue except socket.timeout: continue
def get_all_price(code_list): '''按列表内容获取stk实时数据''' df = ts.get_realtime_quotes(STOCK) print(df)
def get_price(): return float(ts.get_realtime_quotes('hs300')['price'])
def jiance(gpdm, pb=1, ps=1, vb=1, vs=1): jl = junliang(gpdm) with open(f"{gpdm}-{datetime.now().date()}.txt", "a") as f: print(f"{gpdm}最近三天均量为{jl}") f.write(f"{gpdm}最近三交易日大单均值{jl}\n") while datetime.now().hour < 15: r = ts.get_realtime_quotes(gpdm) pn = float(r.price[0]) # print(r.b5_v[0]) zheng = 0 fu = 0 # print(r.b1_v[0],r.b2_v[0],r.b3_v[0],r.b5_v[0],r.b1_v[0],) if r.b1_v[0].isdigit(): zheng += float(r.b1_v[0]) # print("买一",r.b1_v[0]) if r.b2_v[0].isdigit(): zheng += float(r.b2_v[0]) # print("买2", r.b2_v[0]) if r.b3_v[0].isdigit(): zheng += float(r.b3_v[0]) if r.b4_v[0].isdigit(): zheng += float(r.b4_v[0]) if r.b5_v[0].isdigit(): zheng += float(r.b5_v[0]) if r.a1_v[0].isdigit(): fu += float(r.a1_v[0]) if r.a2_v[0].isdigit(): fu += float(r.a2_v[0]) if r.a3_v[0].isdigit(): fu += float(r.a3_v[0]) if r.a4_v[0].isdigit(): fu += float(r.a4_v[0]) if r.a5_v[0].isdigit(): fu += float(r.a5_v[0]) # liangbi = (float(r.b1_v[0]) + float(r.b2_v[0]) + float(r.b3_v[0]) + float(r.b4_v[0]) + float(r.b5_v[0])) / (float(r.a1_v[0]) + float(r.a2_v[0]) + float(r.a3_v[0]) + float(r.a4_v[0]) + float(r.a5_v[0])) if zheng == 0 or fu == 0: continue liangbi = zheng / fu print(datetime.now(), gpdm, liangbi, zheng, fu) if liangbi > 10 and (abs(pb - pn) / pb > 0.01 or liangbi > vb * 1.5) and max(zheng, fu) > jl: with open(f"{gpdm}-{datetime.now().date()}.txt", "a") as f: line = f"{datetime.now()}\t买入\t{pn}\t{round(liangbi,2)}\t{zheng}\t{fu}\n" print(line) f.write(line) pb = pn vb = liangbi if liangbi < 0.1 and (abs(ps - pn) / ps > 0.01 or liangbi < vs / 1.5) and max(zheng, fu) > jl: with open(f"{gpdm}-{datetime.now().date()}.txt", "a") as f: line = f"{datetime.now()}\t卖出\t{pn}\t{round(1/liangbi,2)}\t{zheng}\t{fu}\n" print(line) f.write(line) ps = pn vs = liangbi sleep(1)
import tushare as ts import pandas as pd import datetime f = open('../data/stocks.txt') time1 = datetime.datetime.now() stocks = [line.strip() for line in f.readlines()] dw = 880 data1 = ts.get_realtime_quotes(stocks[0:dw]) data2 = ts.get_realtime_quotes(stocks[dw:2 * dw]) data3 = ts.get_realtime_quotes(stocks[2 * dw, 3 * dw]) data4 = ts.get_realtime_quotes(stocks[3 * dw, -1]) time2 = datetime.datetime.now() print(str(time1)) print(str(time2)) print(data1) print(data2) print(data3) print(data4)
def deal(self): conn = self.conn for item in conn.mystock.yjbtrade.find({'tradestatus': 0}): try: df = ts.get_realtime_quotes(item['code']) # 取得开始时间开始的最大值 starttime = item['buytime'].split(' ')[0] # 最大值需要替换前面程序 maxprice = round(float(item['maxprice']), 2) nowprice = round(float(df['price'][0]), 2) if nowprice == 0.0: continue preclose = round(float(df['pre_close'][0]), 2) lossprice = round(float(df['low'][0]), 2) #如果当天,更新最大价格 if starttime == self.today: # 更新最大收益价格值 if (nowprice > maxprice): conn.mystock.yjbtrade.update( { 'code': item['code'], 'buytime': item['buytime'] }, {'$set': { 'maxprice': nowprice }}) # 更新最低价格 if (nowprice < lossprice): conn.mystock.yjbtrade.update( { 'code': item['code'], 'buytime': item['buytime'] }, {'$set': { 'lossprice': lossprice }}) continue # 更新最大收益价格值 if (nowprice > maxprice): conn.mystock.yjbtrade.update( { 'code': item['code'], 'buytime': item['buytime'] }, {'$set': { 'maxprice': nowprice }}) # 当前收益 profit = round((float(nowprice) - float(item['buyprice'])) / float(item['buyprice']) * 100, 2) # 最大收益 maxprofit = round((float(maxprice) - float(item['buyprice'])) / float(item['buyprice']) * 100, 2) # 当天收益 todayprofit = round((float(nowprice) - float(preclose)) / float(preclose) * 100, 2) # 坑爹的卖出价格计算 sellprice = round(float(nowprice) * 0.98, 2) #可以卖出标识 if item['tradestatus'] == 0: #止损卖出 sellcount = item['stockcount'] # if nowprice < item['lossprice']: # print "nowprice",nowprice," item['lossprice']",item['lossprice'] # self.sellStock(item['code'].encode("utf-8"), sellprice, sellcount, 'zhisun', item['buytime']) #止盈卖出= if self.ifSell(profit, maxprofit, todayprofit, 0): self.sellStock(item['code'].encode("utf-8"), sellprice, sellcount, 'zhiying', item['buytime']) except Exception as e: print e continue
def query_stock_read_price(self): df = ts.get_realtime_quotes(self.stock_num) df = df[['price', 'time']] price = df['price'][0] # df['price'][0] == df['price'].values[0] time = df['time'][0] return price, time
def get_now_price(self): return float(ts.get_realtime_quotes(self.code)['price'][0])