摘要:我正在尝试使用 Pandas 数据框来存储历史股票期权链信息。我按以下顺序设置了索引:
使用这 4 个索引,您可以选择任何单行数据。
问题:问题不是获取有问题的行,而是尝试查找索引值的有效组合,而不包含额外信息。例如,如果我想知道在特定日期可以交易哪些期权到期(quote_datetime 已知,并且我想返回与quote_datetime 键匹配的所有唯一“到期”),该怎么办?或者我想知道给定的 quote_datetime 和到期时间可用的所有罢工。在这些示例中,我不关心数据,我试图查找哪些索引键是有效的,而只有几个已知的索引值。
示例:我正在删除此示例的 option_type 索引和大量数据列,以尽量保持其较小。
oc = { 'quote_datetime': ['2020-08-01', '2020-08-01', '2020-08-01', '2020-08-01', '2020-08-01', '2020-08-01', '2020-08-01', '2020-08-01', '2020-08-01', '2020-08-02', '2020-08-02', '2020-08-02', '2020-08-02', '2020-08-02', '2020-08-02'],
'expiration': ['2020-08-01', '2020-08-01', '2020-08-01', '2020-08-03', '2020-08-03', '2020-08-03', '2020-08-05', '2020-08-05', '2020-08-05', '2020-08-03', '2020-08-03', '2020-08-03', '2020-08-05', '2020-08-05', '2020-08-05'],
'strike': [10, 15, 20, 10, 15, 20, 10, 15, 20, 10, 15, 20, 10, 15, 20],
'price':[3, 2, 1, 4, 3, 2, 5, 4, 3, 3.5, 2.5, 1.5, 4.5, 3.5, 2.5]}
df = pd.DataFrame(data=oc)
df = df.set_index(['quote_datetime','expiration','strike'])
df = df.sort_index()
这为我们提供了一个如下所示的数据框:
price
quote_datetime expiration strike
2020-08-01 2020-08-01 10 3.0
15 2.0
20 1.0
2020-08-03 10 4.0
15 3.0
20 2.0
2020-08-05 10 5.0
15 4.0
20 3.0
2020-08-02 2020-08-03 10 3.5
15 2.5
20 1.5
2020-08-05 10 4.5
15 3.5
20 2.5
假设我想查看 8 月 2 日可用的所有到期日。
df.loc['2020-08-02'].index.levels[0]
我希望收到 ['2020-08-03', '2020-08-05'],而是得到
Index(['2020-08-01', '2020-08-03', '2020-08-05'], dtype='object', name='expiration')
'2020-08-01' 不是我在 .loc[] 中使用的 quote_datetime 的有效期限。似乎 .levels 只是返回数据框中的每个索引,而忽略了我使用 .loc 过滤的行。
我也试过
df.loc['2020-08-02'].index.get_level_values(0)
但它返回每一行而不是唯一索引。这几乎有效,只是我必须通过一个函数运行它才能获得独特的组合。
Index(['2020-08-03', '2020-08-03', '2020-08-03', '2020-08-05', '2020-08-05',
'2020-08-05'],
dtype='object', name='expiration')
这是在一个有很多行的 20 GB .csv 上完成的,所以如果可能的话,我试图让它保持轻便和快速......虽然在这一点上,只要能得到我需要的数据就好了. 我不太精通使用 python 进行此类工作,但这样做可以让我利用已经存在的库。
您可以将.loc
和index.unique()
组合在一起并通过所需的级别以获取其他级别的索引。此外,由于这些是多索引,我建议您使用 tuple.loc
甚至用于单级索引,以使所有内容看起来一致。
# To get unique expiration indices for given quote date index
>>> df.loc[('2020-08-02',)].index.unique(0)
Index(['2020-08-03', '2020-08-05'], dtype='object', name='expiration')
#To get unique strike indices for a given quote date index
>>> df.loc[('2020-08-02',)].index.unique(1)
Int64Index([10, 15, 20], dtype='int64', name='strike')
#To know the strike indices for given quote and expiration date indices
>>> df.loc[('2020-08-01', '2020-08-01')].index.unique(0)
Int64Index([10, 15, 20], dtype='int64', name='strike')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句