【问题标题】:How can I plot specific points on top of another line plot?如何在另一个线图上绘制特定点?
【发布时间】:2021-07-28 00:35:45
【问题描述】:

我是一名交易员,我想跟踪我在基础证券价格走势中的所有头寸入场点。例如,这是迄今为止我的 BTC 头寸的代码。我导入我的库,加载我的数据并绘制最近几个月收盘价数据的范围。一切都是我想要的,但我不知道如何绘制我的位置条目。

这是代码和输出:

# Libraries
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import yfinance as yf


# Data load
BTC = yf.download(tickers='BTC-USD', start='2020-10-01', end='2021-05-03')
BTC_close = BTC['Close']
print(BTC.head())
BTC_positions = yf.download(tickers='BTC-USD', start='2021-02-01', end='2021-05-03')
MyBTC = BTC_positions['Close']
df_RAW = pd.DataFrame(BTC_positions, columns=['Date','Close'])



# Plot
fig = plt.figure()
f, ax = plt.subplots(1,1)
ax.tick_params(length=3, direction='in', labelsize=10)
fmt = '${x:,.0f}'
tick = mtick.StrMethodFormatter(fmt)
ax.yaxis.set_major_formatter(tick)
ax.xaxis.set_tick_params(direction='in')
MyBTC.plot(figsize=(12, 7))
plt.xticks(rotation=0)
plt.title("Bitcoin Position Entries", fontsize=20)
plt.xlabel('Day',fontsize=13) # or fontsize=10
plt.ylabel('Price $$$',fontsize=13) # or fontsize=10
plt.show()

输出图: 我想在其上绘制条目的原始数据图

我尝试过合并 2 个不同的字典:

字典 1 的键:输入日期的值对:花费的金额

Dict1 = {
    '2021-02-17': 250,
    '2021-02-24': 250,
    '2021-02-28': 50,
    '2021-03-08': 500,
    '2021-04-10': 500,
    '2021-04-14': 120,
    '2021-04-17': 400,
    '2021-04-21': 120,
    '2021-04-22': 875,
    '2021-04-23': 300,
    '2021-04-29': 125
}

字典 2 带有 key:value 对的 date-of-entry:price-of-underlying-security

Dict2 = {
    'Date': ['2021-02-17','2021-02-24','2021-02-28','2021-03-08','2021-04-10','2021-04-14','2021-04-17','2021-04-21','2021-04-22','2021-04-23','2021-04-29'],
    'Price': [51280, 49426, 44548, 50840, 60251, 62479, 53637, 55946, 51376, 48080, 53955]
}

我面临的问题是我在 2 月 17 日购买了价值 250 美元的商品,但我希望该点以合适的入场价格显示,即 51,280 美元,因此 y 轴超出了比例。 我在想我可以绘制点并根据购买的数量改变它们的大小或颜色渐变(较小的购买 = 小/亮点,较大的购买 = 大/暗点)

我尝试创建一个 DataFrame,因为我认为这会更容易,但我只是让自己更加困惑。

我已经走到了这一步,完全不知道该怎么做。我以为我在使用 Dict1 和 Dict2 时走在正确的轨道上,但现在我感到更加困惑。任何有关如何解决此问题的帮助将不胜感激。

【问题讨论】:

    标签: python pandas dictionary matplotlib plot


    【解决方案1】:

    遍历Dict1.items() 以从MyBTC 数据框中获取dateClose 价格(您也可以使用annotate 添加您从Dict1 购买的价格)。然后,应用scatter 函数在已经存在的线图之上绘制特定点。此函数将标记放置在 x 轴上由date 给出的位置,y 轴上放置收盘价(closep 来自MyBTC),并且像往常一样对于某些 matplotlib,您可以设置标记形状、大小 (linewidths) 和颜色。

    ...
    ...
    plt.xlabel('Day',fontsize=13) # or fontsize=10
    plt.ylabel('Price $$$',fontsize=13) # or fontsize=10
    
    for date,buy_price  in Dict1.items():
        closep = MyBTC[date]
        plt.annotate(str(buy_price), (date, closep), xytext=(-3, 6),
                textcoords='offset points',  weight='bold', fontsize=12)
        plt.scatter(date, closep, marker='v', linewidths=1, color='r')
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      • 2015-02-08
      • 1970-01-01
      • 2019-12-13
      • 2020-07-13
      • 2012-04-20
      相关资源
      最近更新 更多