如何向烛台绘图添加标签?

2024-04-29 07:13:11 发布

您现在位置:Python中文网/ 问答频道 /正文

https://www.kaggle.com/tencars/interactive-bollinger-bands-for-technical-analysis

我使用上述方法绘制带有布林带的烛台图

有人能告诉我如何添加额外的标签来标记绘图的某些特征吗。例如,用一个向上的三角形标记局部最小“闭合”es,用一个向下的三角形标记局部最大“闭合”es


Tags: https标记comforeswww局部analysis
1条回答
网友
1楼 · 发布于 2024-04-29 07:13:11

由于我无法下载kaggle提供的数据,我从Yahoo Finance获得了AAPL股票价格,并将其用作数据。对于图形本身,我使用kaggle中的代码更改每行的颜色以生成图形。对于文本注释,我使用了add_annotation()。适当地设置了注释数据

import pandas as pd
from datetime import datetime
import plotly.graph_objects as go
import yfinance as yf

df = yf.download("AAPL", start="2021-06-21", interval='1m', end="2021-06-22")
df.reset_index(inplace=True)
df.columns =['time', 'open', 'high', 'low', 'close', 'adj close', 'volume']
# Create a working copy of the last 2 hours of the data
btc_data = df.iloc[-240:].copy()

# Define the parameters for the Bollinger Band calculation
ma_size = 20
bol_size = 2

# Convert the timestamp data to a human readable format
btc_data.index = pd.to_datetime(btc_data.time, unit='ms')

# Calculate the SMA
btc_data.insert(0, 'moving_average', btc_data['close'].rolling(ma_size).mean())

# Calculate the upper and lower Bollinger Bands
btc_data.insert(0, 'bol_upper', btc_data['moving_average'] + btc_data['close'].rolling(ma_size).std() * bol_size)
btc_data.insert(0, 'bol_lower', btc_data['moving_average'] - btc_data['close'].rolling(ma_size).std() * bol_size)

# Remove the NaNs -> consequence of using a non-centered moving average
btc_data.dropna(inplace=True)

# Create an interactive candlestick plot with Plotly
fig = go.Figure(data=[go.Candlestick(x = btc_data.index,
                                     open = btc_data['open'],
                                     high = btc_data['high'],
                                     low = btc_data['low'],
                                     showlegend = False,
                                     close = btc_data['close'])])

# Plot the three lines of the Bollinger Bands indicator
parameter = ['moving_average', 'bol_lower', 'bol_upper']
colors = ['blue', 'orange', 'orange']
for param,c in zip(parameter, colors):
    fig.add_trace(go.Scatter(
        x = btc_data.index,
        y = btc_data[param],
        showlegend = False,
        line_color = c,
        mode='lines',
        line={'dash': 'solid'},
        marker_line_width=2, 
        marker_size=10,
        opacity = 0.8))
    
# Add title and format axes
fig.update_layout(
    title='Bitcoin price in the last 2 hours with Bollinger Bands',
    yaxis_title='BTC/USD')

x = '2021-06-21 10:56:00'
y = df['close'].max()
fig.add_annotation(x=x, y=y,
                   text='\U000025bc',
                   showarrow=False,
                   yshift=10)

xx = '2021-06-21 09:50:00'
yy = df['close'].min()
fig.add_annotation(x=xx, y=yy,
                   text='\U000025b2',
                   showarrow=False,
                   yshift=10)

fig.show()

enter image description here

相关问题 更多 >