最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Python畫一張完整的K線圖的方法教程

 更新時間:2025年04月10日 09:42:07   作者:花小姐的春天  
Pyecharts?是?Python?里的一個強大可視化庫,基于百度?Echarts,支持各種圖表:柱狀圖、折線圖、餅圖、K?線圖等等,本文就給大家介紹了Python如何使用Pyecharts畫一個漂亮的K線圖,感興趣的小伙伴跟著小編一起來看看吧

最近炒股的朋友們老問我:“花姐,你能不能教我用 Python 畫個 K 線圖,研究研究趨勢?”

聽到這個問題,我差點沒一口奶茶噴出來。

“用 Python 畫 K 線?當(dāng)然能!而且還得是高大上的動態(tài)交互圖!”

說實話,一開始我也覺得畫 K 線挺麻煩的,要處理數(shù)據(jù)、搞清楚指標(biāo)、還得美觀……結(jié)果后來發(fā)現(xiàn),Pyecharts 這個庫真的太香了!

今天咱們就一起來畫出一個漂亮的 K 線圖,均線、成交量 指標(biāo)都加上,讓你在 Python 里玩轉(zhuǎn)金融數(shù)據(jù)!

1. 什么是 Pyecharts?

Pyecharts 是 Python 里的一個強大可視化庫,基于百度 Echarts,支持各種圖表:柱狀圖、折線圖、餅圖、K 線圖等等。相比 Excel 或 Matplotlib,Pyecharts 生成的圖表更美觀,而且支持交互!

1.1 安裝 Pyecharts?

用 pip 輕松搞定:

pip install pyecharts

裝好以后,我們先來畫個簡單的折線圖,看看效果。

1.2 畫個簡單的折線圖

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

# 創(chuàng)建折線圖對象
line = Line()

# 添加數(shù)據(jù)
line.add_xaxis(["周一", "周二", "周三", "周四", "周五"])
line.add_yaxis("股票價格", [10, 12, 15, 13, 17])

# 設(shè)置標(biāo)題
line.set_global_opts(title_opts=opts.TitleOpts(title="股票價格變化"))

# 渲染成 HTML
line.render("line_chart.html")

運行后,會在本地生成一個 HTML 頁面,你會看到一條簡單的折線,鼠標(biāo)移動上去還會有交互效果!

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)建舞臺)

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("股票價格", [10, 12, 15, 13, 17])
  •  數(shù)據(jù)綁定
  • X軸 → 橫坐標(biāo)標(biāo)簽(星期)
  •  Y軸 → 股價波動數(shù)值
  • 擴展性:可連續(xù)添加多個add_yaxis()繪制多指標(biāo)對比

1.3.4 樣式配置(美化定型)

.set_global_opts(title_opts=opts.TitleOpts(title="股票價格變化"))
  • 核心配置項
  • title_opts:主/副標(biāo)題設(shè)置
  • tooltip_opts:懸浮提示框樣式
  • axis_opts:坐標(biāo)軸標(biāo)簽格式
  • 可擴展配置:支持50+種樣式參數(shù)調(diào)整

1.3.5 輸出成果(生成文件)

.render("line_chart.html")
  • 輸出特性
  • 生成完整HTML5文件
  • 自帶交互功能(縮放/懸浮提示/下載)
  • 跨平臺兼容(瀏覽器直接打開)

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 = [
    [開盤價, 收盤價, 最低價, 最高價],
    [開盤價, 收盤價, 最低價, 最高價],
    ...
]

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 # 啟用自動縮放
        ),
        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 添加均線

# 計算移動平均線 (處理前4個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},  # 藍色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ù)點標(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 # 啟用自動縮放
        ),
        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
            )
        ]
    )

# 計算移動平均線 (處理前4個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},  # 藍色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ù)點標(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 線,有點意思!

一頓操作下來,我們終于用 pyecharts 畫出了一個完整的 K 線圖,包含了所有關(guān)鍵指標(biāo)!

如果你是個數(shù)據(jù)分析師或者炒股愛好者,這樣的 K 線圖絕對是你的利器!

以上就是使用Python畫一張完整的K線圖的方法教程的詳細內(nèi)容,更多關(guān)于Python畫K線圖的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論

翁牛特旗| 茌平县| 绥德县| 乐都县| 信丰县| 保山市| 垣曲县| 随州市| 星子县| 岳阳县| 科尔| 越西县| 布尔津县| 远安县| 肥东县| 鄂托克前旗| 铜川市| 遵化市| 阜宁县| 裕民县| 边坝县| 定结县| 象州县| 望江县| 汽车| 宜都市| 高台县| 阿巴嘎旗| 弥勒县| 车致| 石城县| 保康县| 林口县| 钟祥市| 青神县| 剑阁县| 冕宁县| 哈巴河县| 揭东县| 富顺县| 龙江县|