gpt4 book ai didi

python - 将自定义图例(标记颜色)添加到 plotly python

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:03 25 4
gpt4 key购买 nike

我尝试使用 plotly 可视化交易算法。我有两个数据框:一个是收盘价,另一个是我的算法执行的交易。绿点应该用于买入操作,红色用于卖出。我还想要的是有一个菜单,可以选择要分析的股票。现在一切都通过在收盘价上绘制操作来工作。

问题是:如何在某个位置添加点颜色的图例(绿色买入,红色卖出)?

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.:我会很感激关于更简单的方法的建议,因为我是 plotly 的新手。

最佳答案

关于python - 将自定义图例(标记颜色)添加到 plotly python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54705261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com