使用Python畫一張完整的K線圖的方法教程
最近炒股的朋友們老問我:“花姐,你能不能教我用 Python 畫個(gè) K 線圖,研究研究趨勢?”
聽到這個(gè)問題,我差點(diǎn)沒一口奶茶噴出來。
“用 Python 畫 K 線?當(dāng)然能!而且還得是高大上的動(dòng)態(tài)交互圖!”
說實(shí)話,一開始我也覺得畫 K 線挺麻煩的,要處理數(shù)據(jù)、搞清楚指標(biāo)、還得美觀……結(jié)果后來發(fā)現(xiàn),Pyecharts
這個(gè)庫真的太香了!
今天咱們就一起來畫出一個(gè)漂亮的 K 線圖,均線、成交量 指標(biāo)都加上,讓你在 Python 里玩轉(zhuǎn)金融數(shù)據(jù)!
1. 什么是 Pyecharts?
Pyecharts
是 Python 里的一個(gè)強(qiáng)大可視化庫,基于百度 Echarts
,支持各種圖表:柱狀圖、折線圖、餅圖、K 線圖等等。相比 Excel 或 Matplotlib,Pyecharts 生成的圖表更美觀,而且支持交互!
1.1 安裝 Pyecharts?
用 pip 輕松搞定:
pip install pyecharts
裝好以后,我們先來畫個(gè)簡單的折線圖,看看效果。
1.2 畫個(gè)簡單的折線圖
from pyecharts.charts import Line from pyecharts import options as opts # 創(chuàng)建折線圖對象 line = Line() # 添加數(shù)據(jù) line.add_xaxis(["周一", "周二", "周三", "周四", "周五"]) line.add_yaxis("股票價(jià)格", [10, 12, 15, 13, 17]) # 設(shè)置標(biāo)題 line.set_global_opts(title_opts=opts.TitleOpts(title="股票價(jià)格變化")) # 渲染成 HTML line.render("line_chart.html")
運(yùn)行后,會(huì)在本地生成一個(gè) HTML 頁面,你會(huì)看到一條簡單的折線,鼠標(biāo)移動(dòng)上去還會(huì)有交互效果!
1.3 關(guān)鍵步驟介紹
1.3.1 模塊導(dǎo)入(基石搭建)
from pyecharts.charts import Line from pyecharts import options as opts
• 核心作用:加載可視化工具包
• Line
:折線圖繪制核心類
• opts
:樣式配置工具箱(控制標(biāo)題/坐標(biāo)軸/顏色等)
1.3.2 畫布初始化(創(chuàng)建舞臺(tái))
line = Line()
• 本質(zhì):創(chuàng)建空白繪圖區(qū)域
• 類比:準(zhǔn)備畫布和畫筆,準(zhǔn)備繪制折線圖
1.3.3 數(shù)據(jù)注入(填充內(nèi)容)
# X軸:維度數(shù)據(jù)(通常為分類數(shù)據(jù)) .add_xaxis(["周一", "周二", "周三", "周四", "周五"]) # Y軸:指標(biāo)數(shù)據(jù)(數(shù)值序列) .add_yaxis("股票價(jià)格", [10, 12, 15, 13, 17])
- 數(shù)據(jù)綁定:
- X軸 → 橫坐標(biāo)標(biāo)簽(星期)
- Y軸 → 股價(jià)波動(dòng)數(shù)值
- 擴(kuò)展性:可連續(xù)添加多個(gè)
add_yaxis()
繪制多指標(biāo)對比
1.3.4 樣式配置(美化定型)
.set_global_opts(title_opts=opts.TitleOpts(title="股票價(jià)格變化"))
- 核心配置項(xiàng):
title_opts
:主/副標(biāo)題設(shè)置tooltip_opts
:懸浮提示框樣式axis_opts
:坐標(biāo)軸標(biāo)簽格式- 可擴(kuò)展配置:支持50+種樣式參數(shù)調(diào)整
1.3.5 輸出成果(生成文件)
.render("line_chart.html")
- 輸出特性:
- 生成完整HTML5文件
- 自帶交互功能(縮放/懸浮提示/下載)
- 跨平臺(tái)兼容(瀏覽器直接打開)
2. 畫一張完整的 K 線圖!
知道了基礎(chǔ)用法,接下來,我們用 pyecharts
畫 K 線圖,并加上均線、成交量、MACD 指標(biāo),讓它更專業(yè)!
2.1 獲取股票數(shù)據(jù)
這里我們用AKShare庫來獲取股票日線行情數(shù)據(jù),把數(shù)據(jù)轉(zhuǎn)存成csv文件,這樣方便我們測試。
import akshare as ak df = ak.stock_zh_a_hist(symbol="000001", period="daily", start_date="20230101", end_date="20250101" ,adjust="qfq") df.to_csv("kdata.csv",index=False)
這是測試用的csv數(shù)據(jù)
2.2 準(zhǔn)備數(shù)據(jù)
K 線圖的數(shù)據(jù)格式要求:
k_data = [ [開盤價(jià), 收盤價(jià), 最低價(jià), 最高價(jià)], [開盤價(jià), 收盤價(jià), 最低價(jià), 最高價(jià)], ... ]
2.3 讀取csv數(shù)據(jù)并做處理
import pandas as pd # 讀取數(shù)據(jù)并排序 df = pd.read_csv("kdata.csv", parse_dates=["日期"]) # 數(shù)據(jù)預(yù)處理 df['日期'] = pd.to_datetime(df['日期']).dt.strftime('%Y-%m-%d') # 格式化日期 df = df.sort_values("日期") # 安裝日期排序 data = df[["開盤", "收盤", "最低", "最高"]].values.tolist() # 生成K線數(shù)據(jù)序列 print(data)
2.4 畫蠟燭圖(K 線)
from pyecharts.charts import Kline from pyecharts import options as opts # 創(chuàng)建K線圖 kline = Kline() kline.add_xaxis(df['日期'].tolist()) # X軸日期數(shù)據(jù) kline.add_yaxis( series_name="k線", # y軸名稱 y_axis=data, # K線數(shù)據(jù)序列 itemstyle_opts=opts.ItemStyleOpts( color="#ef232a", # 上漲顏色(紅色) color0="#14b143", # 下跌顏色(綠色) border_color="#000", # 統(tǒng)一黑色描邊 border_color0="#000" ) ) kline.set_global_opts( title_opts=opts.TitleOpts(title="股票K線走勢圖", subtitle=df['股票代碼'][0]), xaxis_opts=opts.AxisOpts( type_='category', axislabel_opts=opts.LabelOpts(rotate=45), # 日期標(biāo)簽旋轉(zhuǎn)45度 splitline_opts=opts.SplitLineOpts(is_show=True) # 顯示網(wǎng)格線 ), yaxis_opts=opts.AxisOpts( splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ),is_scale=True # 啟用自動(dòng)縮放 ), datazoom_opts=[ # 添加數(shù)據(jù)縮放控件 opts.DataZoomOpts( is_show=True, type_="inside", xaxis_index=[0], range_start=50, range_end=100 ), opts.DataZoomOpts( is_show=True, xaxis_index=[0], type_="slider", pos_top="90%", range_start=50, range_end=100 ) ] ) # 生成HTML文件 kline.render("stock_kline.html")
效果展示:
2.5 添加均線
# 計(jì)算移動(dòng)平均線 (處理前4個(gè)NaN值) ma_periods = [5, 10, 20] for period in ma_periods: df[f'MA{period}'] = df['收盤'].rolling(window=period).mean().bfill() from pyecharts.charts import Line # 創(chuàng)建均線疊加圖 line = Line() # 添加各周期均線 ma_colors = { 5: {"color": "#FF0000", "width": 2}, # 紅色5日均線 10: {"color": "#0000FF", "width": 2}, # 藍(lán)色10日均線 20: {"color": "#00FF00", "width": 2} # 綠色20日均線 } for period in ma_periods: line.add_xaxis(df['日期'].tolist()) line.add_yaxis( series_name=f"MA{period}", y_axis=df[f'MA{period}'].tolist(), symbol="circle", symbol_size=0, linestyle_opts=opts.LineStyleOpts( color=ma_colors[period]["color"], width=ma_colors[period]["width"] ), label_opts=opts.LabelOpts(is_show=False), # 關(guān)閉數(shù)據(jù)點(diǎn)標(biāo)簽 is_smooth=True, # 平滑曲線 z_level=1 # 確保均線顯示在K線上方 ) # 合并圖表 overlap_kline = kline.overlap(line)
2.6 加入成交量柱狀圖
# 生成漲跌顏色列表(與K線顏色同步) df['color'] = df.apply(lambda x: "#ef232a" if x['收盤'] >= x['開盤'] else "#14b143", axis=1) # 創(chuàng)建成交量柱形圖 from pyecharts.charts import Bar from pyecharts.commons.utils import JsCode vol_bar = ( Bar() .add_xaxis(df['日期'].tolist()) .add_yaxis( series_name="", y_axis=df['成交量'].tolist(), itemstyle_opts=opts.ItemStyleOpts( color=JsCode(''' function(params) { var colors = [%s]; return params.dataIndex < colors.length ? colors[params.dataIndex] : '#14b143'; } ''' % ("'" + "','".join(df['color'].tolist()) + "'")) # 生成正確數(shù)組格式 ), yaxis_index=1, bar_width='60%', label_opts=opts.LabelOpts(is_show=False) ) .set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", axislabel_opts=opts.LabelOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False) ), yaxis_opts=opts.AxisOpts( position="right", axislabel_opts=opts.LabelOpts(formatter=JsCode( "function(value){return value > 10000 ? (value/10000).toFixed(1)+'萬' : value;}")) ) ) ) # 組合圖表布局 from pyecharts.charts import Grid grid = ( Grid(init_opts=opts.InitOpts(width="1200px", height="800px")) .add( overlap_kline, # 使用已合并的K線均線圖 grid_opts=opts.GridOpts( pos_left="10%", pos_right="8%", height="65%", # 主圖高度65% pos_top="10%" ) ) .add( vol_bar, grid_opts=opts.GridOpts( pos_left="10%", pos_right="8%", height="15%", # 成交量圖高度15% pos_top="80%" # 從80%位置開始 ) ) ) # 修改渲染對象為grid grid.render("stock_kline.html")
2.8 美化+完整代碼
import pandas as pd from pyecharts.charts import Kline from pyecharts import options as opts # 讀取數(shù)據(jù)并排序 df = pd.read_csv("kdata.csv", parse_dates=["日期"]) # 數(shù)據(jù)預(yù)處理 df['日期'] = pd.to_datetime(df['日期']).dt.strftime('%Y-%m-%d') # 格式化日期 df = df.sort_values("日期") # 安裝日期排序 data = df[["開盤", "收盤", "最低", "最高"]].values.tolist() # 生成K線數(shù)據(jù)序列 # 創(chuàng)建K線圖 kline = Kline() kline.add_xaxis(df['日期'].tolist()) # X軸日期數(shù)據(jù) kline.add_yaxis( series_name="k線", # y軸名稱 y_axis=data, # K線數(shù)據(jù)序列 itemstyle_opts=opts.ItemStyleOpts( color="#ef232a", # 上漲顏色(紅色) color0="#14b143", # 下跌顏色(綠色) border_color="#000", # 統(tǒng)一黑色描邊 border_color0="#000" ) ) kline.set_global_opts( title_opts=opts.TitleOpts(title="股票K線走勢圖", subtitle=df['股票代碼'][0]), xaxis_opts=opts.AxisOpts( type_='category', axislabel_opts=opts.LabelOpts(rotate=45), # 日期標(biāo)簽旋轉(zhuǎn)45度 splitline_opts=opts.SplitLineOpts(is_show=True) # 顯示網(wǎng)格線 ), yaxis_opts=opts.AxisOpts( splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ),is_scale=True # 啟用自動(dòng)縮放 ), datazoom_opts=[ # 添加數(shù)據(jù)縮放控件 opts.DataZoomOpts( is_show=True, type_="inside", xaxis_index=[0], range_start=50, range_end=100 ), opts.DataZoomOpts( is_show=True, xaxis_index=[0], type_="slider", pos_top="90%", range_start=50, range_end=100 ) ] ) # 計(jì)算移動(dòng)平均線 (處理前4個(gè)NaN值) ma_periods = [5, 10, 20] for period in ma_periods: df[f'MA{period}'] = df['收盤'].rolling(window=period).mean().bfill() from pyecharts.charts import Line # 創(chuàng)建均線疊加圖 line = Line() # 添加各周期均線 ma_colors = { 5: {"color": "#FF0000", "width": 2}, # 紅色5日均線 10: {"color": "#0000FF", "width": 2}, # 藍(lán)色10日均線 20: {"color": "#00FF00", "width": 2} # 綠色20日均線 } for period in ma_periods: line.add_xaxis(df['日期'].tolist()) line.add_yaxis( series_name=f"MA{period}", y_axis=df[f'MA{period}'].tolist(), symbol="circle", symbol_size=0, linestyle_opts=opts.LineStyleOpts( color=ma_colors[period]["color"], width=ma_colors[period]["width"] ), label_opts=opts.LabelOpts(is_show=False), # 關(guān)閉數(shù)據(jù)點(diǎn)標(biāo)簽 is_smooth=True, # 平滑曲線 z_level=1 # 確保均線顯示在K線上方 ) # 合并圖表 overlap_kline = kline.overlap(line) # 生成漲跌顏色列表(與K線顏色同步) df['color'] = df.apply(lambda x: "#ef232a" if x['收盤'] >= x['開盤'] else "#14b143", axis=1) # 創(chuàng)建成交量柱形圖 from pyecharts.charts import Bar from pyecharts.commons.utils import JsCode vol_bar = ( Bar() .add_xaxis(df['日期'].tolist()) .add_yaxis( series_name="", y_axis=df['成交量'].tolist(), itemstyle_opts=opts.ItemStyleOpts( color=JsCode(''' function(params) { var colors = [%s]; return params.dataIndex < colors.length ? colors[params.dataIndex] : '#14b143'; } ''' % ("'" + "','".join(df['color'].tolist()) + "'")) # 生成正確數(shù)組格式 ), yaxis_index=1, bar_width='60%', label_opts=opts.LabelOpts(is_show=False) ) .set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", axislabel_opts=opts.LabelOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False) ), yaxis_opts=opts.AxisOpts( position="right", axislabel_opts=opts.LabelOpts(formatter=JsCode( "function(value){return value > 10000 ? (value/10000).toFixed(1)+'萬' : value;}")) ) ) ) # 組合圖表布局 from pyecharts.charts import Grid grid = ( Grid(init_opts=opts.InitOpts(width="1200px", height="800px")) .add( overlap_kline, # 使用已合并的K線均線圖 grid_opts=opts.GridOpts( pos_left="10%", pos_right="8%", height="65%", # 主圖高度65% pos_top="10%" ) ) .add( vol_bar, grid_opts=opts.GridOpts( pos_left="10%", pos_right="8%", height="15%", # 成交量圖高度15% pos_top="80%" # 從80%位置開始 ) ) ) # 修改渲染對象為grid grid.render("stock_kline.html")
3. 結(jié)尾——這 K 線,有點(diǎn)意思!
一頓操作下來,我們終于用 pyecharts 畫出了一個(gè)完整的 K 線圖,包含了所有關(guān)鍵指標(biāo)!
如果你是個(gè)數(shù)據(jù)分析師或者炒股愛好者,這樣的 K 線圖絕對是你的利器!
以上就是使用Python畫一張完整的K線圖的方法教程的詳細(xì)內(nèi)容,更多關(guān)于Python畫K線圖的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python 使用dict實(shí)現(xiàn)switch的操作
這篇文章主要介紹了Python 使用dict實(shí)現(xiàn)switch的操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04Python使用Scrapy保存控制臺(tái)信息到文本解析
這篇文章主要介紹了Python使用Scrapy保存控制臺(tái)信息到文本解析,具有一定借鑒價(jià)值,需要的朋友可以參考下2017-12-12Python計(jì)算機(jī)視覺SIFT尺度不變的圖像特征變換
這篇文章主要為大家介紹了Python計(jì)算機(jī)視覺SIFT尺度不變的圖像特征變換,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05