Python爬取股票数据,制作动态柱状图
前言
雪球成立于 2010 年 ,是北京雪球信息科技有限公司旗下推出的投资者社区。雪球一直致力于为中国投资者提供跨市场(沪深、香港、美国),跨品种(股票、基金、债券等)的数据查询、资讯获取和互动交流以及交易服务。
requests >>> pip install requests (数据请求 第三方模块)
re # 正则表达式 去匹配提取数据
json
pandas
pyecharts
Python 3.8 解释器
Pycharm 2021.2 版本
- 发送请求 访问网站
- 获取数据
- 解析数据(提取数据)
- 保存数据
- 做柱状图 简单的可视化
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36' } url = 'https://xueqiu.com/service/v5/stock/screener/quote/list?page=1&size=30&order=desc&order_by=amount&exchange=CN&market=CN&type=sha&_=1641730868838' response = requests.get(url=url, headers=headers)
json_data = response.json()
data_list = json_data['data']['list'] for data in data_list: data1 = data['symbol'] data2 = data['name'] data3 = data['current'] data4 = data['chg'] data5 = data['percent'] data6 = data['current_year_percent'] data7 = data['volume'] data8 = data['amount'] data9 = data['turnover_rate'] data10 = data['pe_ttm'] data11 = data['dividend_yield'] data12 = data['market_capital'] print(data1, data2, data3, data4, data5, data6, data7, data8, data9, data10, data11, data12) data_dict = { '股票代码': data1, '股票名称': data2, '当前价': data3, '涨跌额': data4, '涨跌幅': data5, '年初至今': data6, '成交量': data7, '成交额': data8, '换手率': data9, '市盈率(TTM)': data10, '股息率': data11, '市值': data12, } csv_write.writerow(data_dict)
file = open('data2.csv', mode='a', encoding='utf-8', newline='') csv_write = csv.DictWriter(file, fieldnames=['股票代码','股票名称','当前价','涨跌额','涨跌幅','年初至今','成交量','成交额','换手率','市盈率(TTM)','股息率','市值']) csv_write.writeheader()
data_df = pd.read_csv('data2.csv') df = data_df.dropna() df1 = df[['股票名称', '成交量']] df2 = df1.iloc[:20] print(df2['股票名称'].values) print(df2['成交量'].values) c = ( Bar() .add_xaxis(df2['股票名称'].values.tolist()) .add_yaxis("股票成交量情况", df2['成交量'].values.tolist()) .set_global_opts( title_opts=opts.TitleOpts(title="成交量图表 - Volume chart"), datazoom_opts=opts.DataZoomOpts(), ) .render("data.html") ) print('数据可视化结果完成,请在当前目录下查找打开 data.html 文件!')