plotly的移动平均线

use*_*528 3 python plotly

所以我正在尝试通过 Plotly 库编写烛台图表,并尝试在我的代码中添加移动平均线。我搜索了许多代码以在我的代码中实现 MA,但我无法弄清楚如何在同一烛台图表中添加 MA 线。

等待有人帮我解决这个问题。

import shrimpy
import pandas_datareader as web
import pandas as pd
import datetime
import plotly.express as px 
import numpy as np
import plotly.graph_objects as go

# sign up for the Shrimpy Developer APIs for your free API keys
public_key = ''
secret_key = ''
# collect the historical candlestick data
client = shrimpy.ShrimpyApiClient(public_key, secret_key)
candles = client.get_candles(
    'binance', # exchange
    'BNB',     # base_trading_symbol
    'BTC',     # quote_trading_symbol
    '1d'       # interval
)
dates = []
open_data = []
high_data = []
low_data = []
close_data = []
# format the data to match the plotting library
for candle in candles:
    dates.append(candle['time'])
    open_data.append(candle['open'])
    high_data.append(candle['high'])
    low_data.append(candle['low'])
    close_data.append(candle['close'])

# plot the candlesticks
fig = go.Figure(data=[go.Candlestick(x=dates,
                       open=open_data, high=high_data,
                       low=low_data, close=close_data)])

fig.show()
Run Code Online (Sandbox Code Playgroud)

小智 16

pandas使用rolling函数来简化您的代码并使用函数来计算移动平均线。

import shrimpy
import pandas as pd
import numpy as np
import plotly.graph_objects as go

# sign up for the Shrimpy Developer APIs for your free API keys
public_key = ''
secret_key = ''
# collect the historical candlestick data
client = shrimpy.ShrimpyApiClient(public_key, secret_key)
candles = client.get_candles(
    'binance', # exchange
    'BNB',     # base_trading_symbol
    'BTC',     # quote_trading_symbol
    '1d'       # interval
)

df = pd.DataFrame(candles)

df['MA5'] = df.close.rolling(5).mean()
df['MA20'] = df.close.rolling(20).mean()


# plot the candlesticks
fig = go.Figure(data=[go.Candlestick(x=df.time,
                                     open=df.open, 
                                     high=df.high,
                                     low=df.low,
                                     close=df.close), 
                      go.Scatter(x=df.time, y=df.MA5, line=dict(color='orange', width=1)),
                      go.Scatter(x=df.time, y=df.MA20, line=dict(color='green', width=1))])
Run Code Online (Sandbox Code Playgroud)

阴谋: 在此处输入图片说明

  • 伙计,你救了我的命。我现在就想嫁给你,哈哈。非常感谢您的帮助,愿上帝保佑您。 (4认同)