Python 爬取股票历史数据_爬取股票历史数据并绘制K线图(pyecharts2021最新版本方法)

2021/10/17 14:11:07

本文主要是介绍Python 爬取股票历史数据_爬取股票历史数据并绘制K线图(pyecharts2021最新版本方法),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

前言:最近在做量化程序设计的初步阶段,发现pyecharts的包已经更新了,网上的使用方法已经不能在最新版本使用了。经过不断查询和探索终于把K线图画出来

 

import requests
from lxml import etree

headers = {
    'User-Agent':'Mozilla/5.0(Windows NT 6.1; WOW64) AppleWebkit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'
}
def parse_url(url):
    response = requests.get(url,headers=headers)
    if response.status_code == 200:
        return etree.HTML(response.content)
    return False

def get_date(response):
    start_date = ".join(response.xpath('//input[@name = 'date_start_type']/@value')[0].split('-'))"
    end_date = ".join(response.xpath('//input[@name = 'date_end_type']/@value')[0].split('-'))"
    code = response.xpath('//h1[@class= "name"]/span/a/text()')[0]
    return code,start_date,end_date

url中的参数code,start和end的值会变,其他参数值固定。
其中code的参数值为该股票所属沪市(0)或深市(1)的代码+股票代码,
start参数为要下载的日期期间的开始值(默认为上市日),
end参数为要下载的日期期间的截至值(默认为下载当天,即今日)。
def download(code,start_date,end_date):
    download_url="http://quotes.money.163.com/service/chddata.html?code=0"+code+"&start="+start_date+"&den="+end_date+"&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VATURNOVER;VATURNOVER;TCAP;MCAP"
    print(download_url)
    data=requests.get(download_url,headers=headers)
    f = open(code + '.csv','wb')
    for chunk in data.iter_content(chunk_size=10000):
        if chunk:
            f.write(chunk)
    print("股票---",code,'历史数据正在下载')

ulr="http://quotes.money.163.com/trade/lsjysj_600893.html"
response= parse_url(ulr)
code,start_date,end_date=get_date(response)
download(code,start_date,end_date)


import pandas as pd
import  numpy as np
stock =pd.read_csv(code+'.csv',usecols=[0,1,2,3,4,5,6],encoding='gbk')
stock.head()
stock_new=stock.iloc[:180,:]
stock_new_sorted = stock_new.sort_values('日期',ascending=True)
stock_new_sorted.head()


前面的代码就不多做赘述了,就是找到数据下载链接,然后分析数据规律,把数据下载下来。


from pyecharts.charts import Kline
from pyecharts import options as opts

stock_code=stock_new_sorted['股票代码'][0]
stock_name=stock_new_sorted['名称'][0]
index = stock_new_sorted['日期']
通过读取csv文件出来的数据是没有经过处理的格式,需要进行转制然后存进列表中
index1 = np.array(index)
index2 = index1.tolist()
stock_tclose=stock_new_sorted.loc[:,['开盘价','收盘价','最低价','最高价']]
stock_tclose1=np.array(stock_tclose)
stock_tclose2= stock_tclose1.tolist()


kline = (
    Kline()
         .add_xaxis(xaxis_data=index2)
         .add_yaxis(series_name=stock_code+stock_name,y_axis=stock_tclose2))
kline.render('hangdadongli.html')



这篇关于Python 爬取股票历史数据_爬取股票历史数据并绘制K线图(pyecharts2021最新版本方法)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程