当前位置: 首页>>代码示例>>Python>>正文


Python tushare.get_realtime_quotes函数代码示例

本文整理汇总了Python中tushare.get_realtime_quotes函数的典型用法代码示例。如果您正苦于以下问题:Python get_realtime_quotes函数的具体用法?Python get_realtime_quotes怎么用?Python get_realtime_quotes使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了get_realtime_quotes函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: getRealData_sk

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
开发者ID:jhshengxy,项目名称:GetSinaSockData,代码行数:35,代码来源:realData.py

示例2: fetch_realtime

	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
开发者ID:ianchan1988,项目名称:dHydra,代码行数:25,代码来源:dHydra.py

示例3: sellIt

    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)
开发者ID:emptist,项目名称:seshell,代码行数:57,代码来源:WebTrader.py

示例4: main_7

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
开发者ID:xlyang0211,项目名称:AlgorithmicTrading,代码行数:51,代码来源:algorithm_7.py

示例5: get_stock_data

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
开发者ID:ideas4u,项目名称:learngit,代码行数:7,代码来源:autoTrading.py

示例6: start

    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
开发者ID:WesleyDevLab,项目名称:pyquant,代码行数:29,代码来源:trade.py

示例7: stop

    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
开发者ID:WesleyDevLab,项目名称:pyquant,代码行数:33,代码来源:trade.py

示例8: run

 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
开发者ID:cirline,项目名称:ct,代码行数:32,代码来源:main.py

示例9: calc

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)
开发者ID:cosmosdreamer,项目名称:tapestar,代码行数:31,代码来源:marketvalue.py

示例10: k_day_sina_one_stock

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 
开发者ID:saibye,项目名称:project,代码行数:29,代码来源:k_day_sina.py

示例11: monitortrade

    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'
开发者ID:tuoxie119,项目名称:stocktrade,代码行数:32,代码来源:monitor_profit.py

示例12: updateData

 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()
开发者ID:smile921,项目名称:Ciss921,代码行数:7,代码来源:tick.py

示例13: meet_price

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
开发者ID:LiYinglin-Bruce-Lee,项目名称:stock,代码行数:7,代码来源:push_msn.py

示例14: stock_today_ditail

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)
开发者ID:bestainan,项目名称:django-scrapy,代码行数:28,代码来源:views.py

示例15: main

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)
开发者ID:chenxiaoyao,项目名称:stock-strategy,代码行数:27,代码来源:main.py


注:本文中的tushare.get_realtime_quotes函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。