0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

あs

Posted at

import pandas as pd
import matplotlib.pyplot as plt

Excelファイルを読み込む

dt_with_bpr_and_roa = pd.read_excel('/mnt/data/Book2.xlsx')

TDATE列を文字列として扱う(YYYYMM形式のデータを維持するため)

dt_with_bpr_and_roa['TDATE'] = dt_with_bpr_and_roa['TDATE'].astype(str)

月次リターンを計算する関数を定義する

def calculate_monthly_returns(df):
df = df.sort_values(by='TDATE')
df['Return'] = df['PRC'].pct_change()
return df

銘柄コードごとにグループ化し、月次リターンを計算する関数を適用する

dt_with_bpr_and_roa = dt_with_bpr_and_roa.groupby('SICC_CODE').apply(calculate_monthly_returns).reset_index(drop=True)

'Return'列にNaN値がある行を削除する(最初の月にはリターンが計算できないためNaNが含まれる)

dt_with_bpr_and_roa = dt_with_bpr_and_roa.dropna(subset=['Return'])

各分位(quantile)の平均リターン、リスク、効率性を計算する

quantile_stats = dt_with_bpr_and_roa.groupby('qua')['Return'].agg(['mean', 'std'])

効率性(平均リターン/リスク)を計算し、新しい列'Efficiency'に追加する

quantile_stats['Efficiency'] = quantile_stats['mean'] / quantile_stats['std']

列名をわかりやすくする

quantile_stats.columns = ['Mean Return', 'Risk', 'Efficiency']

ベンチマークとして全体の平均リターンを計算

benchmark_return = dt_with_bpr_and_roa['Return'].mean()

各分位の平均リターンに対してベンチマークを引いた超過収益を計算

quantile_stats['Excess Return'] = quantile_stats['Mean Return'] - benchmark_return

各分位の累積リターンを計算する

cumulative_returns = dt_with_bpr_and_roa.groupby(['TDATE', 'qua'])['Return'].mean().unstack().cumsum()

累積超過収益を計算する

cumulative_excess_returns = cumulative_returns.subtract(benchmark_return, axis=0).cumsum()

累積超過収益をプロットする

plt.figure(figsize=(12, 8))
for qua in cumulative_excess_returns.columns:
plt.plot(cumulative_excess_returns.index, cumulative_excess_returns[qua], label=f'Quantile {qua}')
plt.title('Cumulative Excess Returns by Quantile')
plt.xlabel('Date')
plt.ylabel('Cumulative Excess Return')
plt.legend()
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()

プロットを表示する

plt.show()

累積超過収益を表示する

print("\nCumulative Excess Returns by Quantile:\n", cumulative_excess_returns)

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?