import pandas as pd
# 엑셀 파일 불러오기
data = pd.read_excel('kospi.xlsx')
# 열 이름을 새롭게 지정된 변수명으로 설정
data.columns = ['date', 'kospi_index', 'price']
# 날짜 컬럼을 datetime 형식으로 변환
data['date'] = pd.to_datetime(data['date'])
# 날짜를 인덱스로 설정
data.set_index('date', inplace=True)
# 각 월의 마지막 거래일 찾기 ('M' 대신 'ME' 사용)
monthly_kospi_last = data['kospi_index'].resample('ME').apply(lambda x: x.iloc[-1])
monthly_price_last = data['price'].resample('ME').apply(lambda x: x.iloc[-1])
# 전 월의 마지막 거래일 데이터 가져오기
monthly_kospi_last_prev = monthly_kospi_last.shift(1)
monthly_price_last_prev = monthly_price_last.shift(1)
# 수익률 계산 (이번 달 마지막 거래일 가격 - 전 월 마지막 거래일 가격) / 전 월 마지막 거래일 가격
monthly_kospi_return = (monthly_kospi_last - monthly_kospi_last_prev) / monthly_kospi_last_prev
monthly_price_return = (monthly_price_last - monthly_price_last_prev) / monthly_price_last_prev
# 결과 확인
result = pd.DataFrame({
'prev_kospi_last_index': monthly_kospi_last_prev,
'current_kospi_last_index': monthly_kospi_last,
'kospi_return': monthly_kospi_return,
'prev_price_last': monthly_price_last_prev,
'current_price_last': monthly_price_last,
'price_return': monthly_price_return
})
# 결과를 엑셀 파일로 저장
result.to_excel('output.xlsx', index=True)
'Python' 카테고리의 다른 글
| Quantiwise_tosql (1) | 2024.09.25 |
|---|---|
| SEIBro 채권정보 수집 (iframe 크롤링) (1) | 2024.07.03 |
| 종가시계열 시각화 컬러맵 (중앙값 기준 정규화) (1) | 2024.04.27 |
| 시각화 컬러맵 (1) | 2024.04.27 |
| DART 자사주 취득, 무상증자 공시 알림 (0) | 2024.03.25 |