Day 036

AWESOMee·2022년 3월 8일
0

Udemy Python Bootcamp

목록 보기
36/64
post-thumbnail

Udemy Python Bootcamp Day 036

Stock Trading News Alert Project

what i wrote

import requests
import datetime as dt
from twilio.rest import Client

STOCK_NAME = "TSLA"
COMPANY_NAME = "Tesla Inc"

STOCK_ENDPOINT = "https://www.alphavantage.co/query"
NEWS_ENDPOINT = "https://newsapi.org/v2/everything"

    ## STEP 1: Use https://www.alphavantage.co/documentation/#daily
# When stock price increase/decreases by 5% between yesterday and the day before yesterday then print("Get News").
ALPHA_API = "**********"

stock_parameters = {
    "function": "TIME_SERIES_DAILY",
    "symbol": STOCK_NAME,
    "apikey": ALPHA_API
}
#TODO 1. - Get yesterday's closing stock price. Hint: You can perform list comprehensions on Python dictionaries.
stock_response = requests.get(url=STOCK_ENDPOINT, params=stock_parameters)
stock_response.raise_for_status()
stock_data = stock_response.json()["Time Series (Daily)"]
stock_data_list = [value["4. close"] for (key, value) in stock_data.items()]
yesterday_price = float(stock_data_list[0])

#TODO 2. - Get the day before yesterday's closing stock price
the_day_before_price = float(stock_data_list[1])

#TODO 3. - Find the positive difference between 1 and 2. e.g. 40 - 20 = -20, but the positive difference is 20. Hint: https://www.w3schools.com/python/ref_func_abs.asp
origin_difference = round(yesterday_price - the_day_before_price, 2)
difference = abs(origin_difference)
if origin_difference < 0:
    origin_difference = f"🔻{origin_difference}"
else:
    origin_difference = f"🔺{origin_difference}"


#TODO 4. - Work out the percentage difference in price between closing price yesterday and closing price the day before yesterday.
the_percentage = round(difference / the_day_before_price * 100, 2)

#TODO 5. - If TODO4 percentage is greater than 5 then print("Get News").

# if the_percentage > 5:
#     print("Get News")


    ## STEP 2: https://newsapi.org/ 
    # Instead of printing ("Get News"), actually get the first 3 news pieces for the COMPANY_NAME. 
NEWS_API = "**********"
today = dt.date.today()
news_parameters = {
    "q": COMPANY_NAME,
    "from": today,
    "sortBy": "popularity",
    "apiKey": NEWS_API
}
#TODO 6. - Instead of printing ("Get News"), use the News API to get articles related to the COMPANY_NAME.
news_response = requests.get(url=NEWS_ENDPOINT, params=news_parameters)
news_response.raise_for_status()

#TODO 7. - Use Python slice operator to create a list that contains the first 3 articles. Hint: https://stackoverflow.com/questions/509211/understanding-slice-notation
news_data = news_response.json()["articles"][:3]

    ## STEP 3: Use twilio.com/docs/sms/quickstart/python
    #to send a separate message with each article's title and description to your phone number. 
account_sid = "**********"
auth_token = "**********"
TWILIO_NUM = "**********"
MY_NUMBER = "**********"
#TODO 8. - Create a new list of the first 3 article's headline and description using list comprehension.
article_list = [(item["title"], item["description"]) for item in news_data]

#TODO 9. - Send each article as a separate message via Twilio.

if the_percentage > 5:
    for article in article_list:
        client = Client(account_sid, auth_token)
        message = client.messages.create(
            body=f"{STOCK_NAME}: {origin_difference}%\nHeadlines: {article[0]}\nBrief: {article[1]}",
            from_=TWILIO_NUM,
            to=MY_NUMBER
        )
        print(message.status)


#Optional TODO: Format the message like this: 
"""
TSLA: 🔺2%
Headline: Were Hedge Funds Right About Piling Into Tesla Inc. (TSLA)?. 
Brief: We at Insider Monkey have gone over 821 13F filings that hedge funds and prominent investors are required to file by the SEC The 13F filings show the funds' and investors' portfolio positions as of March 31st, near the height of the coronavirus market crash.
or
"TSLA: 🔻5%
Headline: Were Hedge Funds Right About Piling Into Tesla Inc. (TSLA)?. 
Brief: We at Insider Monkey have gone over 821 13F filings that hedge funds and prominent investors are required to file by the SEC The 13F filings show the funds' and investors' portfolio positions as of March 31st, near the height of the coronavirus market crash.
"""

변수 이름은 물론 조금 정리는 안되어 보이지만 무튼 솔루션 하나도 안보고 내가 만들어냄 ㅠㅠ
물론 블로그 정리해놓은 것은 조금 봤어..

#output


Solution

Stock Price

stock_params = {
    "function": "TIME_SERIES_DAILY",
    "symbol": STOCK_NAME,
    "apikey": STOCK_API_KEY
}

response = requests.get(url=STOCK_ENDPOINT, params=stock_params)
response.raise_for_status()
data = response.json()["Time Series (Daily)"]
data_list = [value for (key, value) in data.items()]
yesterday_data = data_list[0]
yesterday_closing_price = yesterday_data["4. close"]

day_before_yesterday_data = data_list[1]
day_before_yesterday_closing_data = day_before_yesterday_data["4. close"]

difference = abs(float(yesterday_closing_price) - float(day_before_yesterday_closing_data))

diff_percent = difference / float(yesterday_closing_price) * 100  
# 여기서 왜 day_before_yesterday가 아니라 yesterday로 나누는 지는 모르겠지만..

if diff_percent > 5:
    print("Get News")

News

if diff_percent > 5:
    news_params = {
        "apiKey": NEWS_API_KEY,
        "qInTitle": COMPANY_NAME,
    }
    news_response = requests.get(NEWS_ENDPOINT, params=news_params)
    news_response.raise_for_status()

    articles = news_response.json()["articles"]
    three_articles = articles[:3]

solution 볼때마다 느끼는 건 이렇게까지 간단해도 이게 된다고..? 라는 거임

SMS

    formatted_articles = [f"Headlines: {article['title']}. \nBrief: {article['description']}" for article in three_articles]

    client = Client(TWILIO_SID, TWILIO_AUTH_TOKEN)

    for article in formatted_articles:
        message = client.messages.create(
            body=article,
            from_=TWILIO_NUM,
            to=MY_NUMBER,
        )

FINAL

import requests
from twilio.rest import Client

STOCK_NAME = "TSLA"
COMPANY_NAME = "Tesla Inc"

STOCK_ENDPOINT = "https://www.alphavantage.co/query"
NEWS_ENDPOINT = "https://newsapi.org/v2/everything"

STOCK_API_KEY = "**************"
NEWS_API_KEY = "**************"
TWILIO_SID = "**************"
TWILIO_AUTH_TOKEN = "**************"
TWILIO_NUM = "+********"
MY_NUMBER = "+********"

stock_params = {
    "function": "TIME_SERIES_DAILY",
    "symbol": STOCK_NAME,
    "apikey": STOCK_API_KEY
}

response = requests.get(STOCK_ENDPOINT, params=stock_params)
response.raise_for_status()
data = response.json()["Time Series (Daily)"]
data_list = [value for (key, value) in data.items()]
yesterday_data = data_list[0]
yesterday_closing_price = yesterday_data["4. close"]

day_before_yesterday_data = data_list[1]
day_before_yesterday_closing_data = day_before_yesterday_data["4. close"]

difference = float(yesterday_closing_price) - float(day_before_yesterday_closing_data)
up_down = None
if difference > 0:
    up_down = "🔺"
else:
    up_down = "🔻"

diff_percent = round((difference / float(yesterday_closing_price)) * 100)

if abs(diff_percent) > 5:
    news_params = {
        "apiKey": NEWS_API_KEY,
        "qInTitle": COMPANY_NAME,
    }
    news_response = requests.get(NEWS_ENDPOINT, params=news_params)
    news_response.raise_for_status()

    articles = news_response.json()["articles"]
    three_articles = articles[:3]

    formatted_articles = [f"{STOCK_NAME}: {up_down}{diff_percent}%\nHeadlines: {article['title']}. \nBrief: {article['description']}" for article in three_articles]

    client = Client(TWILIO_SID, TWILIO_AUTH_TOKEN)

    for article in formatted_articles:
        message = client.messages.create(
            body=article,
            from_=TWILIO_NUM,
            to=MY_NUMBER,
        )
profile
개발을 배우는 듯 하면서도

0개의 댓글