情节的移动平均线

时间:2019-12-22 07:25:23

标签: 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()

1 个答案:

答案 0 :(得分:1)

我使用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))])

图: enter image description here