我正在开发一个机器人来分析我在股票市场上的交易.我有两把斧头,一把绘制我的交易指令,另一把绘制交易股票的烛台图.

fig, (ax1, ax2) = plt.subplots(2)

# Plotting Trades
ax1.plot(...)

# Plotting Candlestick Chart
mpf.plot(stock.data, ax=ax2, type='candle')
ax2.set_title(f'Stock History of {stock.symbol}')
ax2.set_xlabel('Date')
ax2.set_ylabel('Price')

This works fine so far and plots the chart as envisioned. enter image description here

然而,我现在想在图表中添加我何时进入和退出交易的标记.为了简单起见,我接受了所有订单,并将所有日期和价格放在单独的列表中,这样我就可以指定X作为日期,Y作为价格.

# Plotting Orders
dates, prices = [], []
for key, order in broker.orders.items():
    dates.append(order.date)
    prices.append(order.price)
ax2.plot(dates, prices, 'o')

But instead, now the chart was completely gone and all I could see was the markers.enter image description here

甚至连日期都没有显示出来,这有点令人困惑,因为我在它自己的特定列表中拆分了日期,以便X位置仍然正确.

Anyone who has an idea of what's going on here? Thanks beforehand.

推荐答案

看起来mpf.plot(..., ax=ax2)ax2.plot(...)会覆盖对方的一些重要的绘图设置.您可能应该添加带有mplfinance.make_addplot()的订单数据,如下所示:

import mplfinance as mpf
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd

# market data
df = yf.download("SPY", start="2024-02-13", end="2024-02-14", interval='1h')

# some fake data
d = {
    'dates': ['2024-02-13 09:30:00', '2024-02-13 10:30:00', '2024-02-13 11:30:00', '2024-02-13 12:30:00', '2024-02-13 13:30:00', '2024-02-13 14:30:00', '2024-02-13 15:30:00'],
    'prices': [493.5, 495.2, 495.8, 494.8, 492.0, 492.6, 493.0]
}
my_df = pd.DataFrame(data=d)

# show everything on one plot
fig, ax = plt.subplots()
my_dict = mpf.make_addplot(my_df['prices'], type='scatter', ax=ax)
mpf.plot(df,
         ax=ax,
         type="candle",
         addplot=my_dict
    )

plt.show()

该代码生成以下图像:

enter image description here

UPDATE

如果您的订单数据仅适用于某些股票市场时间戳,那么您可以创建一个组合的price列,其中行中有NaN个值,其中订单数据"缺失".这样,您将有两个长度相等的数据框,适合在一个图上显示mpf.make_addplot()mpf.plot():

import mplfinance as mpf
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd

# get market data
df = yf.download("SPY", start="2024-02-13", end="2024-02-14", interval="1h")

# make some fake data with the same time format as market data
my_prices = [493.5, 495.2, 495.8]
# these timestamps must be a subset of those from the market data
my_timestamps = pd.date_range("2024-02-13 09:30:00", periods=len(my_prices), freq="H", tz="America/New_York")
d = {
# this column must be named the same way as the column with timestamps from the market data
    "Datetime": my_timestamps,
    "Prices": my_prices
}
my_df = pd.DataFrame(data=d)

# merge data sets, resulting in a new column with prices, where prices for missing market dates are NaN
combined_df = df.merge(my_df, how="outer", on="Datetime")

# show everything on one plot
fig, ax = plt.subplots()
my_dict = mpf.make_addplot(combined_df["Prices"], type="scatter", color="red", ax=ax)
mpf.plot(df,
         ax=ax,
         type="candle",
         addplot=my_dict
    )

plt.show()

结果如下:

enter image description here

Python相关问答推荐

需要计算60,000个坐标之间的距离

Python 约束无法解决n皇后之谜

Pandas - groupby字符串字段并按时间范围 Select

Python键入协议默认值

如何调整QscrollArea以正确显示内部正在变化的Qgridlayout?

关于Python异步编程的问题和使用await/await def关键字

使用Python更新字典中的值

导入...从...混乱

Pandas Loc Select 到NaN和值列表

不允许访问非IPM文件夹

为什么常规操作不以其就地对应操作为基础?

OpenCV轮廓.很难找到给定图像的所需轮廓

干燥化与列姆化的比较

用SymPy在Python中求解指数函数

如果包含特定值,则筛选Groupby

不允许 Select 北极滚动?

多个矩阵的张量积

无法在盐流道中获得柱子

与同步和异步客户端兼容的Python函数

搜索结果未显示.我的URL选项卡显示:http://127.0.0.1:8000/search?";,而不是这个:";http://127.0.0.1:8000/search?q=name";