如何将多条移动平均线动态添加到 Plotly Candlestick

Posted

技术标签:

【中文标题】如何将多条移动平均线动态添加到 Plotly Candlestick【英文标题】:How to add multiple Moving Average lines DYNAMICALLY to Plotly Candlestick 【发布时间】:2021-09-25 18:35:53 【问题描述】:

我编写了这个函数来使用plotly 绘制烛台。我想添加使用不同颜色动态添加N不同行的功能。现在它只添加了 1 行。我可以硬编码另一个Scatter,但不能动态编码。

代码如下:

def plot_candlesticks(df, names = ('DATE','OPEN','CLOSE','LOW','HIGH'), mv = 44):
        '''
        Plot a candlestick on a given dataframe
        args:
            df: DataFrame
            names: Tuple of column names showing ('DATE','OPEN','HIGH','LOW','OPEN','CLOSE')
            mv: Moving Average
        '''
        stocks = df.copy()
        Date, Open, Close, Low, High = names
        stocks.sort_index(ascending=False, inplace = True)
        stocks[f'str(mv)-SMA'] = stocks[Close].rolling(mv, min_periods = 1).mean()

        candle = go.Figure(data = [go.Candlestick(x = stocks[Date], name = 'Trade',
                                                       open = stocks[Open], 
                                                       high = stocks[High], 
                                                       low = stocks[Low], 
                                                       close = stocks[Close]),

                                  go.Scatter(name=f'str(mv) MA',x=stocks[Date], y=stocks[f'str(mv)-SMA'], 
                                             line=dict(color='blue', width=1)),])

        candle.update_xaxes(
            title_text = 'Date',
            rangeslider_visible = True,
            rangeselector = dict(
                buttons = list([
                    dict(count = 1, label = '1M', step = 'month', stepmode = 'backward'),
                    dict(count = 6, label = '6M', step = 'month', stepmode = 'backward'),
                    dict(count = 1, label = 'YTD', step = 'year', stepmode = 'todate'),
                    dict(count = 1, label = '1Y', step = 'year', stepmode = 'backward'),
                    dict(step = 'all')])))

        candle.update_layout(autosize = True,
                             title = 'text': all_stocks[stocks['SYMBOL'][0]],'y':0.97,'x':0.5,
                                      'xanchor': 'center','yanchor': 'top',
                             margin=dict(l=30,r=30,b=30,t=30,pad=2),
                             paper_bgcolor="lightsteelblue",)

        candle.update_yaxes(title_text = 'Close Price', tickprefix = u"\u20B9" ) # Rupee symbol
        candle.show()

【问题讨论】:

【参考方案1】:

我已经修改了代码,因为您的问题的目的是自动将多个移动平均线添加到烛台图,并将基值作为函数参数传递给列表。该点是通过 add_trace() 到烛台图实现的。

import plotly.graph_objects as go
import pandas as pd
import yfinance as yf

data = yf.download("AAPL", start="2021-01-01", end="2021-03-01")
data = data.iloc[:,0:4]
data.reset_index(inplace=True)

def plot_candlesticks(df, names = ('Date','Open','High','Low','Close'), mv = [5,25,75]):
        '''
        Plot a candlestick on a given dataframe
        args:
            df: DataFrame
            names: Tuple of column names showing ('DATE','OPEN','HIGH','LOW','OPEN','CLOSE')
            mv: Moving Average
        '''
        stocks = df.copy()
        Date, Open, Close, Low, High = names
        stocks.sort_index(ascending=False, inplace = True)
        colors = ['red', 'blue', 'yellow']

        candle = go.Figure(data = [go.Candlestick(x = stocks[Date], name = 'Trade',
                                                       open = stocks[Open], 
                                                       high = stocks[High], 
                                                       low = stocks[Low], 
                                                       close = stocks[Close]),])
        for i in range(len(mv)):
            stocks[f'str(mv[i])-SMA'] = stocks[Close].rolling(mv[i], min_periods = 1).mean()
            candle.add_trace(go.Scatter(name=f'str(mv[i]) MA',x=stocks[Date], y=stocks[f'str(mv[i])-SMA'], 
                                             line=dict(color=colors[i], width=2)))

        candle.update_xaxes(
            title_text = 'Date',
            rangeslider_visible = True,
            rangeselector = dict(
                buttons = list([
                    dict(count = 1, label = '1M', step = 'month', stepmode = 'backward'),
                    dict(count = 6, label = '6M', step = 'month', stepmode = 'backward'),
                    dict(count = 1, label = 'YTD', step = 'year', stepmode = 'todate'),
                    dict(count = 1, label = '1Y', step = 'year', stepmode = 'backward'),
                    dict(step = 'all')])))

        candle.update_layout(autosize = True,
                             title = 'text': "all_stocks[stocks['SYMBOL'][0]]",'y':0.97,'x':0.5,
                                      'xanchor': 'center','yanchor': 'top',
                             margin=dict(l=30,r=30,b=30,t=30,pad=2),
                             paper_bgcolor="lightsteelblue",)

        candle.update_yaxes(title_text = 'Close Price', tickprefix = u"\u20B9" ) # Rupee symbol
        candle.show()

plot_candlesticks(data)

【讨论】:

非常感谢您的帮助。这确实是我想要的

以上是关于如何将多条移动平均线动态添加到 Plotly Candlestick的主要内容,如果未能解决你的问题,请参考以下文章

Plotly:如何在 Plotly Express 中注释多行?

如何根据不同的dataFrame部分绘制(plotly.express)多条线

Plotly:如何使用 DASH 回调将多项式拟合线添加到 plotly go.scatter 图?

如何使用 plotly express(XYXY 格式数据)在同一图表上绘制多条线?

将垂直线段添加到动态条形图 ggplot-plotly

Plotly:如何为标准偏差制作具有多条线和阴影区域的图形?