Exemple #1
0
def query_history_k_data(start_date, end_date):
    """
    获取历史A股K线数据:query_history_k_data()
    方法说明:获取A股历史交易数据(包括均线数据),
    可以通过参数设置获取日k线、周k线、月k线,以及5分钟、15分钟、30分钟和60分钟k线数据,
    适合搭配均线数据进行选股和分析。
    返回类型:pandas的DataFrame类型。
    可查询不复权、前复权、后复权数据。
    """
    all_stock = pd.read_csv(path + "all_stock.csv")
    all_stock.drop_duplicates(subset=['code'], keep='first', inplace=True)
    #### 登陆系统 ####
    lg = bs.login()
    # 显示登陆返回信息
    #print('login respond error_code:'+lg.error_code)
    #print('login respond  error_msg:'+lg.error_msg)

    #### 获取沪深A股历史K线数据 ####
    # 详细指标参数,参见“历史行情指标参数”章节
    result_all = pd.DataFrame([])
    for code in all_stock.code:
        rs = bs.query_history_k_data(
            code,
            "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNcfTTM,isST",
            start_date=start_date,
            end_date=end_date,
            frequency="d",
            adjustflag="2")
        #print('query_history_k_data respond error_code:'+rs.error_code)
        #print('query_history_k_data 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_all = result_all.append(result)

    #### 结果集输出到csv文件 ####
    try:
        history_A_stock_k_data = pd.read_csv(path +
                                             "history_A_stock_k_data.csv")
    except:
        history_A_stock_k_data = pd.DataFrame([])
    result_all = result_all.append(history_A_stock_k_data)
    result_all.drop_duplicates(subset=['code', 'date'],
                               keep='first',
                               inplace=True)
    result_all.to_csv(path + "history_A_stock_k_data.csv", index=False)
    #print(result)

    #### 登出系统 ####
    bs.logout()
    return
Exemple #2
0
def computeKDJ(code, startdate, enddate):

    # 获取股票日K线数据
    rs = bs.query_history_k_data(code,
                                 "date,code,high,close,low,tradeStatus",
                                 start_date=startdate,
                                 end_date=enddate,
                                 frequency="d",
                                 adjustflag="3")
    # 打印结果集
    result_list = []

    while (rs.error_code == '0') & rs.next():
        # 获取一条记录,将记录合并在一起
        result_list.append(rs.get_row_data())
        df_init = pd.DataFrame(result_list, columns=rs.fields)
        # 剔除停盘数据
        df_status = df_init[df_init['tradeStatus'] == '1']
        low = df_status['low'].astype(float)
        del df_status['low']
        df_status.insert(0, 'low', low)
        high = df_status['high'].astype(float)
        del df_status['high']
        df_status.insert(0, 'high', high)
        close = df_status['close'].astype(float)
        del df_status['close']
        df_status.insert(0, 'close', close)
        # 计算KDJ指标,前9个数据为空
        low_list = df_status['low'].rolling(window=9).min()
        high_list = df_status['high'].rolling(window=9).max()
        rsv = (df_status['close'] - low_list) / (high_list - low_list) * 100
    df_data = pd.DataFrame()
    df_data['K'] = rsv.ewm(com=2).mean()
    df_data['D'] = df_data['K'].ewm(com=2).mean()
    df_data['J'] = 3 * df_data['K'] - 2 * df_data['D']
    df_data['date'] = df_status['date'].values
    df_data.index = df_status['date'].values
    df_data.index.name = 'date'

    # 删除空数据
    df_data = df_data.dropna()
    # 计算KDJ指标金叉、死叉情况
    df_data['x'] = ''

    kdj_position = df_data['K'] > df_data['D']

    df_data.loc[kdj_position[(kdj_position == True)
                             & (kdj_position.shift() == False)].index,
                'x'] = 'j'
    df_data.loc[kdj_position[(kdj_position == False)
                             & (kdj_position.shift() == True)].index,
                'x'] = 's'

    return (df_data)
Exemple #3
0
def return_constraintdict(stockcodelist):
    login_result = bs.login(user_id='anonymous', password='******')
    print('login respond error_msg:' + login_result.error_msg)

    startdate = '2018-08-21'  # 开始日期,从2018年1月1日开始
    today = datetime.datetime.now()  # 获取今天的时间 年 月 日 小时 分钟 秒 毫秒
    delta = datetime.timedelta(days=1)  # 两个时间的差值为1天
    # 获取截至上一个交易日的历史行情
    predate = today - delta  # 今天的时间 减去 两时间差值,定义为 predate 上一日这个时候的时间值
    strpredate = datetime.datetime.strftime(
        predate, '%Y-%m-%d')  # strpredate 是用 strftime 格式化后的 上一日时间表示
    print(strpredate)  # 打印上一天的日期,格式化过的:年-月-日
    for stockcode in stockcodelist:
        rs = bs.query_history_k_data(
            "%s" % stockcode,
            "date,code,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNcfTTM",
            start_date=startdate,
            end_date=strpredate,
            frequency="d",
            adjustflag="2")
        # rs 为从bs中查询到的 该股票的(按从2018年1月1日起每一日的)k线数据信息,一共有14列
        print('query_history_k_data respond error_code:' + rs.error_code)
        print('query_history_k_data respond error_msg:' + rs.error_msg)
        # print (rs)  <baostock.data.resultset.ResultData object at 0x00000000144FDC50>  (是一个数据集)

        # 打印结果集
        result_list = []  # 结果列表 下面用 append 逐步添加数据
    while (rs.error_code == '0') & rs.next():
        # 获取一条记录,将记录合并在一起
        result_list.append(
            rs.get_row_data())  # 将 rs row_data/行数据 添加到result_list 中去
        print(result_list)  # 打印 result_list 结果集里的数据
        result = pd.DataFrame(
            result_list, columns=rs.fields
        )  # 定义一个 result 变量, 用pd.DataFrame的2个参数 result_list和 columns=rs.fields处理
        print(result)  # result 是一个类,被 pandas.core.frame.DataFrame 定义
        #print (type(result))
        closelist = list(result['close'])
        closelist = [float(price) for price in closelist]

        # 调用 TA-Lib 中的 MA 函数, 计算20日均线值
        malist = ta.MA(np.array(closelist), timeperiod=20)
        if len(malist) > 20 and closelist[-20] > 0:
            ma20value = malist[-1]
            summit20day = max(closelist[-10:])
            # 以突破10日高点且在20日均线以上作为买入条件
            resistancelinedict[stockcode] = max(ma20value, summit20day)
        else:
            resistancelinedict[stockcode] = float(closelist[-1])
            bs.logout()
    return resistancelinedict
Exemple #4
0
def computeMACD(code, startdate, enddate):
    login_result = bs.login(user_id='anonymous', password='******')
    print(login_result)
    # 获取股票日 K 线数据
    rs = bs.query_history_k_data(code,
                                 "date,code,close,tradeStatus",
                                 start_date=startdate,
end_date=enddate,
                                 frequency="d", adjustflag="3")
    # 打印结果集
    result_list = []

    while (rs.error_code == '0') & rs.next():
        # 获取一条记录,将记录合并在一起
        result_list.append(rs.get_row_data())
    df = pd.DataFrame(result_list, columns=rs.fields)
    # 剔除停盘数据
    df2 = df[df['tradeStatus'] == '1']
    # 获取 dif,dea,hist,它们的数据类似是 tuple,且跟 df2 的 date 日期一一对应
    # 记住了 dif,dea,hist 前 33 个为 Nan,所以推荐用于计算的数据量一般为你所求日期之间数据量的3倍
    # 这里计算的 hist 就是 dif-dea,而很多证券商计算的 MACD=hist*2=(dif-dea)*2


    dif, dea, hist = ta.MACD(df2['close'].astype(
        float).values, fastperiod=12, slowperiod=26, signalperiod=9)
    df3 = pd.DataFrame({'dif': dif[33:], 'dea': dea[33:], 'hist':
    hist[33:]},
                         index = df2['date'][33:], columns = ['dif', 'dea',
    'hist'])
    df3.plot(title='MACD')



    # 寻找 MACD 金叉和死叉
    datenumber = int(df3.shape[0])
    for i in range(datenumber - 1):
        if((df3.iloc[i, 0] <= df3.iloc[i, 1]) & (df3.iloc[i + 1, 0] >= df3.iloc[i + 1, 1])):
           print("MACD 金叉的日期:" + df3.index[i + 1])
        #TODO 加入微信触发提醒
        if ((df3.iloc[i, 0] >= df3.iloc[i, 1]) & (df3.iloc[i + 1, 0] <=
                                              df3.iloc[i + 1, 1])):
           print("MACD 死叉的日期:" + df3.index[i + 1])
           # TODO 加入微信触发提醒

    plt.show()
    df.to_csv("/Users/zou/PycharmProjects/weiyl_919/macd.csv", encoding='gbk')

    bs.logout()

    return (dif, dea, hist)
 def start_crawl(self):
     bs.login(user_id="anonymous", password="******")
     code_list = self.dm.get_code_list_02()
     for item in code_list:
         ticker = item["ticker"]
         max_try = 8
         for tries in range(max_try):
             rs = bs.query_history_k_data(ticker, "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg",
                                          start_date='2016-01-01', end_date='2017-12-31', frequency="d", adjustflag="2")
             if rs.error_code == '0':
                 self.parse_pager(rs, ticker)
                 break
             elif tries < (max_try - 1):
                 sleep(2)
                 continue
     bs.logout()
Exemple #6
0
def computeRSI(code, startdate, enddate):
    """计算证券在起止时间内的 RSI 指标。
    :param code:证券代码
    :param startdate:起始日期
    :param enddate:截止日期
    :return:
"""

    login_result = bs.login(user_id='anonymous', password='******')
    print(login_result.error_msg)
    # 获取股票日 K 线数据,adjustflag 复权状态(1:后复权, 2:前复权,3: 不复权)
    rs = bs.query_history_k_data(code,
                                 "date,code,close,tradeStatus",
                                 start_date=startdate,
                                 end_date=enddate,
                                 frequency="d",
                                 adjustflag="3")
    # 打印结果集
    result_list = []
    while (rs.error_code == '0') & rs.next():
        # 获取一条记录,将记录合并在一起
        result_list.append(rs.get_row_data())
    df_init = pd.DataFrame(result_list, columns=rs.fields)
    # 剔除停盘数据
    df_status = df_init[df_init['tradeStatus'] == '1']

    df_status['close'] = df_status['close'].astype(float)

    rsi_12days = ta.RSI(df_status['close'], timeperiod=12)
    rsi_6days = ta.RSI(df_status['close'], timeperiod=6)
    rsi_24days = ta.RSI(df_status['close'], timeperiod=24)
    df_status['rsi_6days'] = rsi_6days
    df_status['rsi_12days'] = rsi_12days
    df_status['rsi_24days'] = rsi_24days

    # RSI 超卖和超买
    rsi_buy_position = df_status['rsi_6days'] > 80
    rsi_sell_position = df_status['rsi_6days'] < 20

    df_status.loc[rsi_buy_position[(rsi_buy_position == True) &
                                   (rsi_buy_position.shift() == False)].index,
                  '超买'] = '超买'
    # TODO 加入微信触发提醒
    df_status.loc[rsi_sell_position[(rsi_sell_position == True) & (
        rsi_sell_position.shift() == False)].index, '超卖'] = '超卖'
    # TODO 加入微信触发提醒
    return df_status
Exemple #7
0
def download_price(start, end, ind_or_sto):
    # print(start, end)
    # login system
    lg = bs.login()
    # Display login infomration
    logger.info("login error code: {}, logging error messge: {}".format(lg.error_code, lg.error_msg))

    # Login error messgae, a detialed explanation of the error.
    df_stock = pd.read_excel(r'Tickers_download.xlsx')  # , sheet_name='Sheet 1'
    new_stock_list = []
    for i in df_stock.index:
        # print(df_stock['Ticker'][i])
        new_stock_list.append(df_stock['Ticker'][i])
    # print(new_stock_list)

    downloaded = os.listdir('downloads_price/')
    had = set()
    for f in downloaded:
        parts = f.split("_")
        had.add(int(parts[0]))

    t = start
    total = end - start
    count = 0
    for i in new_stock_list[start:end]:
        count += 1
        if (t in had):
            logger.info("====omit {}====".format(t))
            t += 1
            continue
        else:
            logger.info("====process {}_{}, {} out of {}====".format(i, t, count, total))
        result_list = []
        if ind_or_sto == "index":
            rs = bs.query_history_k_data_plus(i, "date,code,open,high,low,close,volume,amount", frequency="d")
        elif ind_or_sto == "stock":
            rs = bs.query_history_k_data(i, "date,code,open,high,low,close,volume,amount,adjustflag,turn,peTTM,pbMRQ,psTTM,pcfNcfTTM,pctChg,isST", frequency="d", adjustflag="2")
        logger.info("error code: {}, error message: {}".format(rs.error_code, rs.error_msg))

        while (rs.error_code == '0') & rs.next():

            result_list.append(rs.get_row_data())
        result = pd.DataFrame(result_list, columns=rs.fields)
        output = "downloads_price/{}_{}.csv".format(t, i)
        t += 1
        result.to_csv(output, encoding="gbk", index=False)
Exemple #8
0
def getStocksDetail(stocks, startDay, endDay, frequency, adjustflag,
                    lastTradeDay):
    stock_data_list = []
    stock_fields = []
    for index, stock in stocks.iterrows():
        if stock['tradeStatus'] == '1' and 'sh.600' in stock['code']:
            rs = bs.query_history_k_data(
                stock['code'],
                "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNcfTTM,isST",
                startDay, endDay, frequency, adjustflag)
            print('请求历史数据返回信息:' + rs.error_msg)
            stock_fields = rs.fields
            while (rs.error_code == '0') & rs.next():
                rowData = rs.get_row_data()
                stock_data_list.append(rowData)

    # todo 添加名称、添加昨日涨跌幅
    return pd.DataFrame(stock_data_list, columns=stock_fields)
def bs_k_data_stock(code_val='sz.000651',
                    start_val='2009-01-01',
                    end_val='2019-06-01',
                    freq_val='d',
                    adjust_val='3'):

    # 登陆系统
    lg = bs.login()
    # 获取历史行情数据
    fields = "date,open,high,low,close,volume"
    df_bs = bs.query_history_k_data(
        code_val,
        fields,
        start_date=start_val,
        end_date=end_val,
        frequency=freq_val,
        adjustflag=adjust_val)  # <class 'baostock.data.resultset.ResultData'>
    # frequency="d"取日k线,adjustflag="3"默认不复权,1:后复权;2:前复权

    data_list = []

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

    result.close = result.close.astype('float64')
    result.open = result.open.astype('float64')
    result.low = result.low.astype('float64')
    result.high = result.high.astype('float64')
    result.volume = result.volume.astype('float64')
    result.volume = result.volume / 100  # 单位转换:股-手
    result.date = pd.DatetimeIndex(result.date)
    result.set_index("date", drop=True, inplace=True)
    result.index = result.index.set_names('Date')

    recon_data = {'High': result.high, 'Low': result.low, 'Open': result.open, 'Close': result.close,\
                  'Volume': result.volume}
    df_recon = pd.DataFrame(recon_data)

    # 登出系统
    bs.logout()
    return df_recon
    """
Exemple #10
0
    def __parse_baostock_data(self, code, start, end, freq):
        '''
          虽然价格都进行了复权,但是成交量和换手率都没有前复权(tushare和baostock都没做),同花顺也是, 东方财富做了。
          前复权的价格和同方财富以及同花顺有出入。
        '''
        '''
                能获取2011-01-01至当前时间的数据;
                date	交易所行情日期	格式:YYYY-MM-DD
                code	证券代码	格式:sh.600000。sh:上海,sz:深圳
                open	今开盘价格	精度:小数点后4位;单位:人民币元
                high	最高价	精度:小数点后4位;单位:人民币元
                low	最低价	精度:小数点后4位;单位:人民币元
                close	今收盘价	精度:小数点后4位;单位:人民币元
                preclose	昨日收盘价	精度:小数点后4位;单位:人民币元
                volume	成交数量	单位:股
                amount	成交金额	精度:小数点后4位;单位:人民币元
                adjustflag	复权状态	不复权、前复权、后复权
                turn	换手率	精度:小数点后6位;单位:%
                tradestatus	交易状态	1:正常交易 0:停牌
                pctChg	涨跌幅	精度:小数点后6位
                peTTM	动态市盈率	精度:小数点后4位
                psTTM	市销率	精度:小数点后4位
                pcfNcfTTM	市现率	精度:小数点后4位
                pbMRQ	市净率	精度:小数点后4位
                isST	是否ST	1是,0否'''

        try:
            rs = bs.query_history_k_data(
                code,
                "date,code,open,high,low,close,volume,turn",
                start_date=start,
                end_date=end,
                frequency=freq,
                adjustflag="2")
        except BaseException as e:
            logger.exception('query_history_k_data error')
            raise e
        # print(rs.data);
        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
Exemple #11
0
 def start_crawl(self):
     bs.login()
     code_list = self.dm.get_code_list_02()
     for item in code_list:
         ticker = item["ticker"]
         max_try = 8
         for tries in range(max_try):
             rs = bs.query_history_k_data(
                 ticker,
                 "date,code,close,peTTM,pbMRQ,psTTM,pcfNcfTTM",
                 start_date='2016-01-01',
                 end_date='2017-12-31',
                 frequency="d",
                 adjustflag="2")
             if rs.error_code == '0':
                 self.parse_pager(rs, ticker)
                 break
             elif tries < (max_try - 1):
                 sleep(2)
                 continue
     bs.logout()
Exemple #12
0
 def _get(code: str, date_start: str, date_end: str, period='d'):
     """
     baostock模块查询历史
     :param code: 'sz.002007'
     :param date_start: '2020-04-24'
     :param date_end: '2020-04-28'
     :param period: "d"
     :return:
     """
     rs = bs.query_history_k_data(
         code,
         "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNcfTTM,isST",
         start_date=date_start,
         end_date=date_end,
         frequency=period,
         adjustflag="2")  # frequency="d"取日k线,adjustflag="3"默认不复权
     data_list = []
     while (rs.error_code == '0') & rs.next():
         # 获取一条记录,将记录合并在一起
         data_list.append(rs.get_row_data())
     return data_list
def get_data(code):
    rs = bs.query_history_k_data(
        code,
        "date,code,open,close,high,low,volume,amount,turn",
        start_date='2010-01-01',
        end_date='2019-04-01',
        frequency="d",
        adjustflag="3")
    print('query_history_k_data respond error_code:' + rs.error_code)
    print('query_history_k_data 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.drop(['adjustflag'],axis=1,inplace=True)
    result.to_csv(
        str("data/datas/" + code + "_data.csv"),
        index=False,
    )
    # print(result)
    return None
Exemple #14
0
 def _get_stock_kdata(self, code: string,
                      update_time: datetime.datetime) -> list:
     '''
         1. 查询数据库现有数据,获取离当日最近日期的数据(判断当日是否是最后一个工作日,是的话,就去下一个工作日作为startDate), endDate作为截止日期
         2. 根据上一步的startDate和endDate,获取历史数据
         3. 保存获取到的数据到数据库里
     '''
     print("%s, %s, %s" %
           (__name__, "update_time", update_time.strftime("%Y-%m-%d")))
     print("%s, %s, %s" %
           (__name__, "now_time", timezone.now().strftime("%Y-%m-%d")))
     if update_time.strftime("%Y-%m-%d") < timezone.now().strftime(
             "%Y-%m-%d"):
         start_date = update_time.strftime("%Y-%m-%d")
         end_date = timezone.now().strftime("%Y-%m-%d")
     else:
         start_date, end_date = self._update_date_range(code)
     # 根据start date 和end date 获取历史数据
     rs = baostock.query_history_k_data(
         code,
         "code,close,peTTM,pbMRQ,psTTM,pcfNcfTTM,date",
         start_date=start_date,
         end_date=end_date)
     result = list()
     while (rs.error_code == '0') & rs.next():
         kdata = rs.get_row_data()
         # 因为取的是数据库中时间离当前最近的一条数据作为start time,所以这条数据不用重新保存
         if self.is_exist(kdata, start_date):
             continue
         result.append(
             StockKData(
                 code=kdata[0],
                 close=Decimal(kdata[1]) if kdata[1] else Decimal(0),
                 peTTM=Decimal(kdata[2]) if kdata[2] else Decimal(0),
                 pbMRQ=Decimal(kdata[3]) if kdata[3] else Decimal(0),
                 psTTM=Decimal(kdata[4]) if kdata[4] else Decimal(0),
                 pcfNcfTTM=Decimal(kdata[5]) if kdata[5] else Decimal(0),
                 date=timezone.make_aware(
                     datetime.datetime.strptime(kdata[6], '%Y-%m-%d'))))
     return result
Exemple #15
0
 def load_his_k_data(self, stack_code, start_date, end_date):
     #### 获取历史K线数据 ####
     data_list = []
     res = bs.query_history_k_data(
         stack_code,
         index_pro if self._freq == 'd' else index_mini,
         start_date=start_date,
         end_date=end_date,
         frequency=self._freq,
         adjustflag="3")  #frequency="d"取日k线,adjustflag="3"默认不复权
     show_error(sys._getframe().f_code.co_name, res)
     while (res.error_code == '0') & res.next():
         # 获取一条记录,将记录合并在一起
         data_list.append(res.get_row_data())
     df_data = pd.DataFrame(data_list, columns=res.fields)
     df_data.set_index(["date"], inplace=True)
     df_data.index = pd.to_datetime(df_data.index)
     df_data[['low', 'high', 'open', 'close', 'volume'
              ]] = df_data[['low', 'high', 'open', 'close',
                            'volume']].astype(float)
     self._k_data = df_data
     self._k_data_plus = df_data
Exemple #16
0
def normalize_one_stock(bs, stock_code):
    if stock_code[:2] == '60':
        stock_code = 'sh.' + stock_code
    else:
        stock_code = 'sz.' + stock_code
    rs = bs.query_history_k_data(stock_code,
                                 "date, amount",
                                 start_date='2014-01-01',
                                 end_date='2018-11-30',
                                 frequency="d",
                                 adjustflag="2")
    print('Now dealing stock {}'.format(stock_code))
    print(rs.error_msg)
    print(rs.error_code)
    # 获取具体的信息
    result_list = []
    while (rs.error_code == '0') & rs.next():
        result_list.append(rs.get_row_data())
    result_list = [float(date[1]) for date in result_list]
    range = max(result_list) - min(result_list)
    minval = min(result_list)
    normalize_list = [(i - minval) / range for i in result_list]
    return normalize_list
Exemple #17
0
def start_crawl():
    lg = bs.login()
    print('login response error_code:' + lg.error_code)
    print('login respond  error_msg:' + lg.error_msg)
    code_list = dm.get_code_list()
    for item in code_list:
        ticker = item["ticker"]
        max_try = 8
        for tries in code_list:
            rs = bs.query_history_k_data(
                ticker,
                "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatue,pctChg",
                start_date='2018-01-01',
                end_date='2018-07-28',
                frequency="d",
                adjustflag="2")
            if rs.error_code == '0':
                parse_pager(rs, ticker)
                break
            elif tries < (max_try - 1):
                sleep(2)
                continue
        bs.logout()
def return_constraintdict(stock_code_list, startdate):
    login_result = bs.login()
    print ('login respond error_msg:' + login_result.error_msg)

    today = datetime.datetime.now()
    delta = datetime.timedelta(days = 1)

#get the history market data till last exchange date
    predate = today - delta
    strpredate = datetime.datetime.strftime(predate, '%Y-%m-%d')
    for stock_code in stock_code_list:
        rs = bs.query_history_k_data("%s" % stock_code, "date, code, open, close, preclose, volume, amount, adjustflag, turn, tradestatus, pctChg, peTTM, pbMRQ, psTTM, pcfNcfTTM",
                start_date = startdate, end_date=strpredate, frequency="d", adjustflag="2")
        print ('query_history_k_data respond error_code:' + rs.error_code)
        print ('query_history_k_data respond error_msg:' + rs.error_msg)

        result_list = []
        while(rs.error_code == '0') & rs.next():
            result_list.append(rs.get_row_data())
        result = pd.DataFrame(result_list, columns=rs.fields)
        print (result)

        closelist = list(result['close'])
        closelist = [float(price) for price in closelist]
Exemple #19
0
    def get_data(self, id, start='2018-01-01', end='2018-07-17'):
        #### 获取沪深A股历史K线数据 ####
        # 详细指标参数,参见“历史行情指标参数”章节
        rs = bs.query_history_k_data(
            "sh." + str(id),
            "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,isST",
            start_date=start,
            end_date=end,
            frequency="d",
            adjustflag="3")
        print('query_history_k_data respond error_code:' + rs.error_code)
        print('query_history_k_data 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:\\history_A_stock_k_data.csv", index=False)
        # print(result['turn'])
        return result
Exemple #20
0
    def computeKDJ(self, code, startdate, enddate, is_show, is_refresh,
                   period):
        login_result = bs.login(user_id='anonymous', password='******')
        print(login_result.error_msg)

        # 获取股票日K线数据
        rs = bs.query_history_k_data(code,
                                     "date,code,high,close,low,tradeStatus",
                                     start_date=startdate,
                                     end_date=enddate,
                                     frequency="d",
                                     adjustflag="3")

        # 打印结果集
        result_list = []

        while (rs.error_code == '0') & rs.next():
            # 获取一条记录,将记录合并在一起
            result_list.append(rs.get_row_data())
        df_init = pd.DataFrame(result_list, columns=rs.fields)
        # 剔除停盘数据
        df_status = df_init[df_init['tradeStatus'] == '1']

        low = df_status['low'].astype(float)
        del df_status['low']
        df_status.insert(0, 'low', low)
        high = df_status['high'].astype(float)
        del df_status['high']
        df_status.insert(0, 'high', high)
        close = df_status['close'].astype(float)
        del df_status['close']
        df_status.insert(0, 'close', close)

        # 计算KDJ指标,前9个数据为空
        low_list = df_status['low'].rolling(window=9).min()
        high_list = df_status['high'].rolling(window=9).max()

        rsv = (df_status['close'] - low_list) / (high_list - low_list) * 100

        df_data = pd.DataFrame()
        df_data['K'] = rsv.ewm(com=2).mean()
        df_data['D'] = df_data['K'].ewm(com=2).mean()
        df_data['J'] = 3 * df_data['K'] - 2 * df_data['D']

        df_data.index = df_status['date'].values
        df_data.index.name = 'date'
        # 删除空数据
        df_data = df_data.dropna()
        # 记录index切片list
        loc_list = range(len(df_data))[::period]
        df_data = df_data.iloc[loc_list, :]
        df_data.plot(title=f'KDJ_{period}day')
        #计算KDJ指标金叉、死叉情况
        df_data['KDJ_金叉死叉'] = ''
        kdj_position = df_data['K'] > df_data['D']
        df_data.loc[kdj_position[(kdj_position == True)
                                 & (kdj_position.shift() == False)].index,
                    'KDJ_金叉死叉'] = '金叉'
        df_data.loc[kdj_position[(kdj_position == False)
                                 & (kdj_position.shift() == True)].index,
                    'KDJ_金叉死叉'] = '死叉'

        if is_show:
            plt.show()
        if is_refresh:
            df_data.to_csv(os.path.join(root, "KDJ.csv"), encoding='gbk')
        bs.logout()
        return (df_data)
Exemple #21
0
@author shilong
'''

import baostock as bs

import pandas as pd
import matplotlib.pyplot as plt

lg=bs.login()

#print('login respond error_code:'+lg.error_code)
#print('login respond  error_msg:'+lg.error_msg)

fields= "date,code,open,high,low,close"
rs = bs.query_history_k_data("sz.000831", fields,
    start_date='2019-01-01', end_date='2019-02-21',
    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)
#### 结果集输出到csv文件 ####
result.to_csv("gif/history_k_data.csv",
        encoding="gbk", index=False)
print(result)
result.head()
Exemple #22
0
import baostock as bs
import pandas as pd

#### 登陆系统 ####
lg = bs.login(user_id="anonymous", password="******")
#### 获取沪深A股估值指标(日频)数据 ####
# peTTM    动态市盈率
# psTTM    市销率
# pcfNcfTTM    市现率
# pbMRQ    市净率
rs = bs.query_history_k_data("sh.600000",
                             "date,code,close,peTTM,pbMRQ,psTTM,pcfNcfTTM",
                             start_date='2015-01-01',
                             end_date='2017-12-31',
                             frequency="d",
                             adjustflag="3")
#### 打印结果集 ####
result_list = []
while (rs.error_code == '0') & rs.next():
    # 获取一条记录,将记录合并在一起
    result_list.append(rs.get_row_data())
result = pd.DataFrame(result_list, columns=rs.fields)

#### 结果集输出到csv文件 ####
result.to_csv("peTTM_sh.600000_data.csv", encoding="gbk", index=False)
print(result)

#### 登出系统 ####
bs.logout()
Exemple #23
0
'''
证券宝API 获取 stock data
'''
import baostock as bs
import matplotlib.pyplot as plt
import pandas as pd

#### 登陆系统 ####
lg = bs.login()

#### 获取历史K线数据 ####
# query_history_k_data()
fields = "date,code,open,high,low,close"
rs = bs.query_history_k_data("sh.000001",
                             fields,
                             start_date='2000-01-01',
                             end_date='2018-09-07',
                             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)
#### 结果集输出到csv文件 ####
#result.to_csv("c:/zjy/history_k_data.csv",
#        encoding="gbk", index=False)
result.head()
Exemple #24
0
import tushare as ts


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

#### 获取沪深A股历史K线数据 ####
# 详细指标参数,参见“历史行情指标参数”章节



rs = bs.query_history_k_data("sz.002597",
    "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,isST,peTTM,pbMRQ",
    start_date='2014-01-01', end_date='2018-06-01',
    frequency="d", adjustflag="2")

print(type(rs))


print('query_history_k_data respond error_code:'+rs.error_code)
print('query_history_k_data 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)
Exemple #25
0
import baostock as bs
import pandas as pd

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

#### 获取历史K线数据 ####
# 详细指标参数,参见“历史行情指标参数”章节
rs = bs.query_history_k_data("sh.600000",
    "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNcfTTM,isST",
    start_date='2017-06-01', end_date='2017-12-31', 
    frequency="d", adjustflag="3") #frequency="d"取日k线,adjustflag="3"默认不复权

print('query_history_k_data respond error_code:'+rs.error_code)
print('query_history_k_data 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:/history_k_data.csv", encoding="gbk", index=False)
print(result)

#### 登出系统 ####
bs.logout()
Exemple #26
0
import fileinput

i = 1
# 登陆系统
lg = bs.login(user_id="anonymous", password="******")
with fileinput.input(files=('D:\code.EBK')) as f:
    for line in f:
        print(i)
        # print(line)
        line = line.replace("\n", "")

        # 详细指标参数,参见“历史行情指标参数”章节
        rs = bs.query_history_k_data(
            line,
            "date,code,open,high,low,close,volume,amount,adjustflag",
            start_date='2021-05-13',
            end_date='2021-05-17',
            frequency="15",
            adjustflag="3")
        #print(rs.error_code)
        #print(rs.error_msg!='')

        # 获取具体的信息
        result_list = []

        while (rs.error_code == '0') & rs.next():

            # 分页查询,将每页信息合并在一起
            result_list.append(rs.get_row_data())
            index = 0
        for el in result_list:
import baostock as bs
import pandas as pd

if __name__ == "__main__":
    # 登陆系统
    lg = bs.login(user_id="anonymous", password="******")
    # 显示登陆返回信息
    print('login respond error_code:' + lg.error_code)
    print('login respond  error_msg:' + lg.error_msg)

    # 获取沪深A股历史K线数据
    # 详细指标参数,参见“历史行情指标参数”章节
    rs = bs.query_history_k_data(
        "sh.600000",
        "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,isST",
        start_date='2017-07-01',
        end_date='2017-12-31',
        frequency="d",
        adjustflag="3")
    print('query_history_k_data respond error_code:' + rs.error_code)
    print('query_history_k_data respond  error_msg:' + rs.error_msg)

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

    # print(result)
Exemple #28
0
import pandas as pd
import fileinput
i = 1
with fileinput.input(files=('c:\code.EBK')) as f:
    for line in f:
        print(i)
        print(line)
        line = line.replace("\n", "")

        # 登陆系统
        lg = bs.login(user_id="anonymous", password="******")
        # 详细指标参数,参见“历史行情指标参数”章节
        rs = bs.query_history_k_data(
            line,
            "date,code,open,high,low,close,volume,amount,adjustflag",
            start_date='2019-07-03',
            end_date='2019-07-08',
            frequency="d",
            adjustflag="3")
        #print(rs.error_code)
        #print(rs.error_msg!='')

        # 获取具体的信息
        result_list = []
        while (rs.error_code == '0') & rs.next():
            # 分页查询,将每页信息合并在一起
            result_list.append(rs.get_row_data())
        for el in result_list:
            pricedata = ";INSERT INTO dbo.lishijiage (code,riqi,kai,shou,di,gao,chengjiaoliang) VALUES ('%s', '%s','%s',N'%s',N'%s',N'%s',N'%s')" % (
                el[1], el[0], el[2], el[5], el[4], el[3], el[7])
            with open('D:\\' + str(i) + '.sql', 'a+') as f2:
#### 获取指数(综合指数、规模指数、一级行业指数、二级行业指数、策略指数、成长指数、价值指数、主题指数)K线数据 ####
##综合指数,例如:sh.000001 上证指数,sz.399106 深证综指 等;
##规模指数,例如:sh.000016 上证50,sh.000300 沪深300,sh.000905 中证500,sz.399001 深证成指等;
##一级行业指数,例如:sh.000037 上证医药,sz.399433 国证交运 等;
##二级行业指数,例如:sh.000952 300地产,sz.399951 300银行 等;
##策略指数,例如:sh.000050 50等权,sh.000982 500等权 等;
##成长指数,例如:sz.399376 小盘成长 等;
##价值指数,例如:sh.000029 180价值 等;
##主题指数,例如:sh.000015 红利指数,sh.000063 上证周期 等;

# 详细指标参数,参见“历史行情指标参数”章节
rs = bs.query_history_k_data(
    "sh.600000",
    "date,code,open,high,low,close,preclose,volume,amount,pctChg",
    start_date='2017-01-01',
    end_date='2017-06-30',
    frequency="d",
    adjustflag="3")
print('query_history_k_data respond error_code:' + rs.error_code)
print('query_history_k_data 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:\\history_Index_k_data.csv", index=False)
print(result)
Exemple #30
0
    def computeMACD(self, code, startdate, enddate, is_show, is_refresh,
                    period):
        login_result = bs.login(user_id='anonymous', password='******')
        print(login_result)
        # 获取股票日 K 线数据
        rs = bs.query_history_k_data(code,
                                     "date,code,close,tradeStatus",
                                     start_date=startdate,
                                     end_date=enddate,
                                     frequency="d",
                                     adjustflag="3")
        # 打印结果集
        result_list = []

        while (rs.error_code == '0') & rs.next():
            # 获取一条记录,将记录合并在一起
            result_list.append(rs.get_row_data())
        df = pd.DataFrame(result_list, columns=rs.fields)
        # 剔除停盘数据
        df2 = df[df['tradeStatus'] == '1']
        # 获取 dif,dea,hist,它们的数据类似是 tuple,且跟 df2 的 date 日期一一对应
        # 记住了 dif,dea,hist 前 33 个为 Nan,所以推荐用于计算的数据量一般为你所求日期之间数据量的3倍
        # 这里计算的 hist 就是 dif-dea,而很多证券商计算的 MACD=hist*2=(dif-dea)*2

        dif, dea, hist = ta.MACD(df2['close'].astype(float).values,
                                 fastperiod=12,
                                 slowperiod=26,
                                 signalperiod=9)
        df3 = pd.DataFrame(
            {
                'dif': dif[33:],
                'dea': dea[33:],
                'hist': hist[33:]
            },
            index=df2['date'][33:],
            columns=['dif', 'dea', 'hist'])

        loc_list = range(len(df3))[::period]
        df3 = df3.iloc[loc_list, :]
        df3.plot(title=f'MACD_{period}day')
        # 寻找 MACD 金叉和死叉
        datenumber = int(df3.shape[0])
        for i in range(datenumber - 1):
            if ((df3.iloc[i, 0] <= df3.iloc[i, 1]) &
                (df3.iloc[i + 1, 0] >= df3.iloc[i + 1, 1])):
                print("MACD 金叉的日期:" + df3.index[i + 1])
                # df_data.loc[kdj_position[(kdj_position == True) &
                #   (kdj_position.shift() == False)].index, 'KDJ_金叉死叉'] = '金叉'

            if ((df3.iloc[i, 0] >= df3.iloc[i, 1]) &
                (df3.iloc[i + 1, 0] <= df3.iloc[i + 1, 1])):
                print("MACD 死叉的日期:" + df3.index[i + 1])
        # 记录index切片list

        if is_show:
            plt.show()
        if is_refresh:
            df.to_csv(os.path.join(root, "macd.csv"), encoding='gbk')
        bs.logout()

        return (dif, dea, hist)