请用python写一段用brinson模型做基金业绩归因的代码
时间: 2023-06-09 18:04:44 浏览: 130
python 基金数据爬取
好的,很高兴为您提供帮助!以下是一段用Python编写的使用Brinson模型进行基金业绩归因的示例代码:
``` python
import pandas as pd
# 假设我们有以下数据:
portfolio = pd.DataFrame({'stock_A': [0.2, 0.1, 0.05],
'stock_B': [0.3, 0.15, 0.1],
'stock_C': [0.25, 0.2, 0.15],
'stock_D': [0.15, 0.1, 0.05],
'cash': [0.1, 0.45, 0.65]},
index=['beginning', 'current', 'ending'])
benchmark = pd.DataFrame({'stock_A': [0.25, 0.2, 0.15],
'stock_B': [0.3, 0.25, 0.2],
'stock_C': [0.2, 0.15, 0.1],
'stock_D': [0.15, 0.1, 0.05],
'cash': [0.1, 0.25, 0.5]},
index=['beginning', 'current', 'ending'])
# 首先计算组合和基准的收益率
portfolio_return = ((portfolio.loc['current'] - portfolio.loc['beginning']) / portfolio.loc['beginning']).values
benchmark_return = ((benchmark.loc['current'] - benchmark.loc['beginning']) / benchmark.loc['beginning']).values
# 计算组合中每个股票的贡献
stock_contributions = (portfolio.loc['current'] - portfolio.loc['beginning']).values * benchmark_return.reshape(-1, 1)
# 计算组合中每个股票的超额收益
stock_excess_returns = ((portfolio.loc['current'] - portfolio.loc['beginning']) / portfolio.loc['beginning']).values - benchmark_return
# 计算组合中股票选择和配置的总体贡献
stock_selection_contribution = stock_excess_returns - stock_contributions.sum(axis=0)
# 计算组合中每个行业的贡献
sector_contributions = portfolio.loc['current'].groupby(lambda x: x.split('_')[1], axis=0).sum() - \
portfolio.loc['beginning'].groupby(lambda x: x.split('_')[1], axis=0).sum() \
* benchmark_return.sum()
# 计算组合中每个行业的超额收益
sector_excess_returns = portfolio.loc['current'].groupby(lambda x: x.split('_')[1], axis=0).sum() / \
portfolio.loc['beginning'].groupby(lambda x: x.split('_')[1], axis=0).sum() - \
benchmark_return.sum()
# 计算组合中行业选择和配置的总体贡献
sector_selection_contribution = sector_excess_returns - sector_contributions.sum()
# 计算组合的总体贡献
total_portfolio_return = ((portfolio.loc['ending'] - portfolio.loc['beginning']) / portfolio.loc['beginning']).sum()
total_benchmark_return = ((benchmark.loc['ending'] - benchmark.loc['beginning']) / benchmark.loc['beginning']).sum()
total_contributions = portfolio.loc['current'] - portfolio.loc['beginning'].values.reshape(-1, 1) * \
benchmark.loc['current'].values.reshape(-1, 1)
total_selection_contribution = total_portfolio_return - total_benchmark_return - total_contributions.sum()
# 打印结果
print(f"Stock Contributions: {stock_contributions}\n")
print(f"Stock Selection Contribution: {stock_selection_contribution}\n")
print(f"Sector Contributions: {sector_contributions}\n")
print(f"Sector Selection Contribution: {sector_selection_contribution}\n")
print(f"Total Contributions: {total_contributions}\n")
print(f"Total Selection Contribution: {total_selection_contribution}\n")
```
希望这段代码对您有所帮助!如果您还有其他问题,请随时向我提出。
阅读全文