파이썬/파이썬(python) 중급

[36-1] 주가 뉴스 API 실습하기, abs() 절댓값 함수

Olivia-BlackCherry 2022. 9. 29. 06:55

1. 주가 확인할 수 있는 API

https://www.alphavantage.co/#page-top

 

Free Stock APIs in JSON & Excel | Alpha Vantage

Copyright © Alpha Vantage Inc. 2017-2022 | Site last updated: September 24, 2022 | Boston, Massachusetts

www.alphavantage.co

<미션: 테슬라 주식의 어제 마지막 가격(종가)와 오늘 마지막 가격 확인하기>

STOCK = "TSLA"
COMPANY_NAME = "Tesla Inc"

## STEP 1: Use https://www.alphavantage.co

URL = "https://www.alphavantage.co/query"
API_KEY = os.environ.get("STOCK_API")
parameters = {
    "function" : "TIME_SERIES_DAILY",
    "symbol": STOCK,
    "outputsize": "compact",
    "apikey": API_KEY
}
response = requests.get(URL, params= parameters)
response.raise_for_status()
data = response.json()
day_data = data['Time Series (Daily)']
# print(data)

df = pandas.DataFrame(day_data)
# print(df)
today_price=float(df.loc['4. close'][0])
yesterday_price = float(df.loc['4. close'][1])
print(today_price, yesterday_price)
print(type(today_price))
ratio_price = (today_price-yesterday_price)/yesterday_price * 100

 

 

<미션: 관련 뉴스를 가져오기>

https://newsapi.org

 

News API – Search News and Blog Articles on the Web

“Ascender AI has a mission to apply AI to the media, and NewsAPI is one of our most valuable resources. Ascender is redefining how users interact with complex information, and the NewsAPI feed is an essential showcase for our technologies.” Braddock Ga

newsapi.org

today = datetime.datetime.today().date()
print(today)

new_URL ="https://newsapi.org/v2/everything"
NEWS_API=os.environ.get("NEWS_API")
# print(NEWS_API)
parameters = {
    "q": COMPANY_NAME,
    "apiKey":NEWS_API,
    "sortBy": "popularity",
    "to": "today"
}
response = requests.get(new_URL, params=parameters)
response.raise_for_status()
news_data = response.json()["articles"]
# print(news_data)
contents_title = [(content["title"], content["url"]) for content in news_data]
contents = [content["content"] for content in news_data]

 

 

<미션: 어제 종가와 비교하여 오늘 종가가 1% 이상 차이가 나는지 확인하기>

if ratio_price <0:
    ratio_price*=-1
if ratio_price>1:
    print(contents_title[0:4])
else:
    print("Normal")

또는

abs() 함수 사용

abs()는 음수, 양수 값과 관련없이 절대값을 출력한다.

if abs(ratio_price)>1:
    print(contents_title[0:4])
else:
    print("Normal")