我有一个这样的数据框:
部门,名称,日期,价格
我想汇总我的数据,所以我要计算3年的波动率:
result = (df
.groupby(['sector', 'name'])
volat_3Y=('price', lambda x: 100*np.sqrt(252*np.log(x[-3*252:-1] / x[-3*252:-1].shift(1)).var())) )
我也想计算2020年,2019年...的表现,但是当我尝试时:
result = (df
.groupby(['sector', 'name'])
volat_3Y=('price', lambda x: 100*np.sqrt(252*np.log(x[-3*252:-1] / x[-3*252:-1].shift(1)).var()))
perf_2020=('price', lambda x.loc['2020-09-18']) # Just to have access to a specific date
)
我收到一条错误消息。有什么建议吗?
这是错误消息:
KeyError跟踪(最近一次通话最近) pandas._libs.index.DatetimeEngine.get_loc()中的pandas / _libs / index.pyx
pandas中的pandas / _libs / hashtable_class_helper.pxi._libs.hashtable.Int64HashTable.get_item()
pandas中的pandas / _libs / hashtable_class_helper.pxi._libs.hashtable.Int64HashTable.get_item()
KeyError:1600387200000000000
在处理上述异常期间,发生了另一个异常:
KeyError跟踪(最近一次通话最近) 〜/ opt / anaconda3 / envs / Data / lib / python3.8 / site-packages / pandas / core / indexes / base.py在get_loc中(自身,键,方法,公差) 2888试试: -> 2889返回self._engine.get_loc(casted_key) 2890,除了KeyError错误:
pandas._libs.index.DatetimeEngine.get_loc()中的pandas / _libs / index.pyx
pandas._libs.index.DatetimeEngine.get_loc()中的pandas / _libs / index.pyx
KeyError:Timestamp('2020-09-18 00:00:00')
答案 0 :(得分:0)
这个公式对我有用:
result = (
data
.set_index('Date')
.groupby(['Sector', 'Symbol'])
.agg(
volat_3Y = (
'Price',
lambda x: 100*np.sqrt(252*np.log(x[-3*252:-1] / x[-3*252:-1].shift(1)).var())),
perf_2020_09_18 = (
'Price',
lambda x: x.loc['2020-09-18'])
)
)
结果:
扇区 | 符号 | volatility_3yr | price_2020_09_18 |
---|---|---|---|
通信服务 | FB | 38.1945 | 252.53 |
通信服务 | GOOG | 30.7639 | 1459.99 |
通信服务 | NFLX | 42.3228 | 469.96 |
消费者循环 | 亚马逊 | 32.613 | 2954.91 |
技术 | AAPL | 35.5864 | 106.5 |
完整示例代码:
import numpy as np
import pandas as pd
import pandas_datareader as pdr
import yfinance
symbols = ['FB', 'AMZN', 'AAPL', 'NFLX', 'GOOG']
sectors = [yfinance.Ticker(symbol).info['sector'] for symbol in symbols]
symbols_sectors = dict(zip(symbols, sectors))
raw_data = pdr.get_data_stooq(symbols).Close
data = (
# get raw data
raw_data
# clean up names
.set_axis(list(raw_data.columns), 1)
.sort_index()
.reset_index()
# transform to long form
.melt('Date', var_name='Symbol', value_name='Price')
# attach sector names
.assign(Sector = lambda x: x.Symbol.map(symbols_sectors))
)
result = (
data
.set_index('Date')
.groupby(['Sector', 'Symbol'])
.agg(
volatility_3yr = (
'Price',
lambda x: 100*np.sqrt(252*np.log(x[-3*252:-1] / x[-3*252:-1].shift(1)).var())),
price_2020_09_18 = (
'Price',
lambda x: x.loc['2020-09-18'])
)
)
print(result.reset_index().to_markdown(index=False))