python - 连接点和区间数据

标签 python pandas

我有两个时间序列需要加入:

第一个是价格的时间序列 像这样

ticker date       price 
SBUX   01/01/2012 55

第二个时间序列是调整因子,表示为

ticker start_date end_date    adjustment_factor
SBUX   01/01/1993 01/01/1994  0.015

如何在 pandas 中将这些时间序列连接在一起,以表达调整后的价格

adjusted_price = historical_prices * adjustment_factor

我知道我需要使用 date_range 函数将 adjustment_factor 间隔时间序列扩展为每日序列。 但问题是调整时间序列的每一行都将具有不同的日期范围——有没有一种方法可以对整个调整因子时间序列的间隔日期类型进行批处理转换,而不是对每一行进行转换。

我发现我需要将第一个时间点时间序列旋转到列中,将日期放入行中,对于第二个时间序列,将间隔扩展到每日粒度并旋转它(通过 dataframe.pivot功能。通过组合两个数据框,可以编写我需要的功能。

最佳答案

您可以简单地将 dataFrame 与您的每日柱连接起来,并使用 fillna(method="ffill") 前向填充先前的值。在您的示例中,您有一个范围的调整因子。

#suppose sbux is an ohlc daily bar and adj is your adjustment factors  
adj  = pandas.DataFrame({"adj":pandas.Series(values,index = start_dates)})
sbux_with_adj  = sbux.join(adj)
sbux_with_adj["Adj"] =    sbux_with_adj["Adj"].fillna(method="ffill")
ohlc = sbux_with_adj[["Open","High","Low","Close"]] * sbux_with_adj["adj"]

我会按照以下方式使用更常见的调整因子(例如 .985 表示 1.5% 的股息)进行调整:

sbux_with_adj  = sbux.join(adj)
sbux_with_adj["Adj"] =    sbux_with_adj["Adj"].fillna(1.0)
#now reverse cumulated adjustment.
cumulated_adj = sbux_with_adj["Adj"].cumprod().values[::-1] 
ohlc = sbux_with_adj[["Open","High","Low","Close"]] * cumulated_adj

关于python - 连接点和区间数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12907231/

相关文章:

python代码试图找到质数。代码计算的不是素数。找不到原因

python - 如何旋转数据框

python - Pandas 在 groupby 后为每组采样不同的分数

pandas - Seaborn多变量组条形图

python - 如何在python中创建本体?

python - 使用时间戳列表选择由 DatetimeIndex 索引的 Pandas DataFrame 的子集

python - 基于另一个数组更改 numpy 数组值的矢量化方法

python - 在BeautifulSoup抓取之后,从Python列表中提取数据,并创建Pandas表

python - 使用 8 位量化将 Keras MobileNet 模型转换为 TFLite

python - 具有彩色高度的 Matplotlib 3D 瀑布图