: 파이썬에서 데이터를 쉽게 다룰 수 있게 해주는 라이브러리 / 데이터분석 필수사항
import pandas as pd
import numpy as np
: 판다스의 DataFrame 형식을 이용하면 표 형태로 데이터를 볼 수 있다
⇒ DataFrame은 “딕셔너리” 형태로 표현된 데이터를 표로 바꿔주는 역할
⇒ 맨 왼쪽은 “index”
data = {
'name' : ['영수','철수','영희','소희'],
'age' : [20,15,38,8]
}
df = pd.DataFrame(data)
1) 행 추가 (ignore_index=True 해야 밑에추가됨)
doc = {
'name':'세종',
'age':14,
}
df = df.append(doc,ignore_index=True)
2) column 추가
df['city'] = ['서울','부산','부산','서울','서울']
3) 특정 column 뽑기
⇒ 대괄호를 두번 해야 dataframe형식으로 반환된다!
df[['name','city']]
4) 원하는 조건 행 뽑기
df[df['age'] < 20]
5) 특정 행에서 뽑기(많이 사용!)
df.iloc[-1,0] # 마지막 행의 0번째 정보
df.iloc[0,0] # 첫 행의 0번째 정보
1) 열 정렬(나이로 ascending오름차순)
df.sort_values(by='age',ascending=True)
2) 조건맞는 열 추가
⇒ 조건에 맞는 데이터 넣을때 numpy를 쓴다!
df['is_adult'] = np.where(df['age'] > 20,'성인','청소년')
3) 평균/최대값/최소값/개수
df['age'].mean()
df['age'].max()
df['age'].min()
df['age'].count()
df['age'].describe()
4) 퀴즈-서울사는사람중 나이가장많은사람은 몇살?
df[df['city'] == '서울']['age'].max()
df[df['city'] == '서울'].sort_values(by='age',ascending=False).iloc[0,1]
pd.read_excel('종목데이터.xlsx')
df = pd.read_excel('종목데이터.xlsx')
처음5개 df.head()
끝5개 df.tail()
처음20개 df.head(20)
끝20개 df.tail(20)
소수점 둘째자리까지 보기
pd.options.display.float_format = '{:.2f}'.format
1) 어제 오른 종목들만 골라보기
df[df['change_rate'] > 0]
2) per가 0 인 종목들을 제거하기
df = df[df['per'] > 0]
3) 순이익, 종가를 추가하기
⇒ per = 시가총액/이익 = 주가/주당순이익
df['earning'] = df['marketcap'] / df['per']
df['close'] = df['per'] * df['eps']
4) date 컬럼을 없애기
del df['date']
5) pbr < 1 & 시총 1조 이상 & per < 20 을 추려보기
cond = (df['marketcap'] > 1000000000000) & (df['pbr'] < 1) & (df['per'] < 20)
df[cond]
⇒ 시총이 큰 순서대로 보기
df[cond].sort_values(by='marketcap', ascending=False)
⇒ 평균, 표준편차 등의 정보를 보기 (함께하기)
df[cond].describe()
!pip install yfinance
⇒ !느낌표 꼭 붙여주기
import yfinance as yf
company = yf.Ticker('TSLA')
company.info
* 전체 사용법 : https://pypi.org/project/yfinance/
1) 기본 정보 얻기(예) 회사명, 산업, 시가총액, 매출)
name = company.info['shortName']
industry = company.info['industry']
marketcap = company.info['marketCap']
revenue = company.info['totalRevenue']
print(name,industry,marketcap,revenue)
2) 재무제표에서 3년치 데이터 얻기(대차대조표, 현금흐름표, 기업 실적)
company.balance_sheet
company.cashflow
company.earnings
3) 그 외 정보(주주정보, 애널리스트 추천 등)
company.institutional_holders
company.recommendations
company.calendar
news = company.news
for n in news:
print(n['title'])
: yahoo finance UI와 코드상 항목별name과 상이해서 잘 비교해서 분석해야한다.
cash index만 df형태로 보기 :
company.balance_sheet.loc[['Cash']]
jpMorgan의 recommendations만 필터링해서 정보 보기
df = company.recommendations
cond = df['Firm'] == 'JP Morgam'
df[cond]
company = yf.Ticker('TSLA')
code = 'TSLA'
name = company.info['shortName']
industry = company.info['industry']
marketcap = company.info['marketCap']
summary = company.info['longBusinessSummary']
currentprice = company.info['currentPrice']
targetprice = company.info['targetMeanPrice']
per = company.info['trailingPE']
eps = company.info['trailingEps']
pbr = company.info['priceToBook']
print(code,name,industry,marketcap,summary,
currentprice,targetprice,per,eps,pbr)
⇒ 최근 3년 매출, 순이익 더하기
rev2021 = company.earnings.iloc[-1,0]
rev2020 = company.earnings.iloc[-2,0]
rev2019 = company.earnings.iloc[-3,0]
ear2021 = company.earnings.iloc[-1,1]
ear2020 = company.earnings.iloc[-2,1]
ear2019 = company.earnings.iloc[-3,1]
데이터를 모을 빈 DataFrame 만들기
정보 모아서 딕셔너리 변환
딕셔너리 형태로 append
doc = {
'code':code,
'name':name,
'industry':industry,
'bussiness':bussiness,
'marketCap':marketCap/1000,
'currentPrice':currentPrice,
'targetPrice':targetPrice,
'per':per,
'eps':eps,
'pbr':pbr,
'news':news,
'rev2021':rev2021/1000,
'rev2020':rev2020/1000,
'rev2019':rev2019/1000,
'ear2021':ear2021/1000,
'ear2020':ear2020/1000,
'ear2019':ear2019/1000,
}
df.append(doc,ignore_index = True)
전체 데이터 모으는 함수!
def add_company(code):
company = yf.Ticker(code)
name = company.info['shortName']
industry = company.info['industry']
bussiness = company.info['longBusinessSummary']
marketCap= company.info['marketCap']
currentPrice= company.info['currentPrice']
targetPrice= company.info['targetMeanPrice']
per = company.info['forwardPE']
eps = company.info['forwardEps']
pbr = company.info['priceToBook']
rev2021 = company.earnings.iloc[-1,0]
rev2020 = company.earnings.iloc[-2,0]
rev2019 = company.earnings.iloc[-3,0]
ear2021 = company.earnings.iloc[-1,1]
ear2020 = company.earnings.iloc[-2,1]
ear2019 = company.earnings.iloc[-3,1]
doc = {
'code':code,
'name':name,
'industry':industry,
'bussiness':bussiness,
'marketCap':marketCap/1000,
'currentPrice':currentPrice,
'targetPrice':targetPrice,
'per':per,
'eps':eps,
'pbr':pbr,
'rev2021':rev2021/1000,
'rev2020':rev2020/1000,
'rev2019':rev2019/1000,
'ear2021':ear2021/1000,
'ear2020':ear2020/1000,
'ear2019':ear2019/1000,
}
return doc
분석하기2
df = pd.DataFrame()
codes = ['AAPL','ABNB','BIDU','FB','GOOG','MSFT','TSLA','PYPL','NFLX','NVDA']
for code in codes:
print(code)
row = add_company(code)
df = df.append(row, ignore_index = True)
df
이렇게만 입력하면 에러뜨는데, 특정 코드에 데이터가 없는 경우 에러가 뜸.
=> 에러처리 해줘야함 (아래 코드) : try except 구문!
df = pd.DataFrame()
codes = ['AAPL','ABNB','BIDU','FB','GOOG','MSFT','TSLA','PYPL','NFLX','NVDA']
for code in codes:
print(code)
try:
row = add_company(code)
df = df.append(row, ignore_index = True)
except:
print(f'error - {code}')
df
: 관심 종목을 매일 자동으로 모아서, 분석하고 결과까지 내어줄 수 있다!
1) eps 순서대로 정렬해보기
df.sort_values(by='eps',ascending=False)
2) 특정 per 이하만 보기
df[df['per'] < 30].sort_values(by='per',ascending=False)
3) 현재가격 - 1년 후 가격의 비율 차이가 큰 종목들을 추려내기
df[['code','name','currentPrice','targetPrice']]
new_df = df[['code','name','currentPrice','targetPrice']].copy()
new_df['gap'] = new_df['targetPrice'] / new_df['currentPrice'] -1
new_df.sort_values(by='gap',ascending=False)
4) 3년 연속 순수익이 오른 기업을 표기하기
import numpy as np
new_df2 = df[['code','name','ear2021','ear2020','ear2019']].copy()
cond = (new_df2['ear2021'] > new_df2['ear2020']) & (new_df2['ear2020'] > new_df2['ear2019'])
new_df2['is_target'] = np.where(cond,'O','X')
new_df2[new_df2['is_target'] == 'O']
현재가격 - 1년 후 가격의 비율 차이가 큰 종목들을 추려내기
new_df['gap'] = new_df['targetPrice'] / new_df['currentPrice'] -1
newdf = df[['code','name','currentPrice','targetPrice']].copy()
원본 필터링 후 조작하려면 .copy() _추가해주기!
ox 표기할 열 만들기
new_df['is_target'] = np.where(cond,'O','X')
index 숫자찍히도록 0부터시작 초기화(?)
df.reset_index(drop=True)
#소수점 둘째자리까지 표기하기
pd.options.display.float_format = '{:.2f}'.format
#과제
company = yf.Ticker('AAPL')
df = company.balance_sheet.loc[['Cash']]
df.columns = ['2021','2020','2019','2018']
df['name'] = company.info['shortName']
new_df = df[['name','2021','2020']].copy()
new_df['diff'] = new_df['2021'] - new_df['2020']
new_df.reset_index(drop=True)