如何找到 7 种资产的平均回撤?
How to find AVERAGE drawdown of 7 assets?
我目前的任务是找出 7 种资产的平均回撤。这是我目前所拥有的:
end = dt.datetime.today()
start = end - dt.timedelta(365)
tickers = ["SBUX", "MCD", "CMG", "WEN", "DPZ", "YUM", "DENN"]
bench = ['SPY', 'IWM', 'DIA']
table_1 = pd.DataFrame(index=tickers)
data = yf.download(tickers+bench, start, end)['Adj Close']
log_returns = np.log(data/data.shift())
table_1["drawdown"] = (log_returns.min() - log_returns.max() ) / log_returns.max()
然而,当我真正想要平均值时,这只会给我最大回撤。
您需要 scipy 才能找到本地 max/min:
from scipy.signal import argrelextrema
我定义了一个函数来计算时间序列的局部最小值和最大值。然后简单地计算每个局部最大值和下一个局部最小值之间的相对差并计算平均值:
def av_dd(series):
series = series.values # convert to numpy array
drawdowns = []
loc_max = argrelextrema(series, np.greater)[0] # getting indexes of local maximums
loc_min = argrelextrema(series, np.less)[0] # getting indexes of local minimums
# adding first value of series if first local minimum comes before first local maximum (you want the first drawdown to be taken into account)
if series[0]>series[1]:
loc_max = np.insert(loc_max,0,0)
# adding last value of series if last local maximum comes after last local minimum (you want the last drawdown to be taken into account)
if len(loc_max)>len(loc_min):
loc_min = np.append(loc_min, len(series)-1)
for i in range(len(loc_max)):
drawdowns.append(series[loc_min[i]]/series[loc_max[i]]-1)
return sum(drawdowns)/len(drawdowns)
函数中的两个 if 语句都在这里,以确保您还考虑了第一次和最后一次回撤,具体取决于时间序列开始和结束时的局部极值是什么。
您只需要将此功能应用到您的数据时间
table_1['drawdown'] = df.apply(lambda x: av_dd(x))
我目前的任务是找出 7 种资产的平均回撤。这是我目前所拥有的:
end = dt.datetime.today()
start = end - dt.timedelta(365)
tickers = ["SBUX", "MCD", "CMG", "WEN", "DPZ", "YUM", "DENN"]
bench = ['SPY', 'IWM', 'DIA']
table_1 = pd.DataFrame(index=tickers)
data = yf.download(tickers+bench, start, end)['Adj Close']
log_returns = np.log(data/data.shift())
table_1["drawdown"] = (log_returns.min() - log_returns.max() ) / log_returns.max()
然而,当我真正想要平均值时,这只会给我最大回撤。
您需要 scipy 才能找到本地 max/min:
from scipy.signal import argrelextrema
我定义了一个函数来计算时间序列的局部最小值和最大值。然后简单地计算每个局部最大值和下一个局部最小值之间的相对差并计算平均值:
def av_dd(series):
series = series.values # convert to numpy array
drawdowns = []
loc_max = argrelextrema(series, np.greater)[0] # getting indexes of local maximums
loc_min = argrelextrema(series, np.less)[0] # getting indexes of local minimums
# adding first value of series if first local minimum comes before first local maximum (you want the first drawdown to be taken into account)
if series[0]>series[1]:
loc_max = np.insert(loc_max,0,0)
# adding last value of series if last local maximum comes after last local minimum (you want the last drawdown to be taken into account)
if len(loc_max)>len(loc_min):
loc_min = np.append(loc_min, len(series)-1)
for i in range(len(loc_max)):
drawdowns.append(series[loc_min[i]]/series[loc_max[i]]-1)
return sum(drawdowns)/len(drawdowns)
函数中的两个 if 语句都在这里,以确保您还考虑了第一次和最后一次回撤,具体取决于时间序列开始和结束时的局部极值是什么。
您只需要将此功能应用到您的数据时间
table_1['drawdown'] = df.apply(lambda x: av_dd(x))