데이터의 가능성/pandas

05_Time_Series_Apple_Stock_Exercises

gamnyam 2024. 6. 24. 13:33

1. 필요한 라이브러리들을 import 하세요.

import pandas as pd
import numpy as np

 

2. 다음과 같은 DataSet을 import 하세요.

url = "https://raw.githubusercontent.com/myoh0623/dataset/main/appl_1980_2014.csv"

 

3. apple 라는 변수에 DataFrame을 할당 하세요.

apple = pd.read_csv(url)
apple.head()

 

4. 각 column들의 data type을 확인하세요.

apple.dtypes

 

5. Date column을 datetime type으로 변경하세요.

apple['Date'] = pd.to_datetime(apple['Date'], format='%Y-%m-%d')
apple.dtypes

 

6. Date column을 index로 설정하세요.

apple.set_index('Date', inplace=True, drop=True)

 

7. 중복되는 date가 존재 하는지 확인하세요.

apple.duplicated() # False : 중복된 데이터가 없다
apple.index.is_unique # True : 중복된 데이터가 없다

 

8. index를 오름차순으로 정렬하세요.

apple.sort_index(ascending=True, inplace = True) # 기본값이 오름차순, 내림차순은 ascending=False

 

9. 매월 마지막 영업일 가져오세요. (business day of each month)

apple.resample('BME').last().head()
# apple.resample("BME").apply(lambda x: x.iloc[-1])

 

10. 매월 영업일을 기준으로 평균을 가져오세요. (business day of each month)

apple.resample("BME").mean()

 

11. 주가가 등록된 첫날과 마지막 날의 차이는 몇일인가요?

(apple.index.min() - apple.index.max()).days

#(apple.index[0] - apple.index[-1]).days

 

12. 영업달 기준으로 몇달간의 데이터가 저장되어있나요?

len(apple.resample("BME"))

 

13. 'Adj Close'값을 이용해 종가 그래프를 그려보세요.

!pip install matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax_1 = fig.add_subplot(2,1,1)
ax_1.plot(apple.index, apple["Adj Close"])

fig = plt.figure()
ax_2 = fig.add_subplot(2,1,2)
ax_2.plot(apple.index, apple["Volume"], color="r")

plt.show()

# plt.plot(apple["Adj Close"])
# plt.show()

fig.add_subplot(2,1,1) : 행, 열, 몇 번 째