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?

あwだ

Last updated at Posted at 2024-05-27

import pandas as pd
import numpy as np

データフレームを日付でソート

df.sort_values(by='TDATE', inplace=True)

銘柄コードごとにグループ化

grouped = df.groupby('SICC_CODE')

幾何平均を計算する関数

def geom_mean(iterable):
a = np.array(iterable)
return a.prod()**(1.0/len(a))

EPSの変動率と幾何平均を計算する関数

def calculate_growth_rates(group):
# EPSの変動率を計算(3ヶ月ごと)
group['Growth_Rate'] = group['EPS'].pct_change(periods=3)
# 3か月ごとの変動率の幾何平均を、15か月後から計算して格納
geom_means = []
for i in range(len(group)):
if i >= 14: # 15か月目から幾何平均を計算
rates = group['Growth_Rate'].iloc[i-14:i+1] # 過去15か月分のデータを取得
if not rates.isnull().any(): # NaN値がなければ計算
geom_mean_val = geom_mean(rates.dropna())
else:
geom_mean_val = np.nan
geom_means.append(geom_mean_val)
else:
geom_means.append(np.nan)
group['Geom_Mean_Growth'] = geom_means
return group

各銘柄コードに関数を適用してデータフレームを更新

df = grouped.apply(calculate_growth_rates)

結果の表示

print(df[['TDATE', 'SICC_CODE', 'EPS', 'Geom_Mean_Growth']])

0
0
1

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?