
안녕하세요
chatGPT로 \financedatareader 로 최근 1년간 삼성전자의 종가 데이터의 20일 이동평균선과 60일 이동평균선을 그려주는 파이썬 코드를 만들어줘
' 라고 질문하여 받은 파이썬 코드를 colab에 붙여넣기 하였는데 오류가 발생했습니다.
먼저 colab에 붙여쓴 코드입니다
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
def get_stock_prices(ticker, start_date, end_date):
data = yf.download(ticker, start=start_date, end=end_date)
return data['Adj Close']
# Define the ticker for Samsung Electronics
samsung_ticker = '005930.KS' # Ticker for Samsung Electronics on the Korean Stock Exchange
# Define the date range (past year from today)
end_date = datetime.today().strftime('%Y-%m-%d')
start_date = (datetime.today() - timedelta(days=365)).strftime('%Y-%m-%d')
# Get stock prices
stock_prices = get_stock_prices(samsung_ticker, start_date, end_date)
# Calculate 20-day and 60-day moving averages
stock_prices['20_MA'] = stock_prices['Adj Close'].rolling(window=20).mean()
stock_prices['60_MA'] = stock_prices['Adj Close'].rolling(window=60).mean()
# Plot the data
plt.figure(figsize=(10, 6))
plt.plot(stock_prices['Adj Close'], label='Samsung Electronics Closing Price', linewidth=2)
plt.plot(stock_prices['20_MA'], label='20-day Moving Average', linestyle='--', linewidth=2)
plt.plot(stock_prices['60_MA'], label='60-day Moving Average', linestyle='--', linewidth=2)
plt.title('Samsung Electronics Stock Price with Moving Averages')
plt.xlabel('Date')
plt.ylabel('Price (KRW)')
plt.legend()
plt.show()
colab에서 코드 에러는 다음과 같습니다.
[*********************100%%**********************] 1 of 1 completed
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/_libs/tslibs/parsing.pyx in pandas._libs.tslibs.parsing.parse_datetime_string_with_reso()
8 frames
ValueError: Unknown datetime string format, unable to parse: Adj Close
During handling of the above exception, another exception occurred:
DateParseError Traceback (most recent call last)
DateParseError: Unknown datetime string format, unable to parse: Adj Close
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/datetimes.py in get_loc(self, key, method, tolerance)
704 parsed, reso = self._parse_with_reso(key)
705 except ValueError as err:
--> 706 raise KeyError(key) from err
707 self._deprecate_mismatched_indexing(parsed, one_way=True)
708
KeyError: 'Adj Close'
오류 설명을 파고다에 번역한 내용은 아래와 같습니다.
stock_prices DataFrame에서 Adj Close 열로 인해 오류가 발생했습니다. 이 열은 삼성전자의 조정된 종가를 포함하고 있지만 Panders가 파싱할 수 있는 형식은 아닙니다.
오류를 수정하려면 parse_dates 인수를 사용하여 Yahoo Finance에서 데이터를 로드할 때 parse_dates를 사용할 수 있습니다. 그러면 Panders는 Adj Close 열을 날짜로 파싱해야 합니다.
어떻게 고쳐야 할까요?
