提前建立下载目录文件夹
import baostock as bs
import pandas as pd
import datetime# 是否删除停盘数据
DROP_SUSPENSION = Truedef load_stk_list():df = pd.read_csv('D:/stk_list.csv')return df['code'].tolist()def convert_time(t):H = t[8:10]M = t[10:12]S = t[12:14]return H + ':' + M + ':' + Sdef download_data(stk_list=[], fromdate='1990-12-19', todate=datetime.date.today(),datas='date,open,high,low,close,volume,amount,turn,pctChg',frequency='d', adjustflag='2'):for code in stk_list:print("Downloading :" + code)k_rs = bs.query_history_k_data_plus(code, datas, start_date=fromdate, end_date=todate.strftime('%Y-%m-%d'),frequency=frequency, adjustflag=adjustflag)datapath = 'D:/baostock/' + frequency + '/' + code + '.csv'out_df = k_rs.get_data()if DROP_SUSPENSION and 'volume' in list(out_df):out_df.drop(out_df[out_df.volume == '0'].index, inplace=True)# 做time转换if frequency in ['5', '15', '30', '60'] and 'time' in list(out_df):out_df['time'] = out_df['time'].apply(convert_time)out_df.to_csv(datapath, encoding='gbk', index=False)def update_stk_list(date=None):# 获取指定日期的指数、股票数据stock_rs = bs.query_all_stock(date)stock_df = stock_rs.get_data()print(stock_df)stock_df.drop(stock_df[stock_df.code < 'sh.600000'].index, inplace=True)stock_df.drop(stock_df[stock_df.code > 'sz.399000'].index, inplace=True)stock_df = stock_df['code']return stock_df.tolist()if __name__ == '__main__':bs.login()# 首次运行# stk_list = update_stk_list(datetime.date.today() - datetime.timedelta(days=31))# print(stk_list)# 非首次运行stk_list = load_stk_list()# 下载日线download_data(stk_list)bs.logout()