Beispiel #1
0
    def __init__(self):  #初始化
        # easyquotation.update_stock_codes()
        self.quotationQq = easyquotation.use('qq')
        self.quotationSina = easyquotation.use('sina')
        ts.set_token('38bb3cd1b6af2d75a7d7e506db8fd60354168642b400fa2104af81c5'
                     )  #设置tushare.token
        self.pro = ts.pro_api()
        #沪深A股股票代码转list供easyquotation调用
        self.tscodeData = self.pro.query('stock_basic',
                                         exchange='',
                                         list_status='L',
                                         fields='symbol')
        self.stockList = self.tscodeData['symbol'].tolist()
        #连接数据库
        self.connectQfq = pymysql.connect(host="192.168.151.216",
                                          port=3306,
                                          user="******",
                                          password="******",
                                          database="kday_qfq",
                                          charset='utf8')
        self.connectStat = pymysql.connect(host="192.168.151.216",
                                           port=3306,
                                           user="******",
                                           password="******",
                                           database="statistics",
                                           charset='utf8')

        #读取config
        conf = configparser.ConfigParser()
        conf.read('config.ini')
    def search(self):
        self.tabWidget.setCurrentIndex(2)

        code = self.StockCodeEdit.text()
        if code.isdigit() and len(code) == 6:
            if self.comboBox.currentText() == '新浪':
                quotation = easyquotation.use('sina')
                stockdata = quotation.stocks(code)
                if stockdata:
                    stockdata = stockdata[code]
                    #print(stockdata)
                    self.sharenameline.setText(stockdata['name'])
                    self.sharenumberline.setText(self.StockCodeEdit.text())
                    self.sharepriceline.setText(str(stockdata['now']))
                    if user != None:
                        if user.stocks.get(code) != None:

                            self.shareholdingline.setText(
                                str(user.stocks[code]))
                        else:

                            self.shareholdingline.setText('0')
                    else:
                        self.shareholdingline.setText('0')

                    # self.increaseline.setText()
                    self.datatimeline.setText(stockdata['time'])

                else:
                    QMessageBox.information(self, "错误", "请输入正确的股票代码")
            elif self.comboBox.currentText() == '腾讯':
                quotation = easyquotation.use('qq')
                stockdata = quotation.stocks(code)
                if stockdata:
                    stockdata = stockdata[code]
                    #print(stockdata)
                    self.sharenameline.setText(stockdata['name'])
                    self.sharenumberline.setText(self.StockCodeEdit.text())
                    self.sharepriceline.setText(str(stockdata['now']))
                    if user != None:
                        if user.stocks.get(code) != None:

                            self.shareholdingline.setText(
                                str(user.stocks[code]))
                        else:

                            self.shareholdingline.setText('0')
                    else:
                        self.shareholdingline.setText('0')

                    self.increaseline.setText(str(stockdata['涨跌(%)']) + '%')
                    self.datatimeline.setText(str(stockdata['datetime']))

                else:
                    QMessageBox.information(self, "错误", "请输入正确的股票代码")

        else:
            QMessageBox.information(self, '错误', "请输入6位数字的股票代码")
    def __init__(self):
        self.session = Request()
        sys_str = platform.system()
        # 新浪 ['sina'] 腾讯 ['tencent', 'qq']
        self.quotation = easyquotation.use('sina')
        self.quotation_timekline = easyquotation.use("timekline")

        # 驱动路径
        if sys_str == "Windows":
            path = Config().CHROME_DRIVER_WIN_PATH
        elif sys_str == "Linux":
            path = Config().CHROME_DRIVER_MAC_PATH
        else:
            path = Config().CHROME_DRIVER_MAC_PATH
Beispiel #4
0
def get_stopped_stocks(given_stocks=[],except_stocks=[],hist_dir='C:/hist/day/data/'):
    import easyquotation
    quotation =easyquotation.use('qq')
    stop_stocks = []
    if given_stocks:
        this_quotation = quotation.stocks(given_stocks)
    else:
        this_quotation = quotation.all
    all_stocks = list(this_quotation.keys())
    #print('all_stocks=',('150251'  in all_stocks))
    #print('hist_dir=',hist_dir)
    exist_codes = pds.get_all_code(hist_dir)
    #print('exist_codes=',('150251'  in exist_codes))
    #print('all_stocks=',all_stocks)
    all_codes = list(set(all_stocks) & (set(exist_codes)))
    #print('all_codes=',all_codes)
    for stock_code in all_codes:
        if this_quotation[stock_code]:
            #print(this_quotation[stock_code])
            if this_quotation[stock_code]['ask1']==0 and this_quotation[stock_code]['volume']==0:
                stop_stocks.append(stock_code)
            else:
                pass
    
    if except_stocks:
        all_codes = list(set(all_codes).difference(set(except_stocks)))
    #print('all_codes=',('150251'  in all_codes))
    #print('stop_stocks=', stop_stocks)
    #print(len(stop_stocks))
    #print('all_stocks=',all_stocks)
    #print(len(all_stocks))
    return stop_stocks,all_codes
Beispiel #5
0
def main_do_date_today():
    quotation = easyquotation.use('sina')  # 新浪 ['sina'] 腾讯 ['tencent', 'qq']
    data_vec = quotation.market_snapshot(prefix=True)
    check_time, table_flag, date_flag, table, date, date_vec = False, False, False, None, None, None
    localtime = time.localtime(time.time())
    num = 0
    for id in data_vec:
        stock_vec = data_vec[id]
        if not date_vec:
            date = stock_vec["date"]
            date_vec = date.split("-")
        #检查时间
        if not check_time:
            year, mon, day = int(date_vec[0]), int(date_vec[1]), int(
                date_vec[2])
            if year == localtime.tm_year:
                if mon == localtime.tm_mon:
                    if day != localtime.tm_mday:
                        #logger.debug("[do_date_today] 今天还没有数据 {0} {1} ".format(day,localtime.tm_mday))
                        break
            check_time = True
        if not table:
            table = TABLE + "_" + date_vec[0]
        if not table_flag:
            create_stock_table(table)
            table_flag = True
        if not date_flag:
            date = DATE + date_vec[1] + "_" + date_vec[2]
            add_date_column(table, date)
            date_flag = True
        insert_or_update_id_data(table, date, id, stock_vec["name"], stock_vec)
        num = num + 1

    logger.debug("[do_date_today] {0} {1} 数据已处理完毕".format(date, num))
Beispiel #6
0
    def __init__(self, event_engine, stock_codes, push_interval=1):
        self.event_engine = event_engine
        self.is_active = True

        self.source = easyquotation.use("lf")
        self.stock_codes = stock_codes
        self.push_interval = push_interval
def get_stopped_stocks(given_stocks=[],
                       except_stocks=[],
                       hist_dir='C:/hist/day/data/'):
    import easyquotation
    quotation = easyquotation.use('qq')
    stop_stocks = []
    if given_stocks:
        this_quotation = quotation.stocks(given_stocks)
    else:
        this_quotation = quotation.all
    all_stocks = list(this_quotation.keys())
    #print('all_stocks=',('150251'  in all_stocks))
    #print('hist_dir=',hist_dir)
    exist_codes = pds.get_all_code(hist_dir)
    #print('exist_codes=',('150251'  in exist_codes))
    #print('all_stocks=',all_stocks)
    all_codes = list(set(all_stocks) & (set(exist_codes)))
    #print('all_codes=',all_codes)
    for stock_code in all_codes:
        if this_quotation[stock_code]:
            #print(this_quotation[stock_code])
            if this_quotation[stock_code]['ask1'] == 0 and this_quotation[
                    stock_code]['volume'] == 0:
                stop_stocks.append(stock_code)
            else:
                pass

    if except_stocks:
        all_codes = list(set(all_codes).difference(set(except_stocks)))
    #print('all_codes=',('150251'  in all_codes))
    #print('stop_stocks=', stop_stocks)
    #print(len(stop_stocks))
    #print('all_stocks=',all_stocks)
    #print(len(all_stocks))
    return stop_stocks, all_codes
 def __init__(self, event_engine, stock_codes, push_interval=1):
     self.event_engine = event_engine
     self.is_active = True
     
     self.source = easyquotation.use("lf")
     self.stock_codes = stock_codes
     self.push_interval = push_interval
def getLiutong_from_qq():
    q = easyquotation.use('qq')

    #取上市300天内的股票
    stock_list = getCixinCode()
    stockinfo, stockinfo_zhangting = q.stocks(stock_list)
    data = []

    for key, value in stockinfo.items():
        try:
            infoLiutong = (stockinfo[key]['code'], stockinfo[key]['流通市值'])
            data.append(infoLiutong)

        except Exception as e:
            print(e)

    for key, value in stockinfo_zhangting.items():
        try:
            infoLiutong = (stockinfo_zhangting[key]['code'],
                           stockinfo_zhangting[key]['流通市值'])
            data.append(infoLiutong)

        except Exception as e:
            print(e)
    #sql_truncat = 'truncat table liutong_from_qq'
    sql = 'insert into liutong_from_qq values(?,?)'
    conn = sqlite3API.get_conn('stock.db')
    #sqlite3API.save(conn,sql_truncat,data)
    sqlite3API.truncate(conn, 'liutong_from_qq')

    sqlite3API.save(conn, sql, data)
    print('getLiutong_from_qq OK!')
Beispiel #10
0
 def index_quotation(indexs=['sh','sz','zxb','cyb','sz300','sh50'],force_update=False):
     #http://qt.gtimg.cn/q=sh000001
     #http://qt.gtimg.cn/q=sh000016
     #http://qt.gtimg.cn/q=sz399001
     #http://qt.gtimg.cn/q=sz399005
     #http://qt.gtimg.cn/q=sz399006
     #http://qt.gtimg.cn/q=sz399006
     index_symbol_maps = {'sh':'000001','sz':'399001','zxb':'399005','cyb':'399006',
                          'sh50':'000016','sz300':'399007','zx300':'399008'}#'hs300':'000300'}
     data = {}
     import easyquotation
     quotation = easyquotation.use('qq')
     for index in indexs:
         symbol = index_symbol_maps[index]
         url ='http://qt.gtimg.cn/q=sz%s' % symbol
         if type=='stock':
             if symbol>='600000':
                 url = url.replace('sz', 'sh')
         elif type == 'index':
             if symbol<'000020':
                 url = url.replace('sz', 'sh')
         else:
             pass
         #index_data = get_qq_quotation(symbol)
         index_data = get_url_content(url, decode_type='gbk')
         print(index_data)
         q_data = quotation.format_response_data(index_data)
         print( q_data)
Beispiel #11
0
def get_global_block_by_msg(msg):
    result = ''
    quotation = easyquotation.use('sina')
    blocks_dict = quotation.market_snapshot(prefix=True)
    global_block = [
        'sh000001', 'sz399001', 'sh000300', 'sz399005', 'sz399006', 'sh000003'
    ]
 def test_stock_code_with_prefix(self):
     cases = ['sina', 'qq']
     for src in cases:
         q = easyquotation.use(src)
         data = q.all_market
         for k in data.keys():
             self.assertRegex(k, r'(sh|sz)\d{6}')
Beispiel #13
0
 def test_all(self):
     cases = ["sina", "qq"]
     for src in cases:
         q = easyquotation.use(src)
         data = q.market_snapshot()
         for k in data.keys():
             self.assertRegex(k, r"\d{6}")
 def test_all(self):
     cases = ["sina", "qq"]
     for src in cases:
         q = easyquotation.use(src)
         data = q.all
         for k in data.keys():
             self.assertRegex(k, r"\d{6}")
Beispiel #15
0
def FetchRunTimeDataByEASYQUOTATION(stockCount):
    quotation = easyquotation.use(runtimeSrc)
    data = quotation.market_snapshot(prefix=False)
    obj = {
        "code": [],
        "trade": [],
        "volume": [],
        "amount": [],
        "high": [],
        "low": [],
        "open": []
    }
    for attribute, value in data.items():
        obj["code"].append(attribute)
        obj["trade"].append(str(value["now"]))
        obj["volume"].append(str(value["volume"]))
        obj["amount"].append(str(value["成交额(万)"]))
        obj["high"].append(str(value["high"]))
        obj["low"].append(str(value["low"]))
        obj["open"].append(str(value["open"]))

    df = pd.DataFrame(obj)
    df = df[df['volume'] != '']
    df = df[df['trade'] != '']
    df = df[df['high'] != '']
    df = df[df['low'] != '']
    df = df[df['open'] != '']
    df = Utils.NormlizePrice(df, ['trade', 'high', 'low', 'open'])
    df['amount'] = (df['amount'].astype(float) / 10000.0)
    df['volume'] = (df['volume'].astype(float) / 100.0)
    return df
Beispiel #16
0
 def test_stock_code_with_prefix(self):
     cases = ["sina", "qq"]
     for src in cases:
         q = easyquotation.use(src)
         data = q.market_snapshot(prefix=True)
         for k in data.keys():
             self.assertRegex(k, r"(sh|sz)\d{6}")
Beispiel #17
0
def sub_1min_from_tencent_lru():
    """
    我是阿财,我专门挖坑,所以这个函数我未调试完成
    从腾讯获得当天交易日分钟K线数据
    """
    blockname = [
        'MSCI中国', 'MSCI成份', 'MSCI概念', '三网融合', '上证180', '上证380', '沪深300',
        '上证380', '深证300', '上证50', '上证电信', '电信等权', '上证100', '上证150', '沪深300',
        '中证100', '中证500', '全指消费', '中小板指', '创业板指', '综企指数', '1000可选', '国证食品',
        '深证可选', '深证消费', '深成消费', '中证酒', '中证白酒', '行业龙头', '白酒', '证券', '消费100',
        '消费电子', '消费金融', '富时A50', '银行', '中小银行', '证券', '军工', '白酒', '啤酒', '医疗器械',
        '医疗器械服务', '医疗改革', '医药商业', '医药电商', '中药', '消费100', '消费电子', '消费金融', '黄金',
        '黄金概念', '4G5G', '5G概念', '生态农业', '生物医药', '生物疫苗', '机场航运', '数字货币', '文化传媒'
    ]
    all_stock_blocks = QA.QA_fetch_stock_block_adv()
    for blockname in blocks:
        if (blockname in all_stock_blocks.block_name):
            codelist_300 = all_stock_blocks.get_block(blockname).code
            print(u'QA预定义板块“{}”成分数据'.format(blockname))
            print(codelist_300)
        else:
            print(u'QA默认无板块“{}”成分数据'.format(blockname))

    quotation = easyquotation.use("timekline")
    data = quotation.real([codelist], prefix=False)
    while (True):
        l1_tick = quotation.market_snapshot(prefix=False)
        print(l1_tick)

    return True
Beispiel #18
0
def test_hkquote():
    import easyquotation

    quotation = easyquotation.use("hkquote")
    # data = quotation.get_stock_data(stock_list=['00001'])
    data = quotation.get_stock_data(stock_list=["00001", "00700"])
    print(data)
Beispiel #19
0
    def get_push_stocks(self):
        quotation = easyquotation.use('qq')
        holding_stocks = self.stocks
        if not holding_stocks:
            holding_stocks = self.user.position['证券代码'].values.tolist()
        print('holding_stocks=', holding_stocks)
        init_push_stocks = list(
            set(holding_stocks) | set(self.additional_stocks))
        init_push_stocks = list(
            set(init_push_stocks).difference(set(self.except_stocks)))
        if init_push_stocks:
            this_quotation = quotation.stocks(init_push_stocks)
            if 'sh000001' in holding_stocks:
                this_quotation['sh000001'] = this_quotation.pop('000001')
        else:
            this_quotation = quotation.all
        stop_stocks = []

        print(list(this_quotation.keys()))
        for stock_code in list(this_quotation.keys()):
            if this_quotation[stock_code]:
                #print(this_quotation[stock_code])
                print(this_quotation[stock_code]['bid1_volume'],
                      this_quotation[stock_code]['ask1_volume'])
                if this_quotation[stock_code][
                        'bid1_volume'] > 0 or this_quotation[stock_code][
                            'ask1_volume'] > 0:
                    pass
                else:
                    print(stock_code)
                    stop_stocks.append(stock_code)
        push_stocks = list(set(init_push_stocks).difference(set(stop_stocks)))
        return push_stocks
Beispiel #20
0
def main():

	#stock account
	trader = easytrader.use('ht', debug=False)
	trader.config['entrust']['cssweb_type'] = 'GET_TODAY_ENTRUST'
	#quotation
	quota = easyquotation.use('sina')

	print('login huatai system......')
	trader.prepare('ht.json')
	print('login successfully')

	show_balance(trader.balance[0])

	# if cash less than investment, quit and check
	if (trader.balance[0]['enable_balance'] < g_investment):
		print('**WARNING: total cash is less than the investment you want to use, please check!')
		return

	print('calculate the allocation for each stock...')
	stockbook = prepare(quota, g_stocks)

	print(stockbook)

	# process the orders
	process(trader, quota, stockbook)
Beispiel #21
0
def down_market_snapshot(save=True):
    """
    每半小时获取下市场快照
    :return: 市场快照
    """

    if QA_util_if_tradetime():
        date = datetime.datetime.now()
        dateStr = date.strftime('%Y-%m-%d_%H-%M')
        quotation = easyquotation.use('sina')
        snapshot = quotation.market_snapshot(prefix=True)
        # market_snapshot = MarketSnapshot(date=date, context=snapshot)
        # market_snapshot.save()
        df_snapshot = pd.DataFrame.from_dict(snapshot)
        df_snapshot = df_snapshot.T
        df_snapshot.index.name = 'code'
        if save:
            df_snapshot.to_csv(ls.LocalSetting.data_path + "mark_snapshot/" +
                               dateStr + ".csv",
                               compression='gzip')
        return df_snapshot
    else:
        return pd.read_csv(
            '/Users/momantang/work/cobrass/data/mark_snapshot/2018-11-09_15-05.csv',
            compression='gzip')
Beispiel #22
0
 def get_push_stocks(self):
     quotation = easyquotation.use('qq')
     holding_stocks = self.stocks
     if not holding_stocks:
         holding_stocks = self.user.position['证券代码'].values.tolist()
     print('holding_stocks=',holding_stocks)
     init_push_stocks = list(set( holding_stocks) | set(self.additional_stocks))
     init_push_stocks = list(set(init_push_stocks).difference(set(self.except_stocks)))
     if init_push_stocks:
         this_quotation = quotation.stocks(init_push_stocks)
         if 'sh000001' in holding_stocks:
             this_quotation['sh000001'] = this_quotation.pop('000001')
     else:
         this_quotation = quotation.all
     stop_stocks = []
     
     print(list(this_quotation.keys()))
     for stock_code in list(this_quotation.keys()):
         if this_quotation[stock_code]:
             #print(this_quotation[stock_code])
             print(this_quotation[stock_code]['bid1_volume'], this_quotation[stock_code]['ask1_volume'])
             if this_quotation[stock_code]['bid1_volume']>0 or this_quotation[stock_code]['ask1_volume']>0:
                 pass
             else:
                 print(stock_code)
                 stop_stocks.append(stock_code)
     push_stocks = list(set(init_push_stocks).difference(set(stop_stocks)))
     return push_stocks
Beispiel #23
0
def test_daykline():
    import easyquotation

    quotation = easyquotation.use("daykline")
    data = quotation.get_stock_data(stock_list=["00001"])
    # data = quotation.get_stock_data(stock_list=['hk00700'])
    print(data)
 def test_all(self):
     cases = ['sina', 'qq']
     for src in cases:
         q = easyquotation.use(src)
         data = q.all
         for k in data.keys():
             self.assertRegex(k, r'\d{6}')
Beispiel #25
0
def main():

    #stock account
    trader = easytrader.use('ht', debug=False)
    trader.config['entrust']['cssweb_type'] = 'GET_TODAY_ENTRUST'
    #quotation
    quota = easyquotation.use('sina')

    print('login huatai system......')
    trader.prepare('ht.json')
    print('login successfully')

    show_balance(trader.balance[0])

    # if cash less than investment, quit and check
    if (trader.balance[0]['enable_balance'] < g_investment):
        print(
            '**WARNING: total cash is less than the investment you want to use, please check!'
        )
        return

    print('calculate the allocation for each stock...')
    stockbook = prepare(quota, g_stocks)

    print(stockbook)

    # process the orders
    process(trader, quota, stockbook)
Beispiel #26
0
def 实时行情():
    import easyquotation

    quotation = easyquotation.use(
        'tencent')  # 新浪 ['sina'] 腾讯 ['tencent', 'qq']
    tmp_dict = quotation.market_snapshot(
        prefix=True)  # prefix 参数指定返回的行情字典中的股票代码 key 是否带 sz/sh 前缀
    print(tmp_dict['sz000001'])  #查看实时股价
Beispiel #27
0
def MysqlData():
    #直接调用easyquotation这个函数
    quotation = easyquotation.use('sina')
    res = quotation.market_snapshot(prefix=True)
    secrities_data = {}
    for item, value in res.items():
        secrities_data[item] = value['name']
    return secrities_data
Beispiel #28
0
def gethq(pool):
    quotation = easyquotation.use('qq')
    hq=[[code,val['name'],val['now'],val['涨跌']] for code, val in quotation.stocks(pool).items()]
    hq.append(['CASH','现金',1,0])
    hq = pd.DataFrame(hq, columns = ['code','name','pricenow','change']).set_index('code')    
    hq['preclose'] = hq['pricenow'] - hq['change']
    hq['pctchange%'] = round(hq['change'] / hq['preclose'] *100, 2)
    return hq
Beispiel #29
0
def get_close_price():
    quotation = easyquotation.use('lf')  # ['leverfun', 'lf']
    qq = quotation.stocks(['510050', '159915', '150023'])
    close_510050 = qq.get('510050').get('close')
    close_159915 = qq.get('159915').get('close')
    close_150023 = qq.get('150023').get('close')
    result_list = [close_510050, close_159915, close_150023]
    return result_list
Beispiel #30
0
 def test_all(self):
     warnings.simplefilter("ignore", ResourceWarning)
     cases = ["sina", "qq"]
     for src in cases:
         q = easyquotation.use(src)
         data = q.market_snapshot()
         for k in data.keys():
             self.assertRegex(k, r"\d{6}")
Beispiel #31
0
def stockmline_ws(request):  #websocket 传送实时行情数据
    #    ts.set_token('38bb3cd1b6af2d75a7d7e506db8fd60354168642b400fa2104af81c5') #设置tushare.token
    #    pro = ts.pro_api()
    #    #沪深A股股票代码转list供easyquotation调用
    #    tscodeData = pro.query('stock_basic', exchange='', list_status='L', fields='symbol')
    #    stockList  = tscodeData['symbol'].tolist()
    quotation = easyquotation.use("timekline")  #声明quotation
    quotationQq = easyquotation.use('qq')
    tscode = request.websocket.wait().decode()  #分时个股代码
    if request.is_websocket():
        while True:
            try:
                tradeTime = {'tradeTime': dt.now().strftime('%H:%M:%S')}
                marketTime = dt.now().strftime('%H%M%S')
                tradeDate = dt.now().strftime('%Y%m%d')
                time.sleep(2)
                if request.websocket.count_messages() > 0:  #接收分时个股代码
                    tscode = request.websocket.read().decode()
                # print(tscode)
                shtscode = 'sh000001'
                tsdm = tscode + '.js'
                shdm = 'sh000001.js'
                df = quotation.real([tscode, 'sh000001'], prefix=True)
                stockData = df[tsdm]
                stockData["data"] = stockData.pop("time_data")
                stockData['yestclose'] = getyestClose(quotationQq,
                                                      tscode)  #分时图获取昨日收盘价
                zhishuData = df[shdm]
                zhishuData["data"] = zhishuData.pop("time_data")
                zhishuData['yestclose'] = getyestClose(
                    quotationQq, shtscode)  #上证指数分时图获取昨日收盘价
                MarketData = stockMarket(quotationQq, tscode)  #获取个股实时行情数据
                upRatio = watchMarket(tradeDate)  #获取看盘数据

                # print(upRatio)
                data = dict()  #打包所有即时数据,生成字典类型
                data['stockMline'] = stockData  #分时个股分时数据
                data['shzsMline'] = zhishuData  #上证指数分时数据
                data['tradeTime'] = tradeTime  #当前时间
                data['MarketData'] = MarketData  #个股实时行情数据
                data['watchMarket'] = {'upRatio': upRatio}  #看盘数据:上涨个股比例
                # print(data)
                request.websocket.send(json.dumps(data))
            except:
                pass
Beispiel #32
0
def get_tick(order_book_id_list, resource='sina'):   # copy from dalao
    tick_dict = {}
    quotation = easyquotation.use(resource)
    if type(order_book_id_list) == str:
        order_book_id_list = [order_book_id_list]
        
    code_list = [order_book_id_2_code(order_book_id) for order_book_id in order_book_id_list]

    eq_dict = quotation.stocks(code_list)

    for code, data in eq_dict.items():
        tick = {
            'order_book_id': code_2_order_book_id(code),
            'datetime': parse('%s %s' % (data['date'], data['time'])),
            'open': data['open'],
            'last': data['now'],
            'low': data['low'],
            'high': data['high'],
            'prev_close': data['close'],
            'volume': data['volume'],
            'total_turnover': data['turnover'],
            'open_interest': np.nan,
            'prev_settlement': np.nan,
            
            'bid': [
                data['bid1'],
                data['bid2'],
                data['bid3'],
                data['bid4'],
                data['bid5'],
            ],
            'bid_volume': [
                data['bid1_volume'],
                data['bid2_volume'],
                data['bid3_volume'],
                data['bid4_volume'],
                data['bid5_volume'],
            ],
            'ask': [
                data['ask1'],
                data['ask2'],
                data['ask3'],
                data['ask4'],
                data['ask5'],
            ],
            'ask_volume': [
                data['ask1_volume'],
                data['ask2_volume'],
                data['ask3_volume'],
                data['ask4_volume'],
                data['ask5_volume'],
            ],
            'limit_up': np.nan,
            'limit_down': np.nan,
        }
        tick_dict[code_2_order_book_id(code)] = tick
    return tick_dict
Beispiel #33
0
def mlineData(request):  #个股实时走势图从easyquotation实时获取
    tscode = '300654'
    tsdm = 'sz' + tscode + '.js'
    quotation = easyquotation.use("timekline")
    df = quotation.real([tscode], prefix=True)
    data = df[tsdm]
    data["data"] = data.pop("time_data")
    #     data['yestclose']=yestclose
    return JsonResponse(data, safe=False)
Beispiel #34
0
def index(request):
    # stock_index_snapshot = StockIndexSnapShot.objects.last()
    quotation = easyquotation.use('sina')
    indexs = quotation.stocks(['sh000001', 'sz399001', 'sh000300', 'sz399006'],
                              prefix=True)
    df_indexs = pd.DataFrame.from_dict(indexs).T
    dicts = df_indexs.to_dict()
    print(dicts)
    return render(request, 'finance/index.html', {'dicts': dicts})
Beispiel #35
0
    def test_stock_code_with_prefix(self):
        warnings.simplefilter("ignore", ResourceWarning)

        cases = ["sina", "qq"]
        for src in cases:
            q = easyquotation.use(src)
            data = q.market_snapshot(prefix=True)
            for k in data.keys():
                self.assertRegex(k, r"(sh|sz)\d{6}")
Beispiel #36
0
def get_all_stock_info():
    data = {}

    for cond in conditions:
        quote = easyquotation.use(cond)
        data = quote.market_snapshot(prefix=True)
        if data:
            break

    return data
Beispiel #37
0
def tradable():
    base_info = tushare.get_stock_basics()
    user = eq.use('sina')
    data = user.all
    data = pd.DataFrame(data).T
    data = data[data.sell > 0]
    data['change'] = (data.sell - data.close) / data.close * 100
    data = data[data.change < 9.93]
    base_info[u'price'] = data.sell
    base_info = base_info.dropna()
    base_info['market'] = base_info.totals * base_info.bvps * base_info.pb
    return base_info, data
Beispiel #38
0
def get_stop_stocks(given_stocks=[]):
    quotation = easyquotation.use('qq')
    stop_stocks = []
    if given_stocks:
        this_quotation = quotation.stocks(given_stocks)
    else:
        this_quotation = quotation.all
    for stock_code in (this_quotation.keys()):
        if this_quotation[stock_code]['buy']==0 and this_quotation[stock_code]['sell']==0:
            stop_stocks.append(stock_code)
        else:
            pass
    return stop_stocks
Beispiel #39
0
def pre_signal(mode):
    """
    返回竞价时的市场情况,mode 1表示返回市场涨跌副, 0 表示返回市场买压比。
    """
    user = eq.use('sina')
    data = user.all
    data = pd.DataFrame(data).T
    data['change'] = (data.ask1 - data.close) / data.close
    data = data[data.change > -1]
    if mode == 1:
        return data.change.mean() * 100
    else:
        return data.bid2_volume.sum() / data.ask2_volume.sum()
Beispiel #40
0
    def __init__(self):
        self.today = datetime.date.today().strftime('%Y-%m-%d')
        self.engine = get_engine('db_stock', True)

        self.stock_candidates = self.get_candidates()
        # self.stock_candidates = self.get_candidates()
        self.logger = self.llogger('auto_trader_{}'.format(self.today))
        self.logger.info('程序启动')
        input('请运行下单程序,按Enter\n')
        self.user = easytrader.use('ths')
        # self.user.prepare('user.json')
        self.user.connect(PROGRAM_PATH)
        # self.position = self.get_position()
        self.blacklist_bond = self.get_blacklist()
        self.q=easyquotation.use('qq')
Beispiel #41
0
def xiaoshizhi():
    base_info = tushare.get_stock_basics()
    user = eq.use('sina')
    data = user.all
    data = pd.DataFrame(data).T
    data = data[data.sell > 0]
    data['change'] = (data.sell - data.close) / data.close * 100
    data = data[data.change < 9.93]
    base_info[u'price'] = data.sell
    base_info = base_info.dropna()
    base_info['market'] = base_info.totals * base_info.bvps * base_info.pb
    base_info = base_info[base_info.market > 0]
    base_info = base_info[base_info.name.str.contains('ST')*1 == 0]
    base_info = base_info[base_info.name.str.contains('退市')*1 == 0]
    base_info = base_info.sort_values(by=['market'])
    stock = base_info[base_info.market <= 1000000]
    return stock
def get_easyquotation_stock_data(source='sina'):
    try:
        #
        quotation = easyquotation.use(source) # 新浪 ['sina'] 腾讯 ['tencent', 'qq']
        #
        first_stock_array = quotation.all
        first_stock_pd = pd.DataFrame(first_stock_array)
        first_stock_rows = first_stock_pd.T 
        #
        need_stock_rows,ret_left = get_left_stock_data(first_stock_rows,quotation)
        #
        all_stock_rows = first_stock_rows.append(need_stock_rows)
        #
        all_price = all_stock_rows[['now']]
        #
        stock_price_dict = {}
        all_num = 0
        left_num = 0
        for id,row in all_price.iterrows():
            all_num += 1
            code = str(id)
            if len(code) == 6 and (int(code[0]) == 6 or (code[0]) == "0" or int(code[0]) == 3):
                pass
            else:
                #print "code error:", row['code'],row['shortname']
                continue 
  
            # 大于 1000 为指数
            if int(row['now']) > 1000:
                #print (" > 1000 error:", code,row['now'])
                continue    
            # 停牌
            if float(row['now']) < 0.1:
                #print (" < 0.1 error:", code,row['now'])
                #continue            
                pass

            #print row
            left_num += 1
            stock_price_dict[str(id)] = int(row['now'] * 10000.0)
        return all_num,left_num,ret_left,stock_price_dict,all_stock_rows
    except Exception:
        traceback.print_exc()
    return (False,False,False,None,None)
Beispiel #43
0
def main():

	#stock account
	trader = easytrader.use('ht', debug=False)
	trader.config['entrust']['cssweb_type'] = 'GET_TODAY_ENTRUST'
	#quotation
	quota = easyquotation.use('sina')

	print('login huatai system......')
	trader.prepare('ht.json')
	print('login successfully')

	show_balance(trader.balance[0])

	print('collect the stocks needed be sold')
	stockbook = prepare(trader, g_stocks)

	# process the orders
	process(trader, quota, stockbook)
Beispiel #44
0
 def get_push_stocks(self):
     quotation = easyquotation.use('qq')
     #holding_stocks = self.user.position['证券代码'].values.tolist()
     #print('holding_stocks',holding_stocks)
     init_push_stocks = self.stocks#list(set( holding_stocks) | set(self.stocks))
     if init_push_stocks:
         this_quotation = quotation.stocks(init_push_stocks)
     else:
         this_quotation = quotation.all
     stop_stocks = []
     for stock_code in (this_quotation.keys()):
         if this_quotation[stock_code]:
             #print(this_quotation[stock_code])
             if this_quotation[stock_code]['bid1_volume']>0 or this_quotation[stock_code]['ask1_volume']>0:
                 pass
             else:
                 stop_stocks.append(stock_code)
     push_stocks = list(set(init_push_stocks).difference(set(stop_stocks)))
     return push_stocks
Beispiel #45
0
 def get_realtime_k_data(self,symbol):
     #https://github.com/shidenggui/easyquotation
     quotation=easyquotation.use('sina') # 新浪 ['sina'] 腾讯 ['tencent', 'qq']
     #quotation = easyquotation.use('lf') # ['leverfun', 'lf'] #免费十档行情
     index_code=['999999','399001','399002','399003','399005']
     #print(quotation.stocks(symbol))
     k_data=quotation.stocks(symbol)
     is_stop_trade = False
     if k_data:
         k_data=k_data[symbol]
         is_stop_trade = not k_data['volume'] and not k_data['high']
     """
     {'000680': {'bid4_volume': 19000, 'high': 5.76, 'bid2_volume': 119096, 'sell': 5.7, 'bid2': 5.68, 'volume': 202358001.01,
                 'ask4_volume': 143800, 'ask5_volume': 153400, 'ask1': 5.7, 'bid1_volume': 110500, 'bid3_volume': 20817, 
                 'ask3_volume': 337408, 'open': 5.41, 'ask3': 5.72, 'turnover': 36100590, 'ask2': 5.71, 'ask1_volume': 210213,
                 'ask2_volume': 217367, 'bid4': 5.66, 'ask5': 5.74, 'date': '2016-04-22', 'low': 5.37, 'time': '15:05:56', 
                 'bid3': 5.67, 'name': '山推股份', 'now': 5.69, 'ask4': 5.73, 'bid5': 5.65, 'buy': 5.69, 'bid1': 5.69, 
                 'close': 5.44, 'bid5_volume': 31000}
      }
      """
     #print('k_data=',k_data)
     return k_data,is_stop_trade
Beispiel #46
0
 def init(self):
     self.source = easyquotation.use('sina')
Beispiel #47
0
import easyquotation

t = easyquotation.use('sina')
quote = t.all
print(quote)
Beispiel #48
0
import easyquotation
from pdSql_common import get_HO_dapan

easy_q = easyquotation.use("qq")

all_q = easy_q.all
da_pan = []
print(all_q["000651"])
for code in list(all_q.keys()):
    liutong_amount = all_q[code]["流通市值"]
    total_amount = all_q[code]["总市值"]
    if liutong_amount and total_amount:
        if float(total_amount) > 1000 or float(liutong_amount) > 500:
            da_pan.append(code)
print("da_pan=", da_pan)
print(len(da_pan))
ho_codes = get_HO_dapan(codes=da_pan, ho_rate=0.0026, stock_sql=None)
print(ho_codes)
Beispiel #49
0
 def init(self):
     self.source = easyquotation.use('jsl')
     self.source.login('audoe', 'wh13chen')
Beispiel #50
0
def test_timekline():
    import easyquotation

    quotation = easyquotation.use("timekline")
    data = quotation.market_snapshot(prefix=True)
    print(data)
 def setUp(self):
     self._obj = easyquotation.use("hkquote")
 def setUp(self):
     self._obj = easyquotation.use("daykline")
Beispiel #53
0
def get_prices():
    quotation = easyquotation.use('qq')
    stocks_info = quotation.all
    return stocks_info
Beispiel #54
0
 def init(self):
     # 进行相关的初始化操作
     self.source = easyquotation.use(self.s)
Beispiel #55
0
 def __init__(self,username,passwd,exe_path):
     self.username_ = username;
     self.password_ = passwd;
     self.exePath_ = exe_path;
     self.quotation_ = easyquotation.use('sina');