這部份要實作股票通知功能如下:
import requests
import time
# 要追蹤的股票代號 McDonald's Corporation(MCD)
stock_code = 'MCD'
def get_stock_price(stock_code):
# 使用 Alpha Vantage API 取得股票資訊
api_key = 'your_api_key'
url = f'https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={stock_code}&apikey={api_key}'
response = requests.get(url)
data = response.json()
# 解析股票資訊
stock_price = data['Global Quote']['05. price']
stock_change = data['Global Quote']['09. change']
stock_percent_change = data['Global Quote']['10. change percent']
return stock_price, stock_change, stock_percent_change
while True:
# 取得股票資訊
stock_price, stock_change, stock_percent_change = get_stock_price(stock_code)
# 判斷是否需要提醒
if float(stock_percent_change.strip('%')) > 5:
print(f'{stock_code}: 股價上漲超過5%!')
elif float(stock_percent_change.strip('%')) < -5:
print(f'{stock_code}: 股價下跌超過5%!')
# 更新間隔,這裡設定為 60 秒
time.sleep(60)