趋势(五)利用python绘制烛台图

烛台图(Candlestick)简介

image-20241125161815527

烛台图也叫K线图,通常用作交易工具,用来显示和分析证券、衍生工具、外汇货币、股票、债券等商品随着时间的价格变动。

绘制基本烛台图

由于不是专业的金融从业者,这里只是简单的进行分享,更多用法可参考baostock 数据平台mplfinance文档以及Candlestick charts in Python - Plotly

  1. 获取股票数据

    # 获取股票数据
    import baostock as bs
    import pandas as pd
    
    lg = bs.login()
    
    rs = bs.query_history_k_data_plus("sh.600000",
        "date,open,high,low,close",
        start_date='2022-01-01', end_date='2022-03-31',
        frequency="d", adjustflag="2")
    
    data_list = []
    while (rs.error_code == '0') & rs.next():
        data_list.append(rs.get_row_data())
    result = pd.DataFrame(data_list, columns=rs.fields)
    
    # 将date转为索引
    result['date'] = pd.to_datetime(result['date'])
    result.set_index('date', inplace=True)
    
    # 更换字段类型
    for col in ['open', 'high', 'low', 'close']:
        result[col] = result[col].astype(float)
    
    bs.logout()
    
  2. 基于mplfinance

    import mplfinance as mpf
    
    moving_averages = [5,10,15] # 需要绘制的均线
    
    mpf.plot(result,
             type='candle',
             mav=moving_averages)
    

    2

  3. 基于plotly

    import plotly.graph_objects as go
    
    result['moving3'] = result['close'].rolling(3).mean()
    result['moving8'] = result['close'].rolling(8).mean()
    
    fig = go.Figure(data=[go.Candlestick(
                    x = result.index, # 日期索引
                    open = result['open'],
                    high = result['high'],
                    low = result['low'],
                    close = result['close'],
        
                    # bar颜色
                    increasing_line_color = 'purple',
                    decreasing_line_color = 'orange',
                    showlegend=False
                    ),
                          
                          # 均线
                          go.Scatter(x=result['moving3'].index,
                                         y=result['moving3'],
                                         line=dict(color='gray',
                                                   width=1,
                                                   shape='spline'), # smooth the line
                                         name='MA3'),
                          
                          go.Scatter(x=result['moving8'].index,
                                     y=result['moving8'],
                                     line=dict(color='black',
                                               width=1,
                                               shape='spline'), # smooth the line
                                     name='MA8')
             ])
    
    # 屏蔽默认滑块
    fig.update_layout(xaxis_rangeslider_visible=False,
                     autosize=False,
                     width=700,
                     height=500,
                     legend=dict(
                            x=0.82, 
                            y=0.98,
                            font=dict(size=12)
        ))
    

    3

总结

以上基于baostock获取股票数据,并利用mplfinance和plotly快速绘制烛台图。

共勉~

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐