如何找到股票价格在一定范围内的当前期间之前的nbr

2024-05-16 07:59:25 发布

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

我有一个X年内每日股票价格高低的数据框架。每天我都有一个由上限和下限定义的范围。这个范围每天都在变化。我想找出股票价格在这个范围内的天数

I.e. number of days going back from period i such that high[i-j] < upperbound[i] & low[i-j] > lowerbound[i] where j = i-1 all the way down to 0.

我曾尝试在pandas数据帧上使用Expansing(),但无法使该函数正常工作,也不确定如何自定义该函数。我非常热衷于使用expanding()

import pandas as pd

high = pd.DataFrame([[0.97, 1.95], [0.95, 2.1], [0.99, 1.96], [0.98, 1.99]], columns=['Stock1', 'Stock2'])
upper_bound = pd.DataFrame([[1.01, 2.06], [1.02, 2.01], [1.02, 2.0], [1.0, 2.01]], columns=['Stock1', 'Stock2'])
low = pd.DataFrame([[0.49, 1.21], [0.51, 1.22], [0.52, 1.21], [0.53, 1.201]], columns=['Stock1', 'Stock2'])
lower_bound = pd.DataFrame([[0.48, 1.2], [0.509, 1.21], [0.5, 1.201], [0.48, 1.19]], columns=['Stock1', 'Stock2'])

如果股票高点和低点历史上从未超出范围,函数应返回NA。如果库存已超出范围,则函数应返回从[i]到[i-j]的期间数,即应返回j

将应用于多个股票的大型数据帧,因此寻找优雅的快速矢量化(矩阵化-这是一个字)解决方案

使用我上面的例子,我希望结果是:

    Stock1   Stock2
0   NA       NA
1   1        0
2   2        1
3   NA       2

换句话说,对于Stock1

period [0], there is no historical price that was out of range(lower [0] to upper [0]) -> NA
period [1], the low of period [0] is smaller than lower bound [1] -> 1 day of history within range
period [2], the low of period [0] is smaller than lower bound [2] -> 2 days of histroy within range
period [3], there is no historical price that was out of range(lower [3] to upper [3]) -> NA 

库存2

period [0], there is no historical price that was out of range (lower [0] to upper [0]) -> NA
period [1], the high of period [1] is higher than upper bound [1] -> 0 days of history within range
period [2], the high of period [1] is higher than upper bound [2] -> 1 day of histroy within range
period [3], the high of period [1] is higher than upper bound [3] -> 2 days of histroy within range

任何帮助都将不胜感激


Tags: oftheisrangeupperlowerperiodpd