利用本地csv文件绘制股票走势图(pyercharts)

很多股票数据都是csv文件的,当然也可以利用excel文件另存为csv即可;

笔者近期结合工作情况,利用本地csv文件绘制股票走势图。

首先下载需要的数据,如沪深300指数和中证500指数数据:

最后成图:

#!/usr/bin/python3

#导入需要的包
import csv
from pyecharts import options as opts
from pyecharts.charts import Line

#文件地址
f1 = 'C:\\Users\\Administrator\\Desktop\\test\\指数行情_000300.csv'
f2 = 'C:\\Users\\Administrator\\Desktop\\test\\指数行情_000905.csv'

#创建空列表
t1 = []
t2 = []
t3 = []

#读取其中一个文件
with open(f1, 'r',newline='',encoding='utf-8') as f:
    reader = csv.reader(f)
    
    header = next(reader)    
    print(header) #打印表头

 

 逐行读取数据,并添加到列表中:

    for i in reader:
        t1.append(i[2]) #添加到列表,append() 方法用于在列表末尾添加新的对象,语法:list.append()
        t2.append(i[6])

with open(f2, 'r',newline='',encoding='utf-8') as f:
    reader = csv.reader(f)
    for j in reader:
        t3.append(j[6])

直接画图:

c = (
    Line()
    .add_xaxis(t1)
    .add_yaxis("沪深300", t2)
    .add_yaxis("中证500", t3)

    .set_global_opts(
        title_opts=opts.TitleOpts(title="沪深300VS中证500",subtitle="我是副标题"),
        tooltip_opts=opts.TooltipOpts(trigger="axis"),
        datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")],
    )    
    .render("line.html")
)
    

有时,列表的顺序会颠倒,这时需要我们进行转换,reverse() 函数用于反向列表中元素,语法:list.reverse(),转换后再绘图:

t1.reverse()
t2.reverse()
t3.reverse()

c = (
    Line()
    .add_xaxis(t1)
    .add_yaxis("沪深300", t2)
    .add_yaxis("中证500", t3)

    .set_global_opts(
        title_opts=opts.TitleOpts(title="沪深300VS中证500",subtitle="我是副标题"),
        tooltip_opts=opts.TooltipOpts(trigger="axis"),
        datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")],
    )    
    .render("line.html")
)

 时间和数据正确。

次例难点还在于基础,csv和list包熟悉运用,csv读取时,是每行的进行读取,需要把所得到的数据增至一个新的列表才能完整显示,不然只能显示最后一个数据

当然,我们大多数需要的是比值,而非单纯的数据,目前小编还没做好比值的图,欢迎各位大神指点!

原文地址:https://www.cnblogs.com/adam012019/p/15728256.html