Skip to content

This guide shows how to use Plotly for creating financial charts, such as line charts, bar charts, and candlestick charts and add indicator

Notifications You must be signed in to change notification settings

mohder79/Plotly-Guide-for-financial-Chart

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 

Repository files navigation

Plotly Guide for Financial Chart

how to use plotly lib for Financial Chart

import libraries

import ccxt
from datetime import datetime
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas_ta as ta

load exchange


exchange = ccxt.binance({
    'options': {
        'adjustForTimeDifference': True,
    },

})

creat function for load data

def fetch(symbol: str, timeframe: str, limit: int):
    print(f"Fetching {symbol} new bars for {datetime.now().isoformat()}")

    bars = exchange.fetch_ohlcv(
        symbol, timeframe=timeframe, limit=limit)  # fetch ohlcv
    df = pd.DataFrame(bars[:-1], columns=['timestamp',
                      'open', 'high', 'low', 'close', 'volume'])
    df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
    df = df.set_index(pd.DatetimeIndex(df.timestamp))
    return df

set symbol for data function

BTC = fetch('BTC/USDT', '1h', 1000)

Candlestick Chart

fig = go.Figure()

fig.add_trace(go.Candlestick(x=BTC.index,
                             open=BTC['open'],
                             high=BTC['high'],
                             low=BTC['low'],
                             close=BTC['close'],
                             showlegend=False))
fig.show()

newplot (5)

change Candlestick Chart color

fig.add_trace(go.Candlestick(
    x=BTC.index,
    open=BTC['open'], high=BTC['high'],
    low=BTC['low'], close=BTC['close'],
    increasing_line_color='cyan', decreasing_line_color='gray'
))

newplot (10)

removing rangeslider

fig.update_layout(xaxis_rangeslider_visible=False)

hide Shadow

fig.update_xaxes(rangebreaks=[dict(bounds=["sat", "mon"])])

** add moving averages to data frame and plot them**

BTC['sam15'] = ta.sma(BTC.close , 15)

fig.add_trace(go.Scatter(x=BTC.index,
                         y=BTC['sam15'],
                         opacity=0.7,
                         line=dict(color='Black', width=2),
                         name='sma'))

newplot (6)

** change plot color with condition and set new dataframes**

BTC.loc[BTC['sam15'] >= BTC['close'], 'upper_sma15'] = BTC['sam15']
BTC.loc[BTC['sam15'] < BTC['close'], 'lower_sma15'] = BTC['sam15']

fig.add_trace(go.Scatter(x=BTC.index,
                         y=BTC['upper_sma15'],
                         opacity=1,
                         line=dict(color='Lime', width=4),
                         name='upper_sma'))

fig.add_trace(go.Scatter(x=BTC.index,
                         y=BTC['lower_sma15'],
                         opacity=1,
                         line=dict(color='Maroon', width=4),
                         name='lower_sma'))

newplot (7)

css color link

w3schools:

plot marker

BTC['signal'] = np.where(
    BTC['close'] > BTC['sam15'], 1, 0)

BTC['position'] = BTC['signal'].diff()

BTC['long'] = np.where(
    (BTC['position']) == 1, BTC.close, np.NAN)
BTC['short'] = np.where(
    (BTC['position']) == -1, BTC.close, np.NAN)

fig.add_trace(go.Scatter(x=BTC.index,
                         y=BTC['long'],
                         mode='markers',
                         marker=dict(color='DarkGreen', size=12,
                                     opacity=1),
                         marker_symbol=5,
                         name='long signal'))

fig.add_trace(go.Scatter(x=BTC.index,
                         y=BTC['short'],
                         mode='markers',
                         marker=dict(color='MediumVioletRed', size=12,
                                     opacity=1),
                         marker_symbol=6,
                         name='short signal'))

newplot (8)

marker Styl link

plotly:

plot volume in subplot

# first replace    fig = go.Figure() replace 
fig = make_subplots(rows=2, cols=1, shared_xaxes=True)

#add
colors = ['green' if row['open'] - row['close'] >= 0
          else 'red' for index, row in BTC.iterrows()]
fig.add_trace(go.Bar(x=BTC.index,
                     y=BTC['volume'],
                     marker_color=colors
                     ), row=2, col=1)

newplot (9)

visible plot

# add visible='legendonly'

fig.add_trace(go.Scatter(x=BTC.index,
                         y=BTC['short'],
                         mode='markers',
                         marker=dict(color='MediumVioletRed', size=12,
                                     opacity=1),
                         marker_symbol=6,
                         name='short signal',
                         visible='legendonly'))

fill between two plot lilke BBband

# { bollinger band
def SMA(data: str = 'BTC', src: str = 'close', length: int = 20):  # sma for middle band
    return data[src].rolling(window=length).mean()


def TP(data: str = 'BTC'):  # hlc/3 (typical price)
    return(data['high']+data['low']+data['close'])/3


def BOLU(data: str = "BTC", src: str = 'tp', length: int = 20, m: int = 2):  # upperband
    return SMA(data, src, 20)+((m)*data[src].rolling(window=length).std())


def BOLD(data: str = 'BTC', src: str = 'tp', length: int = 20, m: int = 2):  # lower band
    return SMA(data, 'close', 20)-((m)*data[src].rolling(window=length).std())
# ​}

# { use bollinger band functions to calculate  bbband
BTC['middelband'] = SMA(BTC, 'close', 20)
BTC['tp'] = TP(BTC)
BTC['upperband'] = BOLU(BTC, 'tp')
BTC['lowerband'] = BOLD(BTC, 'tp')
# }

fig.add_trace(go.Scatter(x=BTC.index,
                         y=BTC['upperband'],
                         fill=None,
                         mode='lines',
                         line_color='rgba(0, 0, 255, 0.5)',
                         line=dict(width=2),
                         name='upperband',
                         visible='legendonly'))

fig.add_trace(go.Scatter(x=BTC.index,
                         y=BTC['lowerband'],
                         opacity=0.3,
                         fill='tonexty',
                         line=dict(width=2),
                         name='lowerband',
                         line_color='rgba(0, 0, 255, 0.5)',
                         mode='lines', fillcolor='rgba(0, 0, 255, 0.1)',
                         visible='legendonly'))

newplot (13)

css rgba color link

w3schools:

change candlestack color with condition

# { set condition in new dataframe 
bulish = BTC[(BTC['in_sqz'] == False) & (
    BTC['close'] > BTC['middelband'])]
not_bulish = BTC[BTC.index.isin(bulish.index)].index
# }

fig.add_traces(go.Candlestick(x=billish.index,
                              open=bulish['open'], high=bulish['high'],
                              low=bulish['low'], close=bulish['close'],
                              increasing_line_color='SpringGreen',
                              decreasing_line_color='DarkGreen',
                              name='Bulish momentum(+/-)'))

newplot (14)

finaly code

# { import the libraries
import ccxt
from datetime import datetime
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas_ta as ta
# }

# { show all rows and column
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_column', None)
# }

# { load exchange
exchange = ccxt.binance({
    'options': {
        'adjustForTimeDifference': True,
    },

})
# }


# { load data as function
def fetch(symbol: str, timeframe: str, limit: int):
    print(f"Fetching {symbol} new bars for {datetime.now().isoformat()}")

    bars = exchange.fetch_ohlcv(
        symbol, timeframe=timeframe, limit=limit)  # fetch ohlcv
    df = pd.DataFrame(bars[:-1], columns=['timestamp',
                      'open', 'high', 'low', 'close', 'volume'])
    df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
    df = df.set_index(pd.DatetimeIndex(df.timestamp))
    return df
# }


# { bollinger band
def SMA(data: str = 'BTC', src: str = 'close', length: int = 20):  # sma for middle band
    return data[src].rolling(window=length).mean()


def TP(data: str = 'BTC'):  # hlc/3 (typical price)
    return(data['high']+data['low']+data['close'])/3


def BOLU(data: str = "BTC", src: str = 'tp', length: int = 20, m: int = 2):  # upperband
    return SMA(data, src, 20)+((m)*data[src].rolling(window=length).std())


def BOLD(data: str = 'BTC', src: str = 'tp', length: int = 20, m: int = 2):  # lower band
    return SMA(data, 'close', 20)-((m)*data[src].rolling(window=length).std())
# ​}


# { set the symbol for data function
BTC = fetch('BTC/USDT', '1h', 1000)
# }


# { use panda ta lib for calculate sma
BTC['sam15'] = ta.sma(BTC.close, 15)
# }


# { creat tow data frame for change sma color
BTC.loc[BTC['sam15'] >= BTC['close'], 'upper_sma15'] = BTC['sam15']
BTC.loc[BTC['sam15'] < BTC['close'], 'lower_sma15'] = BTC['sam15']
# }


# { use bollinger band functions to calculate  bbband
BTC['middelband'] = SMA(BTC, 'close', 20)
BTC['tp'] = TP(BTC)
BTC['upperband'] = BOLU(BTC, 'tp')
BTC['lowerband'] = BOLD(BTC, 'tp')
# }


# { find cross for plot marker
BTC['signal'] = np.where(
    BTC['close'] > BTC['sam15'], 1, 0)

BTC['position'] = BTC['signal'].diff()

BTC['long'] = np.where(
    (BTC['position']) == 1, BTC.close, np.NAN)
BTC['short'] = np.where(
    (BTC['position']) == -1, BTC.close, np.NAN)
# }


# { set condition in new dataframe
bulish = BTC[(BTC['close'] > BTC['middelband'])]
not_bulish = BTC[BTC.index.isin(bulish.index)].index
# }


# {  plot the data
fig = make_subplots(rows=2, cols=1, shared_xaxes=True)
#fig = go.Figure()

fig.add_trace(go.Candlestick(x=BTC.index,
                             open=BTC['open'],
                             high=BTC['high'],
                             low=BTC['low'],
                             close=BTC['close'],
                             showlegend=False))

fig.add_traces(go.Candlestick(x=bulish.index,
                              open=bulish['open'], high=bulish['high'],
                              low=bulish['low'], close=bulish['close'],
                              increasing_line_color='SpringGreen',
                              decreasing_line_color='DarkGreen',
                              name='Bulish momentum(+/-)'))

fig.add_trace(go.Scatter(x=BTC.index,
                         y=BTC['upper_sma15'],
                         opacity=1,
                         line=dict(color='Lime', width=4),
                         name='upper_sma'))

fig.add_trace(go.Scatter(x=BTC.index,
                         y=BTC['lower_sma15'],
                         opacity=1,
                         line=dict(color='Maroon', width=4),
                         name='lower_sma'))


fig.add_trace(go.Scatter(x=BTC.index,
                         y=BTC['long'],
                         mode='markers',
                         marker=dict(color='DarkGreen', size=12,
                                     opacity=1),
                         marker_symbol=5,
                         name='long signal'))

fig.add_trace(go.Scatter(x=BTC.index,
                         y=BTC['short'],
                         mode='markers',
                         marker=dict(color='MediumVioletRed', size=12,
                                     opacity=1),
                         marker_symbol=6,
                         name='short signal',
                         visible='legendonly'))

colors = ['green' if row['open'] - row['close'] >= 0
          else 'red' for index, row in BTC.iterrows()]
fig.add_trace(go.Bar(x=BTC.index,
                     y=BTC['volume'],
                     marker_color=colors
                     ), row=2, col=1)

fig.add_trace(go.Scatter(x=BTC.index,
                         y=BTC['middelband'],
                         opacity=1,
                         line=dict(color='orange', width=2),
                         name='middelband'))

fig.add_trace(go.Scatter(x=BTC.index,
                         y=BTC['upperband'],
                         fill=None,
                         mode='lines',
                         line_color='rgba(0, 0, 255, 0.5)',
                         line=dict(width=2),
                         name='upperband'))

fig.add_trace(go.Scatter(x=BTC.index,
                         y=BTC['lowerband'],
                         opacity=0.3,
                         fill='tonexty',
                         line=dict(width=2),
                         name='lowerband',
                         line_color='rgba(0, 0, 255, 0.5)',
                         mode='lines', fillcolor='rgba(0, 0, 255, 0.1)'))

fig.show()
# }

newplot (15)

About

This guide shows how to use Plotly for creating financial charts, such as line charts, bar charts, and candlestick charts and add indicator

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published