예를 들어 검색하는 방법을 이미 시연했습니다. Python에서 pandas_datareader를 사용하는 FRED의 GDP 데이터. 또한 Yahoo Finance를 소스로 사용하고 pandas_datareader를 통해 데이터를 가져 오는 Procter & Gamble의 주가를 분석했습니다.
이 게시물에서는 UPS 및 FedEx에 대한 일일 재고 반품을 분석하고 싶습니다. pandas_datareader를 사용하여 데이터를 가져옵니다. 데이터에 대한 추가 분석을 수행하고 matplotlib.pyplot을 사용하여 결과를 시각화합니다.
항상 그렇듯이 첫 번째 단계는 관련 모듈을 가져 오는 것입니다.
# 관련 모듈 가져 오기
import pandas as pd
import pandas_datareader.data as web
import datetime
import matplotlib.pyplot as plt
다음 단계는 pandas_datareader를 통해 Yahoo Finance에서 주가 데이터를 가져 오는 것입니다.
# 시작 및 종료 날짜에 대한 날짜 시간 정의
start_date = datetime.datetime(2000, 1, 1)
end_date = datetime.datetime(2020, 9, 30)
# Yahoo Finance에서 시작일과 종료일 사이의 지정된 기간 동안 주식 데이터 가져 오기
ups = web.DataReader("UPS", "yahoo", start_date, end_date)
fedex = web.DataReader("FDX", "yahoo", start_date, end_date)
이 게시물에는 몇 가지 도우미 기능이 필요합니다. 먼저 일일 주식 수익률 플로팅 함수를 정의합니다.
def plottingReturns(title,xtitle,ytitle,df1,df2,color1,color2,returns1,returns2,alpha1,alpha2):
# create figure
plt.figure(figsize=(17.5,10))
# create line plots for daily returns
plt.plot(df1.index,returns1,color=color1,alpha=alpha1)
plt.plot(df1.index,returns2,color=color2,alpha=alpha2) # df1.index placed here on purpose
# add title to plot
plt.title(title, size=22)
# add x-axis label
plt.xlabel(xtitle, size=16)
# add y-axis label
plt.ylabel(ytitle, size=16)
또한 일일 주식 수익률의 분포를 플로팅하기위한 히스토그램 플로팅 함수를 정의합니다.
def histogramReturns(title,xtitle,ytitle,color1,color2,returns1,returns2,alpha1,alpha2,name1,name2):
# 그림 만들기
plt.figure(figsize=(17.5,10))
# 일일 수익을위한 라인 플롯 생성
plt.hist(returns1,histtype="bar",color=color1,alpha=alpha1,label=name1,bins=100)
plt.hist(returns2,histtype="bar",color=color2,alpha=alpha2,label=name2,bins=100) # 의도적으로 여기에 배치 된 df1.index
# 플롯에 제목 추가
plt.title(title, size=22)
# x 축 레이블 추가
plt.xlabel(xtitle, size=16)
# y 축 레이블 추가
plt.ylabel(ytitle, size=16)
또한 주가 시계열 플로팅 함수를 정의합니다.
def plottingPrices(title,xtitle,ytitle,df1,df2,color1,color2):
# 그림 만들기
plt.figure(figsize=(17.5,10))
# 일일 종가에 대한 라인 플롯 생성
plt.plot(df1.index,df1["Close"],color=color1,alpha=0.5)
plt.plot(df1.index,df2["Close"],color=color2,alpha=0.5) # 의도적으로 여기에 배치 된 df1.index
# 플롯에 제목 추가
plt.title(title, size=22)
# x 축 레이블 추가
plt.xlabel(xtitle, size=16)
# y 축 레이블 추가
plt.ylabel(ytitle, size=16)
마지막으로 일일 주식 수익률 계산 함수를 정의합니다.
def returns(df):
prices = df["Close"]
returns = [0 if i == 0 else 100*(prices[i]-prices[i-1])/(prices[i-1]) for i in range(0,len(prices))]
return(returns)
이제 위의 일일 재고 수익률 계산 기능을 사용하여 일일 주식 종가를 기준으로 2020 년 이후의 UPS 및 FedEx 일일 재고 수익률을 계산합니다.
또한 ups 및 fedex 데이터 프레임 날짜 목록의 길이가 일일 재고 반환 목록의 길이와 동일한 지 테스트합니다.
print(len(ups.index))
5220
print(len(fedex.index))
5220
테스트에 성공했습니다. 데이터가 일관된 것 같습니다. 이제 이미 정의 된 플로팅 기능을 사용하여 2000 년 이후 UPS 및 FedEx의 일일 재고 반품을 시각화합니다.
plottingReturns("UPS [black] vs. FedEx [orange] daily stock returns since 2000","Date","Daily stock return [%]",ups,fedex,"black","orange",return_ups,return_fedex,0.25,0.60)
위의 히스토그램 플로팅 기능을 사용하여 UPS 및 FedEx의 일일 재고 반품 분포를 살펴 보겠습니다.
histogramReturns("Histogram of daily stock returns for UPS [black] and FedEx [orange]","Daily return [%]","Absolute frequency [-]","black","orange",return_ups,return_fedex,0.25,0.60,"UPS","FedEx")
마지막으로이 분석을 완료하기 위해 2000 년 이후의 시간에 따른 종가 추이를 플로팅 해 보겠습니다.이를 위해 저는 당면한 게시물 상단에 정의 된 가격 플로팅 기능을 사용합니다.
plottingPrices("Daily stock price development for UPS [black] and FedEx [orange]","Date","Daily stock closing price [USD]",ups,fedex,"black","orange")
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Leave a Reply