利用本地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讀取時,是每行的進行讀取,需要把所得到的數據增至一個新的列表才能完整顯示,不然只能顯示最后一個數據

 

當然,我們大多數需要的是比值,而非單純的數據,目前小編還沒做好比值的圖,歡迎各位大神指點!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM