python爬取新浪股票数据—绘图【原创分享】

时间:2023-01-11 19:09:14

目标:不做蜡烛图,只用折线图绘图,绘出四条线之间的关系。

注:未使用接口,仅爬虫学习,不做任何违法操作。

 """
新浪财经,爬取历史股票数据
""" # -*- coding:utf-8 -*- import numpy as np
import urllib.request, lxml.html
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re, time
import matplotlib.pyplot as plt
from datetime import datetime
# 绘图显示中文设置
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False # 公共模块,请求头信息
def public(link):
r = urllib.request.Request(link) ug = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0' r.add_header('User-Agent', ug) cookie = "SUB=_2AkMsqZjif8NxqwJRmfkRxG7nZYpzyg_EieKa9Wk5JRMyHRl-yD83qkJatRB6Bym2DDqPE870e3uMsySIjHjrMbMNxNqk; " \
"SUBP=0033WrSXqPxfM72-Ws9jqgMF55529P9D9WFXmxLGpAG5k05lCJw6qgYe; " \
"SINAGLOBAL=172.16.92.24_1542789082.401113; " \
"Apache=172.16.92.24_1542789082.401115; UOR=www.baidu.com,blog.sina.com.cn,; " \
"ULV=1542789814434:1:1:1:172.16.92.24_1542789082.401115:; U_TRS1=000000d1.1f4d3546.5bf53673.955fa32e; " \
"U_TRS2=000000d1.1f593546.5bf53673.736853cc; FINANCE2=661413ac85cadaab72ec7e3d842d6a3a; _s_upa=1" r.add_header("Cookie", cookie) html = urllib.request.urlopen(r, timeout=500).read() bsObj = BeautifulSoup(html, "lxml") # 将html对象转化为BeautifulSoup对象 return bsObj # 获取股票价格
def shares_price(code, year, quarter):
link = "http://money.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/%s.phtml?year=%d&jidu=%d" % (code, year, quarter) bsObj = public(link)
# print(bsObj) a = 0
# date_list为日期列表,open_list为开盘价列表,high_list为最高价列表,close_list为收盘价列表,low_list为最低价列表
price_list, date_list, open_list, high_list, close_list, low_list = [], [], [], [], [], []
# 获取股票信息
jpg_title = re.findall("(.*?\))", bsObj.title.text) prices_bs = bsObj.find_all(name='div', attrs={"align": 'center'})
# 获取并处理价格信息
for price_bs in prices_bs:
# 去除空格
price_bs_1 = price_bs.text.replace("\n\r\n\t\t\t", "")
price_bs_2 = price_bs_1.replace("\t\t\t\n", "") # 6个字符串为一个列表
if a != 6:
price_list.append(price_bs_2)
a = a + 1
else:
date_list.append(price_list[0])
open_list.append(price_list[1])
high_list.append(price_list[2])
close_list.append(price_list[3])
low_list.append(price_list[4])
a = 0
price_list = []
# 删除列表头
for b in (date_list, open_list, high_list, close_list, low_list):
b.pop(0) # 全部倒序排列(由日期远到近,从左到右排列)
for c in (date_list, open_list, high_list, close_list, low_list):
c.reverse() return date_list, open_list, high_list, close_list, low_list, jpg_title # 输入股票代码,年份,季度
code = ""
year = ""
quarter = 4
# 以下为手动输入模式,因调试方便默认上面固定模式。
# code = input("code:") # 002925
# year = input("year:") # 2018
# quarter = int(input("quarter:")) # 列表字符串转为数值date
x = [datetime.strptime(d, '%Y-%m-%d').date() for d in shares_price(code, int(year), quarter)[0]]
# 将爬取的数据(字符串)转化为浮点型
open_list = [float(i) for i in shares_price(code, int(year), quarter)[1]]
high_list = [float(i) for i in shares_price(code, int(year), quarter)[2]]
close_list = [float(i) for i in shares_price(code, int(year), quarter)[3]]
low_list = [float(i) for i in shares_price(code, int(year), quarter)[4]] # 线条设置
plt.plot(x, open_list, label='open', linewidth=1, color='red', marker='o', markerfacecolor='blue', markersize=2)
plt.plot(x, high_list, label='high', linewidth=1, color='green', marker='o', markerfacecolor='blue', markersize=2)
plt.plot(x, close_list, label='close', linewidth=1, color='blue', marker='o', markerfacecolor='blue', markersize=2)
plt.plot(x, low_list, label='low', linewidth=1, color='black', marker='o', markerfacecolor='blue', markersize=2) # 取数列最大数值与最小值做图表的边界值。
plt.ylim(min(low_list)-1, max(high_list)+1)
plt.gcf().autofmt_xdate() # 自动旋转日期标记 # 打印表头
plt.xlabel('time')
plt.ylabel('price')
# shares_price(code, int(year), quarter)[5][0]为title中的股票名称与代码
plt.title('gp_1_{0}.jpg'.format(shares_price(code, int(year), quarter)[5][0]))
plt.legend()
plt.show()

效果如下:

python爬取新浪股票数据—绘图【原创分享】

是不是有另一种看法的感觉?如:黑线下跌后向上的第一个大拐点为买入点。