Python tushare.get_realtime_quotes() Examples

The following are 17 code examples of tushare.get_realtime_quotes(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tushare , or try the search function .
Example #1
Source File: base_manager.py    From StrategyEase-Python-SDK with MIT License 6 votes vote down vote up
def repo(self):
        try:
            security = '131810'
            quote_df = ts.get_realtime_quotes(security)
            order = {
                'action': 'SELL',
                'symbol': security,
                'type': 'LIMIT',
                'price': float(quote_df['bid'][0]),
                'amountProportion': 'ALL'
            }
            for trader in self._traders.values():
                try:
                    trader.execute(**order)
                except:
                    self._logger.exception('[%s] 逆回购失败', trader.id)
        except:
            self._logger.exception('逆回购失败') 
Example #2
Source File: uqer.py    From uqtrader with MIT License 6 votes vote down vote up
def get_order(self, strategy_id, all=True):
        """获取订单列表
            :param all:True返回当日所有订单,False返回上次下单后新产生的订单。
        """

        s = self.session
        orders = s.get(order_url%strategy_id).json()
        
        percent = self.percent

        if all:
            return orders
        else:
            tmp_orders = []
            for order in orders:
                price = float(ts.get_realtime_quotes(order['ticker']).price)
                order['price'] = round(price*(order['side']=='BUY' and 1.+percent or 1.-percent), 2)
                tmp_orders.append(order)
            return tmp_orders 
Example #3
Source File: online_data.py    From stock with Apache License 2.0 6 votes vote down vote up
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 
Example #4
Source File: sw.py    From Stock_WeChat with MIT License 6 votes vote down vote up
def get_remind(all_list = []):
    stock_symbol_list, price_low_list, price_high_list = handle(all_list)
    localtime = datetime.datetime.now()    # 获取当前时间
    now = localtime.strftime('%H:%M:%S')
    data = ts.get_realtime_quotes(stock_symbol_list)    # 获取股票信息
    price_list = data['price']
    itchat.send(now, toUserName='filehelper')
    print(now)

    for i in range(int(len(all_list) / 3)):
        content = stock_symbol_list[i] + ' 当前价格为 ' + price_list[i] + '\n'
        if float(price_list[i]) <=  float(price_low_list[i]):
            itchat.send(content + '低于最低预警价格', toUserName='filehelper')
            print(content + '低于最低预警价格')
        elif float(price_list[i]) >=  float(price_high_list[i]):
            itchat.send(content + '高于最高预警价格', toUserName='filehelper')
            print(content + '高于最高预警价格')
        else:
            print(content + '价格正常')
    itchat.send('***** end *****', toUserName='filehelper')
    print('***** end *****\n') 
Example #5
Source File: sw.py    From Stock_WeChat with MIT License 6 votes vote down vote up
def get_push(all_list = []):
    stock_symbol_list, price_low_list, price_high_list = handle(all_list)
    localtime = datetime.datetime.now()    # 获取当前时间
    now = localtime.strftime('%H:%M:%S')
    data = ts.get_realtime_quotes(stock_symbol_list)    # 获取股票信息
    price_list = data['price']
    itchat.send(now, toUserName='filehelper')
    print(now)

    for i in range(int(len(all_list) / 3)):
        content = stock_symbol_list[i] + ' 当前价格为 ' + price_list[i] + '\n'
        if float(price_list[i]) <=  float(price_low_list[i]):
            itchat.send(content + '低于最低预警价格', toUserName='filehelper')
            print(content + '低于最低预警价格')
        elif float(price_list[i]) >=  float(price_high_list[i]):
            itchat.send(content + '高于最高预警价格', toUserName='filehelper')
            print(content + '高于最高预警价格')
        else:
            itchat.send(content + '价格正常', toUserName='filehelper')
            print(content + '价格正常')
    itchat.send('***** end *****', toUserName='filehelper')
    print('***** end *****\n') 
Example #6
Source File: repo.py    From StrategyEase-Python-SDK with MIT License 5 votes vote down vote up
def __call__(self):
        df = ts.get_realtime_quotes(self._symbol)
        order = {
            'action': 'SELL',
            'symbol': self._symbol,
            'type': 'LIMIT',
            'price': float(df['bid'][0]),
            'amountProportion': 'ALL'
        }
        for client_alias in self._client_aliases:
            try:
                client = self._client_aliases[client_alias]
                self._client.execute(client, **order)
            except:
                self._logger.exception('客户端[%s]逆回购失败', client_alias) 
Example #7
Source File: online_data.py    From stock with Apache License 2.0 5 votes vote down vote up
def getAllChinaStock():

    stockList = []
    try:
        df = get_real_price_dataframe()
        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)
    except:
        print 'get real price timeout'

    return stockList

# 获取A股所有股票的实时股价
# 通过get_realtime_quotes接口获取 
Example #8
Source File: views.py    From StockPredict with Apache License 2.0 5 votes vote down vote up
def get_stock_name(stocknumber):
    realtimeData = ts.get_realtime_quotes(stocknumber)
    realtimeData = realtimeData.to_dict('record')
    stock_name = realtimeData[0]['name']
    return stock_name


# 获取分词List 
Example #9
Source File: views.py    From StockPredict with Apache License 2.0 5 votes vote down vote up
def get_stock_name(stock_code):
    real_time_data = ts.get_realtime_quotes(stock_code).to_dict('record')
    stock_name = real_time_data[0]['name']
    return stock_name 
Example #10
Source File: utils.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def get_realtime_quotes(code_list, open_only=False):
    import tushare as ts

    max_len = 800
    loop_cnt = int(math.ceil(float(len(code_list)) / max_len))

    total_df = reduce(lambda df1, df2: df1.append(df2),
                      [ts.get_realtime_quotes([code for code in code_list[i::loop_cnt]])
                       for i in range(loop_cnt)])
    total_df["is_index"] = False

    index_symbol = ["sh", "sz", "hs300", "sz50", "zxb", "cyb"]
    index_df = ts.get_realtime_quotes(index_symbol)
    index_df["code"] = index_symbol
    index_df["is_index"] = True
    total_df = total_df.append(index_df)
    total_df = total_df.set_index("code").sort_index()

    columns = set(total_df.columns) - set(["name", "time", "date"])
    # columns = filter(lambda x: "_v" not in x, columns)
    for label in columns:
        total_df[label] = total_df[label].map(lambda x: 0 if str(x).strip() == "" else x)
        total_df[label] = total_df[label].astype(float)

    total_df["chg"] = total_df["price"] / total_df["pre_close"] - 1

    total_df["order_book_id"] = total_df.index
    total_df["order_book_id"] = total_df["order_book_id"].apply(tushare_code_2_order_book_id)

    total_df["datetime"] = total_df["date"] + " " + total_df["time"]
    total_df["datetime"] = total_df["datetime"].apply(lambda x: convert_dt_to_int(datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S")))

    total_df["close"] = total_df["price"]

    if open_only:
        total_df = total_df[total_df.open > 0]

    return total_df 
Example #11
Source File: views.py    From StockSensation with Apache License 2.0 5 votes vote down vote up
def get_stock_name(stocknumber):
    realtimeData = ts.get_realtime_quotes(stocknumber)
    realtimeData = realtimeData.to_dict('record')
    stock_name = realtimeData[0]['name']
    return stock_name

# 获取分词List 
Example #12
Source File: views.py    From StockSensation with Apache License 2.0 5 votes vote down vote up
def get_stock_name(stock_code):
    real_time_data = ts.get_realtime_quotes(stock_code).to_dict('record')
    stock_name = real_time_data[0]['name']
    return stock_name 
Example #13
Source File: utils.py    From puppet with MIT License 5 votes vote down vote up
def get_realtime_quotes(code_list, open_only=False):
    import tushare as ts

    max_len = 800
    loop_cnt = int(math.ceil(float(len(code_list)) / max_len))

    total_df = reduce(lambda df1, df2: df1.append(df2),
                      [ts.get_realtime_quotes([code for code in code_list[i::loop_cnt]])
                       for i in range(loop_cnt)])
    total_df["is_index"] = False

    index_symbol = ["sh", "sz", "hs300", "sz50", "zxb", "cyb"]
    index_df = ts.get_realtime_quotes(index_symbol)
    index_df["code"] = index_symbol
    index_df["is_index"] = True
    total_df = total_df.append(index_df)
    total_df = total_df.set_index("code").sort_index()

    columns = set(total_df.columns) - set(["name", "time", "date"])
    # columns = filter(lambda x: "_v" not in x, columns)
    for label in columns:
        total_df[label] = total_df[label].map(lambda x: 0 if str(x).strip() == "" else x)
        total_df[label] = total_df[label].astype(float)

    total_df["chg"] = total_df["price"] / total_df["pre_close"] - 1

    total_df["order_book_id"] = total_df.index
    total_df["order_book_id"] = total_df["order_book_id"].apply(tushare_code_2_order_book_id)

    total_df["datetime"] = total_df["date"] + " " + total_df["time"]
    total_df["datetime"] = total_df["datetime"].apply(lambda x: convert_dt_to_int(datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S")))

    total_df["close"] = total_df["price"]

    if open_only:
        total_df = total_df[total_df.open > 0]

    return total_df 
Example #14
Source File: trader.py    From uqtrader with MIT License 5 votes vote down vote up
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) 
Example #15
Source File: utils.py    From InplusTrader_Linux with MIT License 4 votes vote down vote up
def get_realtime_quotes(code_list, open_only=False):
    import tushare as ts

    max_len = 800
    loop_cnt = int(math.ceil(float(len(code_list)) / max_len))

    total_df = reduce(lambda df1, df2: df1.append(df2),
                      [ts.get_realtime_quotes([code for code in code_list[i::loop_cnt]])
                       for i in range(loop_cnt)])
    total_df["is_index"] = False

    index_symbol = ["sh", "sz", "hs300", "sz50", "zxb", "cyb"]
    index_df = ts.get_realtime_quotes(index_symbol)
    index_df["code"] = index_symbol
    index_df["is_index"] = True
    total_df = total_df.append(index_df)

    columns = set(total_df.columns) - set(["name", "time", "date", "code"])
    # columns = filter(lambda x: "_v" not in x, columns)
    for label in columns:
        total_df[label] = total_df[label].map(lambda x: 0 if str(x).strip() == "" else x)
        total_df[label] = total_df[label].astype(float)

    total_df["chg"] = total_df["price"] / total_df["pre_close"] - 1

    total_df["order_book_id"] = total_df["code"]
    total_df["order_book_id"] = total_df["order_book_id"].apply(tushare_code_2_order_book_id)

    total_df = total_df.set_index("order_book_id").sort_index()

    total_df["datetime"] = total_df["date"] + " " + total_df["time"]
    total_df["datetime"] = total_df["datetime"].apply(lambda x: convert_dt_to_int(datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S")))

    total_df["close"] = total_df["price"]
    total_df["last"] = total_df["price"]

    total_df["limit_up"] = total_df.apply(lambda row: row.pre_close * (1.1 if "ST" not in row["name"] else 1.05), axis=1).round(2)
    total_df["limit_down"] = total_df.apply(lambda row: row.pre_close * (0.9 if "ST" not in row["name"] else 0.95), axis=1).round(2)

    if open_only:
        total_df = total_df[total_df.open > 0]

    return total_df 
Example #16
Source File: utils.py    From Rqalpha-myquant-learning with Apache License 2.0 4 votes vote down vote up
def get_realtime_quotes(order_book_id_list, open_only=False, include_limit=False):
    import tushare as ts

    code_list = [order_book_id_2_tushare_code(code) for code in order_book_id_list]

    max_len = 800
    loop_cnt = int(math.ceil(float(len(code_list)) / max_len))

    total_df = reduce(lambda df1, df2: df1.append(df2),
                      [ts.get_realtime_quotes([code for code in code_list[i::loop_cnt]])
                       for i in range(loop_cnt)])
    total_df["is_index"] = False

    index_symbol = ["sh", "sz", "hs300", "sz50", "zxb", "cyb"]
    index_df = ts.get_realtime_quotes(index_symbol)
    index_df["code"] = index_symbol
    index_df["is_index"] = True
    total_df = total_df.append(index_df)

    columns = set(total_df.columns) - set(["name", "time", "date", "code"])
    # columns = filter(lambda x: "_v" not in x, columns)
    for label in columns:
        total_df[label] = total_df[label].map(lambda x: 0 if str(x).strip() == "" else x)
        total_df[label] = total_df[label].astype(float)

    total_df["chg"] = total_df["price"] / total_df["pre_close"] - 1

    total_df["order_book_id"] = total_df["code"]
    total_df["order_book_id"] = total_df["order_book_id"].apply(tushare_code_2_order_book_id)

    total_df = total_df.set_index("order_book_id").sort_index()
    total_df["order_book_id"] = total_df.index

    total_df["datetime"] = total_df["date"] + " " + total_df["time"]
    # total_df["datetime"] = total_df["datetime"].apply(
    #     lambda x: convert_dt_to_int(datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S")))

    total_df["close"] = total_df["price"]
    total_df["last"] = total_df["price"]

    total_df = total_df.rename(columns={
        "{}{}_p".format(base_name, i): "{}{}".format(base_name, i)
        for i in range(1, 6) for base_name in ["a", "b"]
    })
    total_df = total_df.rename(columns={"pre_close": "prev_close"})

    del total_df["code"]
    del total_df["is_index"]
    del total_df["date"]
    del total_df["time"]

    if include_limit:
        total_df["limit_up"] = total_df.apply(
            lambda row: row.prev_close * (1.1 if "ST" not in row["name"] else 1.05), axis=1).round(2)
        total_df["limit_down"] = total_df.apply(
            lambda row: row.prev_close * (0.9 if "ST" not in row["name"] else 0.95), axis=1).round(2)

    if open_only:
        total_df = total_df[total_df.open > 0]

    return total_df 
Example #17
Source File: utils.py    From rqalpha-mod-stock-realtime with Apache License 2.0 4 votes vote down vote up
def get_realtime_quotes(order_book_id_list, open_only=False, include_limit=False):
    import tushare as ts

    code_list = [order_book_id_2_tushare_code(code) for code in order_book_id_list]

    max_len = 800
    loop_cnt = int(math.ceil(float(len(code_list)) / max_len))

    total_df = reduce(lambda df1, df2: df1.append(df2),
                      [ts.get_realtime_quotes([code for code in code_list[i::loop_cnt]])
                       for i in range(loop_cnt)])
    total_df["is_index"] = False

    index_symbol = ["sh", "sz", "hs300", "sz50", "zxb", "cyb"]
    index_df = ts.get_realtime_quotes(index_symbol)
    index_df["code"] = index_symbol
    index_df["is_index"] = True
    total_df = total_df.append(index_df)

    columns = set(total_df.columns) - set(["name", "time", "date", "code"])
    # columns = filter(lambda x: "_v" not in x, columns)
    for label in columns:
        total_df[label] = total_df[label].map(lambda x: 0 if str(x).strip() == "" else x)
        total_df[label] = total_df[label].astype(float)

    total_df["chg"] = total_df["price"] / total_df["pre_close"] - 1

    total_df["order_book_id"] = total_df["code"]
    total_df["order_book_id"] = total_df["order_book_id"].apply(tushare_code_2_order_book_id)

    total_df = total_df.set_index("order_book_id").sort_index()
    total_df["order_book_id"] = total_df.index

    total_df["datetime"] = total_df["date"] + " " + total_df["time"]
    # total_df["datetime"] = total_df["datetime"].apply(
    #     lambda x: convert_dt_to_int(datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S")))

    total_df["close"] = total_df["price"]
    total_df["last"] = total_df["price"]

    total_df = total_df.rename(columns={
        "{}{}_p".format(base_name, i): "{}{}".format(base_name, i)
        for i in range(1, 6) for base_name in ["a", "b"]
    })
    total_df = total_df.rename(columns={"pre_close": "prev_close"})

    del total_df["code"]
    del total_df["is_index"]
    del total_df["date"]
    del total_df["time"]

    if include_limit:
        total_df["limit_up"] = total_df.apply(
            lambda row: row.prev_close * (1.1 if "ST" not in row["name"] else 1.05), axis=1).round(2)
        total_df["limit_down"] = total_df.apply(
            lambda row: row.prev_close * (0.9 if "ST" not in row["name"] else 0.95), axis=1).round(2)

    if open_only:
        total_df = total_df[total_df.open > 0]

    return total_df