예제 #1
0
def getStockList(type: str = "default", date: str = ""):
    result = []
    data: DataFrame
    if type == "sz50":
        data = BaoStock.query_sz50_stocks(date).get_data()
    elif type == "hs300":
        data = BaoStock.query_hs300_stocks(date).get_data()
    elif type == "zz500":
        data = BaoStock.query_zz500_stocks(date).get_data()
    elif type == "default":
        path = Path(__file__).parent.absolute()/"list.json"
        file = open(str(path), "r", encoding="utf8")
        return Json.loads(file.read())
    else:
        data = BaoStock.query_stock_basic().get_data()
        keys = data.keys()
        data = [x[1]
                for x in BaoStock.query_stock_basic().get_data().iterrows()]
        if type == "index":
            data = [x for x in data if x["type"] == "2"]
        elif type == "stock":
            data = [x for x in data if x["type"] == "1"]
        for row in data:
            result.append({getStockListMap[key][0]: row[key]
                          for key in keys if key in getStockListMap})
        return result
    for row in data.iterrows():
        result.append({getStockListMap[key][0]: row[1][key]
                      for key in data.keys() if key in getStockListMap})
    return result
예제 #2
0
 def query_basic(code='', code_name=''):
     assert(isinstance(code, str))
     rs = bs.query_stock_basic(code, code_name)
     while Stock.retried_num < Stock.RETRY_MAX_NUM and rs.error_code != '0':
         sleep(Stock.RETRY_DELAY_S)
         rs = bs.query_stock_basic(code, code_name)
         Stock.retried_num += 1
     if '0' == rs.error_code:
         Stock.retried_num = 0
         return Stock.rs_to_list(rs)
def compute_Avg_EarningRate():
    # 登陆系统
    lg = bs.login()

    # 显示登陆返回信息
    print('login respond error_code:' + lg.error_code)
    print('login respond  error_msg:' + lg.error_msg)

    # 获取全部证券基本资料
    rs = bs.query_stock_basic()
    result = pd.DataFrame()
    while (rs.error_code == '0') & rs.next():
        # 获取一条记录,将记录合并在一起
        code = rs.get_row_data()[0]
        df = get_closeprice(code)
        if result.empty:
            result = df
        else:
            result = result.append(df)
    result = result[result['open'] != '']
    result['open'] = result['open'].astype(float)
    result['close'] = result['close'].astype(float)
    result['avgEarningRate'] = (
        result['close'] /
        result['open']).apply(lambda x: math.pow(x, 1 / 3) - 1)
    result = result.sort_values(by=['avgEarningRate'], ascending=False)
    result.to_csv("D:\\Avg_Earning_Rate_data.csv", encoding="gbk", index=False)

    result[:10]['avgEarningRate'].plot(title='Avg Earning Rate', kind='bar')
    plt.show()
    # 登出系统
    bs.logout()
예제 #4
0
def getStockInfo():
    # 登陆系统
    lg = bstk.login()
    # 显示登陆返回信息
    print('login respond  error_msg:' + lg.error_msg)
    # 获取证券基本资料
    data_list = []
    # stock_list = getCode()
    # rs = bstk.query_stock_basic(code="sh.{}".format(stock_code))
    rs = bstk.query_stock_basic()

    # 打印结果集
    while (rs.error_code == '0') & rs.next():
        # 获取一条记录,将记录合并在一起
        data_list.append(rs.get_row_data())
    result = pd.DataFrame(data_list, columns=rs.fields)
    # 登出系统
    bstk.logout()

    df = result
    df.columns = [
        'stock_code', 'stock_name', 'ipo_date', 'out_date', 'stock_type',
        'stock_status'
    ]
    df['out_date'] = result['out_date'].apply(lambda x: np.NaN
                                              if x == '' else x)

    return df
예제 #5
0
def getBasicInfoByName(name):
    # 登陆系统
    lg = bs.login()
    # 显示登陆返回信息
    print('login respond error_code:' + lg.error_code)
    print('login respond  error_msg:' + lg.error_msg)

    # 获取证券基本资料
    rs = bs.query_stock_basic(code_name=name)  # 支持模糊查询
    print('query_stock_basic respond error_code:' + rs.error_code)
    print('query_stock_basic respond  error_msg:' + rs.error_msg)

    obj = {}

    if (rs.error_code != '0'):
        obj['error_code'] = rs.error_code
        obj['error_msg'] = rs.error_msg
        return obj

    #print(type(rs))#<class 'baostock.data.resultset.ResultData'>
    #打印结果集
    data_list = []
    while (rs.error_code == '0' and rs.next()):
        #获取一条记录,将记录合并在一起
        data_list.append(rs.get_row_data())
    obj['error_code'] = '0'
    obj['data_list'] = data_list
    #登出系统
    bs.logout()

    return obj
예제 #6
0
def compute_avg_earning_rate():
    # 登录系统
    lg = bs.login()

    # 显示登录返回信息
    print("login response error_code:{},error_msg:{}".format(
        lg.error_code, lg.error_msg))

    # 获取全部证券基本资料
    rs = bs.query_stock_basic()
    result = pd.DataFrame()
    while (rs.error_code == '0') & rs.next():
        # 获取一条记录,将记录合并
        code = rs.get_row_data()[0]
        df = get_close_price(code)
        if df is None:
            continue

        if df.empty:
            result = df
        else:
            result = result.append(df)
    result = result[result['open'] != '']
    result['open'] = result['open'].astype(float)
    result['close'] = result['close'].astype(float)
    result['avgEarningRate'] = (
        result['close'] /
        result['open']).apply(lambda x: math.pow(x, 1 / 3) - 1)
    result = result.sort_values(by=['avgEarningRate'], ascending=False)
    result.to_csv("Avg_Earning_Rate_data.csv", encoding="utf-8", index=False)

    result[:10]['avgEarningRate'].plot(title='Avg Earning Rate', kind='bar')
    plt.show()
    # 登出系统
    bs.logout()
def getIPO(code):
    re = 0
    try:
        re = bs.query_stock_basic(code)
        re = re.get_row_data()[2]
    except:
        pass
    return re
예제 #8
0
def compute_total_ROE():
    # 登陆系统
    lg = bs.login()
    # 显示登陆返回信息
    print('login respond error_code:' + lg.error_code)
    print('login respond error_msg:' + lg.error_msg)
    # 获取全部证券基本资料
    rs = bs.query_stock_basic()
    # rs = bs.query_stock_basic(code_name="浦发银行") # 支持模糊查询
    print('query_stock_basic respond error_code:' + rs.error_code)
    print('query_stock_basic respond error_msg:' + rs.error_msg)
    result_profit = pd.DataFrame()

    jingduCount = 0
    startt = time.time()
    yearSE = (2015, 2020)
    while (rs.error_code == '0') & rs.next():
        # 获取一条记录,将记录合并在一起
        code = rs.get_row_data()[0]
        jingduCount += 1
        newt = time.time()
        lg = bs.login()
        print('\r',
              "进度:%.2f%% | Code:%s | End@:%s | year:%d~%d" %
              (100 * jingduCount / len(rs.data), code,
               time.asctime(
                   time.localtime(newt + (newt - startt) / jingduCount *
                                  (len(rs.data) - jingduCount))), yearSE[0],
               yearSE[1]),
              end='')

        for year in range(yearSE[0], yearSE[1]):

            for season in range(1, 5):
                df = computeROE(code, year, season)
                if df.empty:
                    continue
                else:
                    if result_profit.empty:
                        result_profit = df
                    else:
                        result_profit = result_profit.append(df)
    # 原始数据存储
    result_profit.to_csv("./data3/dupont_data_ROE_" + str(yearSE) + ".csv",
                         encoding="utf-8",
                         index=False)
    # 筛选有用数据
    # result = result_profit[['code', 'dupontROE']]
    # result = result[result['dupontROE'] != '']
    # result['dupontROE'] = result['dupontROE'].astype(float)
    # series_mean = result.groupby(by=['code'])['dupontROE'].mean()
    # series_std = result.groupby(by=['code'])['dupontROE'].std()
    # df2 = pd.DataFrame({'mean': series_mean.data, 'std':series_std.data},\
    #         columns=['mean', 'std'], index=series_mean.index)
    # df2 = df2.sort_values(['mean'])
    # df2.to_csv("./data3/dupont_data_sorted_by_roe.csv", encoding="gbk",index=True)
    # 登出系统
    bs.logout()
예제 #9
0
    def appendCompanyDetail(self, company):

        rs = bs.query_stock_basic(code_name=company.short_name)
        print('query_stock_industry {} {} :', rs.error_code, rs.error_msg)

        if rs.error_code == '0':
            company.ipo_date = rs.get_row_data()[2]

        return company
def getStockBasic(code):
    # 获取证券基本资料
    rs = bs.query_stock_basic(code=code)
    # 打印结果集
    data_list = []
    while (rs.error_code == '0') & rs.next():
        # 获取一条记录,将记录合并在一起
        data_list.append(rs.get_row_data())
    return pd.DataFrame(data_list, columns=rs.fields)
예제 #11
0
    def query_stock_basic(self,code = None, code_name = None):
        '''
        code:A股股票代码,sh或sz.+6位数字代码,或者指数代码,如:sh.601398。sh:上海;sz:深圳。可以为空;
        code_name:股票名称,支持模糊查询,可以为空。
        '''
        if code:
            rs = bs.query_stock_basic(code=code)
        else:
            rs = bs.query_stock_basic(code_name=code_name)  # 支持模糊查询
        self.log('query_stock_basic respond  error_msg:', rs)

        # 打印结果集
        data_list = []
        while (rs.error_code == '0') & rs.next():
            # 获取一条记录,将记录合并在一起
            data_list.append(rs.get_row_data())
        result = pd.DataFrame(data_list, columns=rs.fields)
        return result
예제 #12
0
def download_data(date):
    data_df = download_data_by_day(date)
    data_df = filter_data(data_df)
    #    print(data_df)
    #    rs_df = pd.DataFrame()
    #    begin_date = datetime.datetime.strptime(date, "%Y-%m-%d").date()
    #    end_date = begin_date + datetime.timedelta(days=1)
    #    if end_date <= datetime.date.today():
    #        for row_index, row in data_df.iterrows():
    #            k_rs = get_history_k_data(row.code, end_date.strftime("%Y-%m-%d"))
    #            #print(k_rs.get_data().loc[0].low,row.low,row.code)
    #            #print(float(k_rs.get_data().loc[0].low)-row.low,row.code)
    #            rs_df = rs_df.append(row,ignore_index=False)
    #            rs_df = rs_df.append(k_rs.get_data())
    #

    print("当日过滤数据", data_df)
    write_to_excel(
        data_df, 'd:\\output-' + datetime.datetime.now().strftime('%Y-%m') +
        '-filter.xlsx', date)
    # 过滤上个交易日相关指标
    begin_date = datetime.datetime.strptime(date, "%Y-%m-%d").date()
    basic_df = pd.DataFrame()
    for row_index, row in data_df.iterrows():
        if begin_date.isoweekday() == 1:
            day_step = -3
        else:
            day_step = -1

        # 上一个工作日
        last_work_day = begin_date + datetime.timedelta(days=day_step)
        last_rs = get_history_k_data(row.code,
                                     last_work_day.strftime("%Y-%m-%d"))

        last_st = last_rs.get_data().loc[0]
        # 当日最低价小于等于上日最低价,当日收盘价高于上日最高价,上一日涨幅或跌幅<10%
        if row.low <= float(last_st.low) and row.close > float(
                last_st.high) and abs(
                    float(last_st.close) - float(last_st.open)) < 10:
            # 名称
            basic_rs = bs.query_stock_basic(code=row.code)
            basic_df = basic_df.append(basic_rs.get_data())

    data_df = pd.merge(data_df, basic_df, how='inner', on=['code'])
    # 改变数据列的顺序
    data_df = data_df[[
        'date', 'code', 'code_name', 'pctChg', 'amplitude', 'turn', 'close',
        'open', 'high', 'low', 'amount', 'peTTM'
    ]]
    # 输出
    print(data_df)
    write_to_excel(
        data_df,
        'd:\\output-' + datetime.datetime.now().strftime('%Y-%m') + '.xlsx',
        date)
예제 #13
0
def baseinfo(code):
    filename = "data/baseinfo_{}.csv".format(code)
    if os.path.exists(filename):
        result = pd.read_csv(filename)
    else:
        rs = bs.query_stock_basic(code="sh.601012")
        data_list = []
        while (rs.error_code == '0') & rs.next():
            data_list.append(rs.get_row_data())
        result = pd.DataFrame(data_list, columns=rs.fields)
        result.to_csv(filename, encoding="utf-8", index=False)
    return result
예제 #14
0
def get_single_stock_ipo_date(code):
    #### 登陆系统 ####
    lg = bs.login()
    # 显示登陆返回信息
    print('login respond error_code:' + lg.error_code)
    print('login respond  error_msg:' + lg.error_msg)
    # 获取证券基本资料
    rs = bs.query_stock_basic(code)
    res_df = rs.get_data()
    # 登出系统
    bs.logout()
    # print(res_df['ipoDate'][0])
    return res_df['ipoDate'][0]
예제 #15
0
def queryStockName(stockCode):
    customLogin()
    #查股票名字
    #返回示例数据
    #code	code_name	ipoDate	outDate	type	status
    #sh.600000	浦发银行	1999-11-10		1	1
    rs = bs.query_stock_basic(code=stockCode)
    stockName = None
    if (rs.error_code == '0') & rs.next():
        stockName = rs.get_row_data()[1]
    if stockName == None:
        raise RuntimeError("无此股票代码:", stockCode)
    return stockName
예제 #16
0
def getCode():
    lg = bs.login()
    rs = bs.query_stock_basic()
#   rs = bs.query_all_stock()
    
    print('query_all_stock respond error_code:'+rs.error_code)
    print('query_all_stock respond  error_msg:'+rs.error_msg)

    data_list = []
    while (rs.error_code == '0') & rs.next():
        data_list.append(rs.get_row_data())
    bs.logout()
    return data_list
예제 #17
0
def get_bao_PE(yearSE = '2019-03-24'):
    lg = bs.login()
    # 显示登陆返回信息
    # print('login respond error_code:'+lg.error_code)
    # print('login respond  error_msg:'+lg.error_msg)

    #### 获取沪深A股估值指标(日频)数据 ####
    # peTTM    滚动市盈率
    # psTTM    滚动市销率
    # pcfNcfTTM    滚动市现率
    # pbMRQ    市净率
    rsAll = bs.query_stock_basic ()
    jingduCount = 0
    startt = time.time()

    result_list = []
    while (rsAll.error_code == '0') & rsAll.next():
        # 获取一条记录,将记录合并在一起
        code = rsAll.get_row_data()[0]

        jingduCount += 1
        newt = time.time()
        
        print('\r',
            "进度:%.2f%% | Code:%s | End@:%s | date:%s" % (100*jingduCount/len(rsAll.data), code, 
            time.asctime( time.localtime(newt+(newt - startt)/jingduCount*(len(rsAll.data) - jingduCount))),yearSE),end='')


        rs = bs.query_history_k_data_plus(str(code),
            "date,code,close,peTTM,pbMRQ,psTTM,pcfNcfTTM",
            start_date=yearSE, end_date=yearSE, 
            frequency="d", adjustflag="1")
        #### 打印结果集 ####

        while (rs.error_code == '0') & rs.next():
            # 获取一条记录,将记录合并在一起
            lrs = rs.get_row_data()
            if(len(lrs) > 3 and lrs[3] != '' 
                        and float(lrs[3]) > 0.000001):
                result_list.append(lrs)
                break
    if len(result_list) == 0:
        print('no PE data on ', yearSE)
        return 0
    result = pd.DataFrame(result_list, columns=rs.fields)

    #### 结果集输出到csv文件 ####
    result.to_csv("./data3/history_PE_"+yearSE+".csv", encoding="utf-8", index=False)
    #### 登出系统 ####
    bs.logout()
    return 1
예제 #18
0
def bs_save_stock_basic():
    '''
    获取股票和指数
    :return:
    '''
    bs.login()
    rs = bs.query_stock_basic()
    data_list = []
    while (rs.error_code == '0') & rs.next():
        data_list.append(rs.get_row_data())
    result = pd.DataFrame(data_list, columns=rs.fields)
    engine = create_engine('mysql+pymysql://root:root@localhost:3306/stock_quant?charset=utf8')
    result.to_sql('bs_stock_basic', engine, index=True)
    bs.logout()
예제 #19
0
def get_stock_basic(type, save=False):
    '''
    获取所有股票基本信息,并且返回type类型的数据
    :param type: 选择希望返回的数据
    :param save: 选择是否保存股票基本信息
    :return: 返回type类型的数据
    '''
    stock_basic = bs.query_stock_basic()
    res = pd.DataFrame(stock_basic.data, columns=stock_basic.fields)
    if save:
        res.to_csv("D:\quant\BaoStock\data\stock_basic.csv", index=False)
    if type == 'code-ipoDate':
        return res['code'].values, res['ipoDate'].values
    else:
        return res
예제 #20
0
def get_stock_basic():
    bs.login()
    rs = bs.query_stock_basic()
    data_list = []
    while (rs.error_code == '0') & rs.next():
        data_list.append(rs.get_row_data())
    data = pd.DataFrame(data_list, columns=rs.fields)
    data.rename(columns={
        'code_name': 'name',
        'ipoDate': 'ipo_date',
        'outDate': 'out_date'
    },
                inplace=True)
    bs.logout()
    return data
예제 #21
0
def get_stock_basic():
    """
    获取最新BS-A股股票列表
    """
    #清空原有数据
    BS_Stock_Basic.del_all_date()

    # 登陆系统
    lg = bs.login()
    # 显示登陆返回信息
    print('login respond error_code:' + lg.error_code)
    print('login respond  error_msg:' + lg.error_msg)

    # 获取证券基本资料
    rs = bs.query_stock_basic()
    # rs = bs.query_stock_basic(code_name="浦发银行")  # 支持模糊查询
    print('query_stock_basic respond error_code:' + rs.error_code)
    print('query_stock_basic respond  error_msg:' + rs.error_msg)

    # 打印结果集
    data_list = []
    while (rs.error_code == '0') & rs.next():
        # 获取一条记录,将记录合并在一起
        data_list.append(rs.get_row_data())
    result = pd.DataFrame(data_list, columns=rs.fields)
    result['updated_on'] = datetime.now()

    result['status'] = [
        None if x == "" else bool(get_int_from_str(x))
        for x in result["status"]
    ]
    result['ipoDate'] = [
        convert_to_date(x, '%Y-%m-%d') for x in result.ipoDate
    ]
    result['outDate'] = [
        convert_to_date(x, '%Y-%m-%d') for x in result.outDate
    ]
    result['ts_code'] = [convert_to_tscode(x) for x in result.code]

    # 输出结果集
    result.to_sql('odl_bs_stock_basic',
                  engine,
                  schema=CQ_Config.DB_SCHEMA,
                  if_exists='append',
                  index=False)

    # 登出系统
    bs.logout()
예제 #22
0
def get_stock_basic(_code):
    '''
	code: 证券代码
	code_name: 证券名称
	ipoDate: 上市日期
	outDate: 退市日期
	type: 证券类型(1,股票;2,指数;3,其他)
	status: 上市状态(1,上市;0,退市)
	'''
    rs = BS.query_stock_basic(code=_code)
    data_list = []
    while (rs.error_code == '0') & rs.next():
        data_list.append(rs.get_row_data())
    result = PD.DataFrame(data_list, columns=rs.fields)
    print(result)
    return result
예제 #23
0
    def create(self, code):
        rsbasic = bs.query_stock_basic(code)

        if len(rsbasic.data) > 0:
            data_basic_list = []
            while (rsbasic.error_code == '0') & rsbasic.next():
                data_basic_list.append(rsbasic.get_row_data())
            result_basic = pd.DataFrame(data_basic_list,
                                        columns=rsbasic.fields)
            # print(result_basic.code)
            # print(result_basic.to_dict()['code_name'][0])

            fields = "date,code,open,high,low,close"
            rs = bs.query_history_k_data_plus(code,
                                              fields,
                                              start_date=self.start_date,
                                              end_date=self.end_date,
                                              frequency="d",
                                              adjustflag="2")
            # frequency="d"取日k线,adjustflag="3"默认不复权,
            # 1:后复权;2:前复权

            data_list = []
            while (rs.error_code == '0') & rs.next():
                # 获取一条记录,将记录合并在一起
                data_list.append(rs.get_row_data())
            result = pd.DataFrame(data_list, columns=rs.fields)
            result.index = pd.to_datetime(result.date)

            y = list(result.loc[:, ['open', 'close', 'low', 'high']].values)

            x = list(result.index.strftime('%Y%m%d'))

            kline = Kline(result_basic.to_dict()['code_name'][0],
                          title_text_size=15)
            kline.add("",
                      x,
                      y,
                      is_datazoom_show=False,
                      mark_line=["average"],
                      mark_point=["max", "min"],
                      mark_point_symbolsize=60,
                      mark_line_valuedim=['highest', 'lowest'])
            kline.render("baostock/%s.gif" % (code))
            kline
        else:
            print("empty ----> " + rsbasic.code)
예제 #24
0
    def get_basic_code_info(self, kechuang=False):

        rs = bs.query_stock_basic()
        print('query_stock_basic respond  error_msg:' + rs.error_msg)
        # 打印结果集
        data_list = []
        while (rs.error_code == '0') & rs.next():
            # 获取一条记录,将记录合并在一起
            data_list.append(rs.get_row_data())
        result = pd.DataFrame(data_list, columns=rs.fields)
        # 结果集输出到csv文件
        # result.to_csv("D:/stock_basic.csv", encoding="gbk", index=False)
        result['only_code'] = result['code'].str.lower().str.split('.').str[1]
        result_stock = result[result['type'] == '1']
        if kechuang:
            pass
        else:
            result_stock = result_stock[(result_stock['only_code'].str[:2] !=
                                         '30')]
        # result_stock[('st' not in  result_stock['code_name'].str.lower() )]
        # result_stock['code_name']=result_stock['code_name'].str.lower()
        # result_stock['st股'] = result_stock['code_name'].apply(lambda x: True if 'st' in str(x) else False )
        # print(result_stock[result_stock['st股'] == False])
        # result[((result['code'].str[:2] == 'sh')&(result['only_code'].str[:2] == '60'))|((result['code'].str[:2] == 'sz')&(result['only_code'].str[:2] == '00'))])
        result_stock.reset_index(drop=True, inplace=True)

        # 获取行业分类数据
        rs = bs.query_stock_industry()
        print('query_stock_industry error_code:' + rs.error_code)
        print('query_stock_industry respond  error_msg:' + rs.error_msg)

        # 打印结果集
        industry_list = []
        while (rs.error_code == '0') & rs.next():
            # 获取一条记录,将记录合并在一起
            industry_list.append(rs.get_row_data())
        result2 = pd.DataFrame(industry_list, columns=rs.fields)

        result = pd.merge(
            result_stock,
            result2[['code', 'industry', 'industryClassification']],
            how='left',
            on=['code'])
        # print(result.keys())
        # exit()

        return result
예제 #25
0
def download_k_line_csv_data(code):
    lg = bs.login()
    # 显示登陆返回信息
    # print('login respond error_code:' + lg.error_code)
    # print('login respond  error_msg:' + lg.error_msg)

    #### 获取沪深A股历史K线数据 ####
    # 详细指标参数,参见“历史行情指标参数”章节;“分钟线”参数与“日线”参数不同。“分钟线”不包含指数。
    # 分钟线指标:date,time,code,open,high,low,close,volume,amount,adjustflag
    # 周月线指标:date,code,open,high,low,close,volume,amount,adjustflag,turn,pctChg
    yesterday = date.today() + timedelta(days=-1)
    d = yesterday.strftime("%Y-%m-%d")
    rs = bs.query_history_k_data_plus(
        code,
        "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,isST",
        start_date='2017-07-01',
        end_date=d,
        frequency="d",
        adjustflag="3")
    # print('query_history_k_data_plus respond error_code:' + rs.error_code)
    # print('query_history_k_data_plus respond  error_msg:' + rs.error_msg)

    #### 打印结果集 ####
    data_list = []
    while (rs.error_code == '0') & rs.next():
        # 获取一条记录,将记录合并在一起
        data_list.append(rs.get_row_data())
    result = pd.DataFrame(data_list, columns=rs.fields)

    rsb = bs.query_stock_basic(code="")
    # data_list1 = []
    # while (rsb.error_code == '0') & rsb.next():
    #     # 获取一条记录,将记录合并在一起
    #     data_list1.append(rsb.get_row_data())
    #
    # filename=""
    # for data in data_list1:
    #     if data[0] == code:
    #         print(data)
    filename = "D:\\stock\\astock\\" + code + '-' + time.strftime(
        "%Y-%m-%d-%H%M%S", time.localtime()) + '.csv'

    #### 结果集输出到csv文件 ####
    result.to_csv(filename, index=False)
    print('Stock coed:' + code + ' data download done ,file path :' + filename)
    #### 登出系统 ####
    bs.logout()
예제 #26
0
def downloadAllStocks(tradeDate):
    customLogin()
#     set_trace()
#     stock_rs = bs.query_all_stock(tradeDate)
    stock_rs = bs.query_stock_basic()
    stock_df = stock_rs.get_data()
    dataList = []
    for index,stock in stock_df.iterrows():
        stockObj = Stock(stock["code"], stock["code_name"])
        stockObj.stockType = stock["type"]
        dataList.append(stockObj.__dict__)
    mydb = dbutil.connectDB()
    mydb["Stock"].delete_many({})
    mydb["Stock"].insert_many(dataList)
    customLogout()
    
    return True
예제 #27
0
 def getAllStock(self):
     BsUtils.login()
     rs = bs.query_all_stock(self.date)
     rs_detail = bs.query_stock_basic()
     print('query_all_stock respond error_code:' + rs.error_code)
     print('query_all_stock respond  error_msg:' + rs.error_msg)
     print('query_stock_basic respond error_code:' + rs_detail.error_code)
     print('query_stock_basic respond  error_msg:' + rs_detail.error_msg)
     data, data_detail = [], []
     while (rs.error_code == '0') & rs.next():
         data.append(rs.get_row_data())
     while (rs_detail.error_code == '0') & rs_detail.next():
         data_detail.append(rs_detail.get_row_data())
     bs.logout()
     self.saveToDB('all_stock_code', rs.fields, data, self.date)
     self.saveToDB('all_stock_basic', rs_detail.fields, data_detail,
                   self.date)
     return data, rs.fields
예제 #28
0
파일: api.py 프로젝트: qiudongwei/stock-api
 def dispatch_request(self):
     post_data = request.get_json()
     code = post_data.get('code', '')
     code_name = post_data.get('code_name', '')
     attr_fields = post_data.get('attr_fields', None)
     rs = bs.query_stock_basic(code=code, code_name=code_name)
     data_list = []
     while (rs.error_code == '0') & rs.next():
         data_list.append(rs.get_row_data())
     fields = ['code', 'code_name', 'ipoDate', 'outDate', 'type', 'status']
     data = jsonWrapper(data_list, fields)
     result = {
       'code': 200 if rs.error_code == '0' else rs.error_code,
       'data': list(map(lambda x: { attr: x.get(attr, '') for attr in attr_fields }, data)) if attr_fields else data,
       'msg': rs.error_msg
     }
     self.logout()
     return jsonify(result)
예제 #29
0
def update_ipodate():
    data_list = []
    lg = bs.login()
    shobj = AStocksHeader.objects.all()
    for obj in shobj:
        rs = bs.query_stock_basic(code_name=obj.stock_name)
        while (rs.error_code == '0') & rs.next():
            data_list.append(rs.get_row_data())
    for index, item in enumerate(data_list):
        sb = AStocksHeader.objects.filter(stock_name=item[1]).first()
        if sb:
            print(index, item[1])
            sb.ipodate = item[2]
            if item[3] != '':
                sb.outdate = item[3]
                sb.isdelisted = True
            sb.save()
    print('update finished...')
    bs.logout()
예제 #30
0
 def update_stock_all(self):
     bs.login()
     rs = bs.query_stock_basic()
     data_list = []
     while (rs.error_code == '0') & rs.next():
         # 获取一条记录,将记录合并在一起
         data_list.append(rs.get_row_data())
     data = pd.DataFrame(data_list, columns=rs.fields)
     # 创建会话
     session = sqlUtils.get_sqlalchemy_session()
     d_len = data.shape[0]
     for i in range(d_len):
         row = data.iloc[i]
         stock_basic = StockBasic.tranfer(row)
         session.merge(stock_basic)
         session.commit()
     session.close()
     bs.logout()
     print("股票列表已更新")