Ivan Mishalkin
Ivan Mishalkin

Reputation: 1108

Add custom legend (markers color) to plotly python

I try to visualize trading algo with plotly. I have two dataframes: one with close prices and another one with transactions, that my algo performs. Green dots should be for buy action, red for sell. What I also want is to have a menu to be able to choose what stock to analyse. For now everything works by drawing actions over the close price.

The question is: how to add a legend about dot color (green for buy, red for sell) in a certain position?

from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.graph_objs as go
import pandas as pd
init_notebook_mode(connected=True)

feed = pd.DataFrame({'AAPL': [100, 120, 130, 120, 150],
                     'MSFT': [80, 70, 90, 100, 99]}, index = pd.date_range('2018-01-01', '2018-01-05'))

trans = pd.DataFrame({'Symbol': ['AAPL', 'AAPL', 'MSFT', 'MSFT'],
                        'Amount': [2, 1, 3, 1],
                        'Action': ['buy', 'sell', 'buy', 'sell'],
                        'Price': [120, 150, 70, 100],
                        'Date': [pd.to_datetime(i) for i in ['2018-01-02', '2018-01-05', '2018-01-02', '2018-01-04']]
                       })

data = []
all_but = dict(label = 'All',
               method = 'update',
                  args = [{'visible': [True] * len(feed.columns.tolist())},
                          {'title': 'all'}
                           ])
buttonlist = [all_but]
for col in feed.columns.tolist():
    stock = go.Scatter(x=feed.index,
                       y=feed.loc[:, col],
                       name=col
                      )
    #actions
    success = trans.loc[trans.Symbol == col]
    actions = go.Scatter(x=success.Date,
                         y=success.Price,
                         name='',
                         mode = 'markers',
                         text = ['Amount ' + str(amount) for amount in success.Amount],
                         hoverinfo = 'text',
                         showlegend=False,
                         marker = dict(
                             size=10,
                             color = ['green' if i == 'buy' else 'red' for i in success.Action]

                         )
                        )
    data.append(stock)
    data.append(actions)
    button = dict(label = col,
                  method = 'update',
                  args = [{'visible': [col == i for i in feed.columns.tolist() for _ in range(2)]},
                          {'title': 'title' + col}
                           ])
    buttonlist.append(button)

updatemenus = list([
    dict(active=-1,
         buttons=buttonlist,
    )
])
layout = dict(title='Feed', showlegend=True,
              updatemenus=updatemenus)

fig = dict(data=data, layout=layout)
iplot(fig)

enter image description here

P.S.: I will appreciate advices on simpler ways to do the same as I am new to plotly.

Upvotes: 2

Views: 6138

Answers (1)

Ivan Mishalkin
Ivan Mishalkin

Reputation: 1108

Answer on plotly forum with code improvements: https://community.plot.ly/t/add-custom-legend-markers-color-to-plotly-python/19635/2

Upvotes: 1

Related Questions