【问题标题】:How to find all the points in time series data were new lows were made?如何找到时间序列数据中出现新低的所有点?
【发布时间】:2020-09-26 15:48:17
【问题描述】:

所以我有一组数据,即 AMD 股票价格,代码如下:

import pandas as pd
import pandas_datareader as web
import datetime as dt

#get stock prices
start = dt.datetime(2017, 1, 1)
end = dt.datetime(2020, 1, 1)
d = web.DataReader('AMD', 'yahoo', start, end)

所以知道我的问题是,每次股票(换句话说,d['Adj Close'])创下 52 周新低时,能够找出什么代码。因此,每次发生这种情况时,您都可以打印股票的价格。谢谢你

【问题讨论】:

    标签: python pandas dataframe datetime time-series


    【解决方案1】:
    # import packages, seed numpy
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    np.seed=42
    

    生成模拟数据

    时间戳和价格数据列表:

    timestamps = ['timestamp'+str(x) for x in range(20)]
    price = [np.random.normal(100,10) for _ in range(20)]
    

    Put them to a Pandas dataframe:

    df = pd.DataFrame({'timestamps':timestamps,'price':price})
    

    寻找低点

    让我们定义window。每次代码考虑一个数据点时,它都会考虑window-之前的许多数据点(不包括它自己)。

    window=3
    

    遍历价格,检查当前价格是否低于window-之前的任何价格。保存 True 的那些数据点的索引:

    indices=[]
    for index, row in enumerate(df.iterrows()):
        if index >= window:
            if all(df.loc[index,'price'] < each for each in df[index-window:index]['price'].values):
                indices.append(index)
    

    或者,如果您更喜欢list comprehensions

    indices = [index for index, row in enumerate(df.iterrows()) if index>=window and all(df.loc[index,'price'] < each for each in df[index-window:index]['price'].values)]
    

    检查结果

    让我们plot the data 和我们的发现来确保它是正确的。我们将plot the lows as vertical lines 参与我们的阴谋。

    df.plot()
    for index in indices:
        plt.axvline(index,c='r')
    

    导致:

    这是我们所期望的。

    【讨论】:

    • 非常感谢您的所有帮助,尤其是另一个问题,您是救世主!
    猜你喜欢
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 2020-03-23
    • 2021-10-27
    • 1970-01-01
    • 2020-09-18
    相关资源
    最近更新 更多