주식시장 뉴스 알림

JOOYEUN SEO·2024년 9월 18일

100 Days of Python

목록 보기
36/76
post-thumbnail

🗂️ Day36 프로젝트 : 주식시장 뉴스 알림

관심 있는 주식 시세를 모니터링하여 관련 뉴스를 가져오고 SMS로 알려주는 프로그램

◇ 주가 변동 확인하기

🔍 유의 사항

  • TSLA Stick Price로 차트 확인
  • alphavantage - Stock Market Data API
    • 이메일로 무료 API 키 생성
    • 현재 기준 무료 키로 하루에 25번의 리퀘스트까지만 가능
  • 변동 확인하기
    1. 어제의 폐장가와 엊그제의 폐장가를 비교
    2. 차이를 비율로 계산
    3. 5% 이상의 비율로 차이날 경우 뉴스를 가져와야 한다
  • abs( n ) : 숫자 n의 절대값을 반환하는 함수

⌨️ main.py

import requests
import os

STOCK = "TSLA"
COMPANY_NAME = "Tesla Inc"

STOCK_API_KEY = os.environ.get("STOCK_API_KEY")

url = (f'https://www.alphavantage.co/query?'
       f'function=TIME_SERIES_DAILY&symbol={STOCK}&apikey={STOCK_API_KEY}')
r = requests.get(url)
data = r.json()["Time Series (Daily)"]

# 폐장 가격만 모은 리스트 생성(어제와 엊그제만 나타나도록 슬라이싱)
closing_price_list = [value["4. close"] for (key, value) in test_data.items()][:2]
yesterday_closing_price = float(closing_price_list[0])
day_before_yesterday_closing_price = float(closing_price_list[1])
# 가격 차이 계산
difference = yesterday_closing_price - day_before_yesterday_closing_price
# 가격 차이의 절대값으로 비율 차이 계산
percentage_gap = abs(difference) / yesterday_closing_price * 100

# 테스트 때는 출력을 위해 5대신 0을 넣어서 진행
if percentage_gap > 5:
	print("Get News")
Get News

◇ 뉴스 기사 가져오기

🔍 유의 사항

  • 슬라이싱으로 3개의 기사만 가져오기

⌨️ main.py

import requests
import os

STOCK = "TSLA"
COMPANY_NAME = "Tesla Inc"

STOCK_API_KEY = os.environ.get("STOCK_API_KEY")
NEWS_API_KEY = os.environ.get("NEWS_API_KEY")# 테스트 때는 출력을 위해 5대신 0을 넣어서 진행
if percentage_gap > 5:
    news_parameters = {
        "q": COMPANY_NAME,
        "apiKey": NEWS_API_KEY
    }
    news_endpoint = 'https://newsapi.org/v2/everything'

    news_response = requests.get(news_endpoint, params=news_parameters)
    articles = news_response.json()['articles']
    three_articles = articles[:3]

◇ SMS 메시지 보내기

🔍 유의 사항

  • 원하는 출력
    TSLA: 🔺0.48%
    Headline: 2 killed in fiery Tesla crash in White Plains, NY
    Brief: WHITE PLAINS, N.Y. (PIX11) – Two people died in a fiery crash involving a Tesla in White Plains on Monday. The crash happened on Battle Avenue near Waldo...
    TSLA: 🔺0.48%
    Headline: Which EVs Can Charge at a Tesla Supercharger?
    Brief: Many of Tesla's Superchargers are now open to electric cars from other automakers, but NACS adapters are slow to arriveThe 2025 Hyundai Ioniq 5 will become...
    TSLA: 🔺0.48%
    Headline: Fisker owners who paid up to $70,000 for malfunctioning EVs are told they might have to pay for recall repairs, too
    Brief: Fisker said that owners would have to pay the repair costs for two outstanding recalls facing its Ocean electric car.
  • 테스트는 1개의 기사로만 진행

⌨️ main.py

import requests
import os
from twilio.rest import Client

STOCK = "TSLA"
COMPANY_NAME = "Tesla Inc"

STOCK_API_KEY = os.environ.get("STOCK_API_KEY")
NEWS_API_KEY = os.environ.get("NEWS_API_KEY")

TWILIO_SID = os.environ.get("TWILIO_SID")
TWILIO_AUTH_TOKEN = os.environ.get("TWILIO_AUTH_TOKEN")
TWILIO_VIRTUAL_PHONE_NUMBER = os.environ.get("TWILIO_PHONE_NUMBER")
MY_PHONE_NUMBER = os.environ.get("MY_PHONE_NUMBER")


url = (f'https://www.alphavantage.co/query?'
       f'function=TIME_SERIES_DAILY&symbol={STOCK}&apikey={STOCK_API_KEY}')
r = requests.get(url)
data = r.json()["Time Series (Daily)"]

closing_price_list = [value["4. close"] for (key, value) in data.items()][:2]
yesterday_closing_price = float(closing_price_list[0])
day_before_yesterday_closing_price = float(closing_price_list[1])

difference = yesterday_closing_price - day_before_yesterday_closing_price
if difference > 0:
    up_down = "🔺"
else:
    up_down = "🔻"

percentage_gap = abs(difference) / yesterday_closing_price * 100

# 테스트 때는 출력을 위해 5대신 0을 넣어서 진행
if percentage_gap > 5:
    news_parameters = {
        "q": COMPANY_NAME,
        "apiKey": NEWS_API_KEY
    }
    news_endpoint = 'https://newsapi.org/v2/everything'

    news_response = requests.get(news_endpoint, params=news_parameters)
    articles = news_response.json()['articles']
    three_articles = articles[:3]

    formatted_articles = [
        (f"{STOCK}: {up_down}{round(percentage_gap, 2)}%\n"
         f"Headline: {article['title']}\n"
         f"Brief: {article['description']}") for article in three_articles
    ]

    # Client 클래스로부터 객체 생성
    client = Client(TWILIO_SID, TWILIO_AUTH_TOKEN)

    # SMS 3개 보내기
    for article in formatted_articles:
        message = client.messages.create(
            body=article,
            from_=TWILIO_VIRTUAL_PHONE_NUMBER,
            to=MY_PHONE_NUMBER,
        )




▷ Angela Yu, [Python 부트캠프 : 100개의 프로젝트로 Python 개발 완전 정복], Udemy, https://www.udemy.com/course/best-100-days-python/?couponCode=ST3MT72524

0개의 댓글