본문 바로가기
프로그램

[파이썬] 주식 chart에 월별 주요 이슈 표시(plot)

by 오디세이99 2023. 4. 6.
728x90
반응형
import pandas as pd
import matplotlib.pyplot as plt
from pykrx import stock
 
def first_date(adf):              # 월의 첫번쩨 날짜에 text를 쓰는 것으로 해서 첫 날짤을 찾음
    lst = []
    lst.append(df.index[0])        # 첫번째 데이터 추가
    old_month = df.index[0]
    for i in range(len(df)):
        dd = adf.index[i]                                        # df.index 가 문자열이 아닌 datatime이어서 동일하게 사용해여 함.
        if old_month.strftime('%Y-%m') != dd.strftime('%Y-%m'):  # 월이 바뀌는지 확인
            lst.append(dd)
            old_month = df.index[i]
    return lst


# 삼성전자 주가 데이터 가져오기 (2020-01-01 ~ 2020-12-31)
df = stock.get_market_ohlcv_by_date("20200101", "20201231", "005930")

# 주요 이슈 월별 날짜 및 내용
news = {
    '2020-01-13': '코로나바이러스 초기 확산',
    '2020-02-15': '코로나바이러스 확산으로 인한 경제 우려',
    '2020-03-15': '코로나바이러스 대유행',
    '2020-04-15': '주식시장 안정화 추세',
    '2020-05-15': '경제 정상화 기대감 상승',
    '2020-06-15': '국내 코로나바이러스 재확산 우려',
    '2020-07-15': '2분기 실적 발표',
    '2020-08-15': "한국 정부의 '한국판 뉴딜' 계획 발표",
    '2020-09-15': '코로나바이러스 백신 개발 소식',
    '2020-10-15': '3분기 실적 발표',
    '2020-11-15': '미국 대선 결과 발표 및 백신 개발',
    '2020-12-15': '코로나바이러스 백신 접종 시작',
}

date_lst = first_date(df)
issues = {}
for i in range(len(news)):
    issues[date_lst[i]] = list(news.values())[i]

# Plot 설정
fig, ax = plt.subplots(figsize=(12, 6))
plt.rcParams['font.family'] = 'NanumGothic'  # 한글 가능하도록 폰트 설정
ax.plot(df.index, df['종가'], label='삼성전자 종가', color='b')

# 주요 이슈 표시
for date, issue in issues.items():
    ax.annotate(issue, (date, df.loc[date]['종가']),
                xytext=(10, 10), textcoords='offset points',
                arrowprops=dict(arrowstyle='->', color='red'),
                color='red')

# 레이블 및 타이틀
ax.set_xlabel("날짜")
ax.set_ylabel("종가")
ax.set_title("2020년 삼성전자 주가 및 월별 주요 이슈")
ax.legend()
plt.xticks(rotation=45)

plt.show()

728x90
반응형

댓글