【发布时间】:2021-06-09 17:05:12
【问题描述】:
您好,我有一个具有多个输入的函数,我想通过滚动窗口计算它。
我的功能是:
def tracking_error(r_a, r_b):
'''
Returns the tracking error between two return series.
This method is used in Sharpe Analysis minimization problem.
See STYLE_ANALYSIS method.
'''
return ( ((r_a - r_b)**2).sum() )**(0.5)
def style_analysis_tracking_error(weights, ref_r, bb_r):
'''
Sharpe style analysis objective function.
Returns the tracking error between the reference returns
and a portfolio of building block returns held with given weights.
'''
return tracking_error(ref_r, (weights*bb_r).sum(axis=1))
def style_analysis(dep_var, exp_vars):
'''
Sharpe style analysis optimization problem.
Returns the optimal weights that minimizes the tracking error between a portfolio
of the explanatory (return) variables and the dependent (return) variable.
'''
# dep_var is expected to be a pd.Series
if isinstance(dep_var,pd.DataFrame):
dep_var = dep_var[dep_var.columns[0]]
n = exp_vars.shape[1]
init_guess = np.repeat(1/n, n)
weights_const = {
'type': 'eq',
'fun': lambda weights: 1 - np.sum(weights)
}
solution = minimize(style_analysis_tracking_error,
init_guess,
method='SLSQP',
options={'disp': False},
args=(dep_var, exp_vars),
constraints=(weights_const,),
bounds=((0.0, 1.0),)*n)
weights = pd.Series(solution.x, index=exp_vars.columns)
return weights
据此,我有一个包含我的数据的数据框,并计算长度为windowie 的时间段内每个日期的输出,例如:
weights = rolling(252).apply(style_analysis, y, x)
有什么想法吗?
【问题讨论】:
-
一目了然,您所做的优化将破坏您使用内置
rolling功能可能获得的任何效率。既然如此,我只会自己“滚动”它。for i in range(252, len(df)): df_ = df.iloc[i - 252: i]和df_做你想做的事。这有意义吗? -
不清楚!我的函数返回:
AGG 0.030380 IWP 0.357634 IWX 0.526391 IWY 0.085595 dtype: float64,我想将结果存储在 df 中,日期为索引。 -
我建议提供minimal reproducible example 以便我可以查看和使用数据。否则,我们会围着对方兜圈子,一无所获。
-
我的数据来自:
import yfinance as yf etf = yf.download("IWX IWY IWS IWP ACWX AGG", start="2010-01-01")['Adj Close']然后:df = etf.pct_change().dropna()最后我想将所有输出权重存储在 df 中:weight = style_analysis(ret['ACWX'], ret[['AGG', 'IWP', 'IWX', 'IWY']]) -
这对我来说工作量太大了。我想查看可以复制和粘贴的数据子集。使用比 252... 更短的值...比如 10 来表达观点。然后显示结果数据应该是什么样子。我知道这看起来像是工作,但我更愿意你做而不是我做。
标签: python pandas apply rolling-computation