Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moving average for plotly

Tags:

python

plotly

so I'm trying to code candlesticks chart via Plotly library and I'm trying to add moving average lines in my code. I search for many codes to implement MA to my code, but I couldn't figure out how to add MA lines at the same candlesticks chart.

Waiting for someone to help me with this.

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()
like image 737
user2508528 Avatar asked Dec 04 '22 17:12

user2508528


1 Answers

I simplify your code with pandas and using rolling function to calculate the moving averages.

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))])

Plot: enter image description here

like image 79
9mat Avatar answered Dec 28 '22 09:12

9mat