4차산업혁명의 일꾼/데이터 크롤링과 파이썬

금융인을 위한 파이썬 업무자동화 2주차

르무엘 2023. 3. 27. 20:25

DataFrame 만들기

Pandas : 데이터 분석

해외주식야후사이트: 

 

https://finance.yahoo.com/quote/AAPL?p=AAPL&.tsrc=fin-srch 

 

Apple Inc. (AAPL) Stock Price, News, Quote & History - Yahoo Finance

Find the latest Apple Inc. (AAPL) stock quote, history, news and other vital information to help you with your stock trading and investing.

finance.yahoo.com

 

코렙 활용하기 :  https://drive.google.com/

 

Google Drive: 로그인

이메일 또는 휴대전화

accounts.google.com

 

판다스, 넘피 라이브러리 설치 명령어 : !pip install pandas numpy

 

[DataFrame을 만들어서(df)  문서추가, 컬럼추가, 조건컬럼추가 ]

import pandas as pd
import numpy as np

data = {
    'name' :['철수','영희','동희','영수'],
    'age' : [15,12,20,35]
}

df = pd.DataFrame(data)


doc = {
    'name' : '세종',
    'age':23
}
df =df.append(doc,ignore_index=True)

df['city'] = ['서울','부산','서울','부산','부산']

df['is_adult'] = np.where(df['age']<20 , '청소년','성인')

df를 찍어보면 하기와 같이 나온다

최대값 - max() , 최소값 - min() , 평균 - mean()

describe  다보여주기(count,mean,std,min, max 등)

df['age'].max()
df['age'].min()
df['age'].mean()
df['age'].describe()

Quiz. 서울에 사는 사람들의 age 평균 구하기 

df[df['city']=='서울']['age'].mean()

 

종목데이터_2주차 엑셀파일을 읽어와서,  엑셀데이터를 소수점 2째짜리 까지 보여주고

어제보다 올랐고(change_rate >0) , per가 0보다 크고 ,

순이익은 시가총액을 per로 나눈게 순이익 df['earning'] = df['marketcap'] / df['per']    

 * per = 시가총액/순이익 = 주가/주당순이익 * 에서

주가 = per(주가수익비율) * eps(주당순이익) 

=>    df['close'] = df['per'] * df['eps']  

 

순이익, 종가를 추가하고 , date 컬럼을 없애고 , 

pbr < 1 , 시총 1조이상, per <20 을 추려보

import pandas as pd
import numpy as np

df=pd.read_excel('종목데이터_2주차.xlsx')

pd.options.display.float_format = '{:.2f}'.format

df.head()
df.tail(10)

cond = df['change_rate'] >0
df = df[cond]

cond = df['per'] >0
df = df[cond]

df['close'] = df['per'] * df['eps']
df['earning'] = df['marketcap'] / df['per']

del df['date']

cond = (df['pbr'] <1) & (df['marketcap'] > 1000000000000) & (df['per'] <20)
df = df[cond]

df.sort_values(by='marketcap', ascending=False)
#df.describe()
 
 
[설치]
 
!pip install urllib3==1.26.14 requests==2.25.1 yahooquery==2.3.0

 

[ 해외주식 전체사용법]

https://yahooquery.dpguthrie.com/guide/

 

Introduction - yahooquery

Introduction Classes The majority of the data available through the unofficial API can be obtained through the use of three classes: Ticker - Retrieve company-specific data Screener - Retrieve lists of stocks based on certain criteria Research - Retrieve p

yahooquery.dpguthrie.com

https://finance.yahoo.com/quote/AAPL?p=AAPL&.tsrc=fin-srch 

 

Apple Inc. (AAPL) Stock Price, News, Quote & History - Yahoo Finance

Find the latest Apple Inc. (AAPL) stock quote, history, news and other vital information to help you with your stock trading and investing.

finance.yahoo.com

 

[  Ticker의 여러 Module 사용법]

https://yahooquery.dpguthrie.com/guide/ticker/modules/

 

Modules - yahooquery

Modules The following data accessors, or modules, are grouped together because they're all retrieved from the same endpoint. The modules are given as query parameters to the API endpoint and as such can be combined to create convenient interfaces to retrie

yahooquery.dpguthrie.com

 

 

[yahoo finance 에서 볼 수 있는 거의 모든 정보 보기 가져오는 함수 만들고 불러오기]

from yahooquery import Ticker
import pandas as pd

pd.options.display.float_format = '{:.2f}'.format

def add_company(code):  
  company = Ticker(code)
  modules = 'summaryDetail assetProfile price financialData defaultKeyStatistics'
  all_data = company.get_modules(modules)

  name = all_data[code]['price']['shortName']
  industry = all_data[code]['assetProfile']['industry']
  marketcap = all_data[code]['price']['marketCap']  
  currentPrice = all_data[code]['financialData']['currentPrice']
  business  = all_data[code]['assetProfile']['longBusinessSummary']
  targetPrice  = all_data[code]['financialData']['targetMeanPrice']
  revenue = all_data[code]['financialData']['totalRevenue']

  per = all_data[code]['summaryDetail']['trailingPE']
  eps = all_data[code]['defaultKeyStatistics']['trailingEps']
  pbr = all_data[code]['defaultKeyStatistics']['priceToBook']
  
  df_earnings = pd.DataFrame.from_dict(company.earnings[code]['financialsChart']['yearly'])

  rev2021 = df_earnings.iloc[-2,1]
  rev2020 = df_earnings.iloc[-3,1]
  rev2019 = df_earnings.iloc[-4,1]

  ear2021 = df_earnings.iloc[-2,2]
  ear2020 = df_earnings.iloc[-3,2]
  ear2019 = df_earnings.iloc[-4,2]

  doc = {
    'code':code,
    'name':name,
    'industry':industry,
    'business':business,
    '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

df = pd.DataFrame()
codes = ['AAPL','ABNB','BIDU','FB','GOOG','MSFT','TSLA','PYPL','NFLX','NVDA']

for code in codes:
  try:
    row = add_company(code)
    df = df.append(row, ignore_index= True)
  except:
    print(f'error -{code}')

#df[df['per']<30].sort_values(by='eps',ascending=False)

new_df = df[['name','currentPrice','targetPrice']].copy()

new_df['gap'] = new_df['targetPrice'] / new_df['currentPrice'] -1

new_df.sort_values(by='gap', ascending=False)
#print(name, marketcap, industry, currentPrice, targetPrice, per, eps, pbr, revenue)

# 재무제표
#company.balance_sheet()

# 현금흐름표
#company.cash_flow()

#company.earnings['TSLA']['earningsChart'] 
# company.earnings['TSLA']['quarterly']

 

 

[yahooquery를 이용해서, Balance Sheet의 CashAndCashEquivalents를 아래와 같이 표기후 2022,2021 차이도 만들어 보세요]

from yahooquery import Ticker
import pandas as pd

company = Ticker('TSLA')

df = company.balance_sheet()
df = df[['CashAndCashEquivalents']].transpose()

df.columns = ['2022','2021','2020','2019']

data = company.price

df['name'] = data['TSLA']['shortName']

new_df = df[['name','2022','2021']].copy()

new_df['diff'] = new_df['2022'] - new_df['2021']
new_df.reset_index(drop=True)

 

1주차 : 네이버에서 뉴스 가져오는 함수 , 코랩 폴더에 저장 및 다운로드 ,네이버금융사진 저장
https://iamipro.tistory.com/231

 

스파르타코딩클럽 금융인을 위한 파이썬 업무자동화 1주차

스파르타코딩클럽 금융인을 위한 파이썬 업무자동화 1주차 import urllib.request import openpyxl wb = openpyxl.load_workbook('관리종목.xlsx') sheet = wb['종목'] new_rows = list(sheet.rows)[1:] for row in new_rows: print(row[0].val

iamipro.tistory.com

2주차 : 데이터프레임( 순이익, 종가, pbr<1, 시총1조이상, per<20) 그려보기 , 해외주식(야후쿼리) 정보 보기

3주차 : dart 상장/비상장 엑셀 추출, dart API 로 종목 정보 (증자,배당,직원정보,이사보수, 재무정보, 이익잉여금, 당기순이익, 지분율, 연봉 TOP5 등)
https://iamipro.tistory.com/233

 

금융인을 위한 파이썬 업무자동화 3주차

스파르타코딩클럽 금융인을 위한 파이썬 업무자동화 3주차 [다트 open api 발급] https://opendart.fss.or.kr/uat/uia/egovLoginUsr.do 전자공시 OPENDART 시스템 | 로그인 opendart.fss.or.kr [ 구글 드라이브 코랩 가기] h

iamipro.tistory.com

4주차 : 최적의 단기/장기 이동평균선 구하기
https://iamipro.tistory.com/234

 

금융인을 위한 파이썬 업무자동화 4주차

금융인을 위한 파이썬 업무자동화 4주차 https://drive.google.com/ Google Drive: 로그인 이메일 또는 휴대전화 accounts.google.com [라이브러리 설치 명령어 yfinance pandas-datareader finance-datareader !pip install yfinance

iamipro.tistory.com

5주차 : 변동성 돌파적략 최적값 k 구하기 , 월요일에 사서 금요일에 팔경우 수익나는 종목 보기
https://iamipro.tistory.com/235

 

금융인을 위한 파이썬 업무자동화 5주차

금융인을 위한 파이썬 업무자동화 5주차 https://drive.google.com/ Google Drive: 로그인 이메일 또는 휴대전화 accounts.google.com 전일 종가에서 금일 시작가에서 판다. [ 오르는 추세라 판단] [주가 가져오는

iamipro.tistory.com

 

LIST