当阵列长度变化时,计算堆叠条形图的累积底部值

2024-05-09 01:28:26 发布

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

找到了如何做到这一点: 使用pandas进行分组罢工、到期和计算未平仓利率,然后在搔了几个小时的脑筋后,我知道了.unstack()做了什么,并且做了什么

y = option_chain.groupby(['strike', 'expirationDate'])['openInterest'].sum().unstack(level=-1)
y.plot.bar(stacked=True)

我正在寻找一个堆叠的条形图为开放式权益的选择。我期待着做与这个链接中的人完全相同的事情:https://medium.com/@txlian13/webscraping-options-data-with-python-and-yfinance-e4deb0124613。我有来自同一来源的数据,并且我以同样的方式安排数据

我的问题是我找不到计算底部参数的方法,图表如下所示: 所有值都从y=0开始,而不是上一个条形高度

在其他选项中尝试了此代码,但无法使其正常工作

exp是选项所有可能过期日期的列表

bottom = np.zeros(12) #(using 12 because I am testing with the same stock, so I know my first array needs to be 12 to match the number of strikes for the first date)
for i in exp:
    z = option_chain.loc[option_chain['expirationDate'] == i]
    zx = z['strike']
    zy = z['openInterest']
    #here i print my bottom and its an empty array of 0s so it will plot the next line from 0
    plt.bar(zx,zy,label=i,alpha=0.7,bottom=bottom)
    bottom += zy
    #i print bottom again here and I can see that it has the 12 correct values of the open interest
    #then i get an error "ValueError: shape mismatch: objects cannot be broadcast to a single shape"

所以我的问题是,每次迭代时,罢工(我的x值)都会改变。例如,我的第一次迭代有12个x值,第二次迭代有9个x值

那么,有没有一种方法可以使变量数组随x的变化而变化,我也意识到这将导致另一个问题:如何匹配x,以便将其添加到正确的罢工

我想做的一个方法是找出罢工次数最多的日期,并以此作为我的基准,但问题是没有给出罢工次数最多的日期在其他日期的罢工次数

如果这个问题可以很容易地用另一个绘图软件包解决,我在使用它时没有问题。我是一名金融专业的毕业生,正试图学习python,所以只使用matplotlib,因为它是学习材料最多的一种


Tags: andoftheto方法chainplot次数