寻找时间序列中的最大下降

2024-03-28 13:28:32 发布

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

我想知道有没有一种有效的方法来为下面的代码生成输出。我正在寻找一个时间序列中的最大下降通过定位下降值的峰值

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.signal import find_peaks

data={'time': list(np.arange(21)), 'price': [10,11,12,13,12,10,9,13,14,15,18,19,20,22,23,20,17,16,19,24,23]}
df = pd.DataFrame(data, columns = ['time', 'price'])
plt.plot(df['time'],df['price'])

def max_drawdown_list(X):
    drawdowns = []
    peak = X[0]
    for x in X:
        if x > peak: 
            peak = x
        dd = peak - x
        drawdowns.append(dd)
    return drawdowns 

def max_drawdown(prices):
    peaks_index,_ = find_peaks(max_drawdown_list(prices), height = 0)
    max_dd_list = max_drawdown_list(prices)
    max_dd = [max_dd_list[i] for i in peaks_index]
    return max_dd, peaks_index
max_drawdown(df['price'])

diagram of price vs time, drawdown values vs time


Tags: importdfindextimeasnppricemax