Python 使用 baostock 库获取过去 6 个季度的财务数据
import baostock as bs import pandas as pd import pymysql
登陆系统
lg = bs.login()
显示登陆返回信息
print('login respond error_code:' + lg.error_code) print('login respond error_msg:' + lg.error_msg)
连接数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='baostock', charset='utf8mb4')
获取游标
cursor = conn.cursor()
成长能力
growth_list = [] for quarter in range(6, 0, -1): if quarter == 1: year = 2021 else: year = 2022 rs_growth = bs.query_growth_data(code='sh.600000', year=year, quarter=quarter) while (rs_growth.error_code == '0') & rs_growth.next(): growth_list.append(rs_growth.get_row_data()) result_growth = pd.DataFrame(growth_list, columns=rs_growth.fields)
打印输出
print(result_growth)
结果集插入到数据库
for index, row in result_growth.iterrows(): sql = 'INSERT INTO cznl VALUES ('sh.600000', {}, {}, '{}', {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {})'.format( int(row[1]), int(row[2]), row[3], float(row[4]), float(row[5]), float(row[6]), float(row[7]), float(row[8]), float(row[9]), float(row[10]), float(row[11]), float(row[12]), float(row[13]), float(row[14])) cursor.execute(sql) conn.commit()
关闭游标和连接
cursor.close() conn.close()
登出系统
bs.logout()
原文地址: https://www.cveoy.top/t/topic/mzoR 著作权归作者所有。请勿转载和采集!