T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 36 天:多 API 组合:股票异动新闻提醒

这是「Python 100 天」系列第 36 天的学习笔记:多 API 组合:股票异动新闻提醒。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

查某只股票最近两天的收盘价,如果涨跌幅超过 5%,就去新闻 API 拉 3 条相关新闻,拼成一条消息发到 Telegram。README 知识点:股票价格 API、新闻 API、Telegram 推送。

一、多个 API 串联

这是真实项目最常见的形态:A 接口的输出决定 B 接口要不要调。

1
2
拉股价 → 算涨跌幅 → 超过阈值?→ 拉新闻 → 发消息
↘ 没超过 → 什么都不做

判断放在中间,能省掉大量无谓的请求(也就省了配额)。

二、涨跌幅的计算

1
performance = abs(current - previous) / previous * 100
  • abs() 取绝对值,因为涨跌都要报警;
  • 先除后乘 100,注意整数除法的坑(Python 3 的 / 是真除法,没问题)。

三、遍历字典的前几个键

1
for _, date in zip(range(3), stock_data['Time Series (Daily)']):

zip 把两个可迭代对象"拉链式"配对,range(3) 保证只取前 3 个。字典直接迭代得到的是键(日期字符串),顺序是插入顺序(API 返回时通常已按日期倒序)。

这段其实等价于更简单的:

1
dates = list(stock_data["Time Series (Daily)"])[:3]

代码全文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# ============================================================
# day36/main.py —— 股票异动 + 新闻推送
# 作用:用 Alpha Vantage 取 TSLA 最近两天的收盘价,算涨跌幅;
# 若波动 ≥5%,就去 NewsAPI 抓 3 条相关新闻,拼成一条消息发到 Telegram。
# 知识点:两个 API 串联、zip(range(3), dict) 同时按索引取键、字符串转 float、
# 自定义函数算百分比、三元/if-else 选 emoji、list + join 拼多行文本
# 运行方式:填好三个密钥后 cd day36 再 python main.py
# ============================================================

import requests


STOCK_NAME = "TSLA"
# Alpha Vantage 的“每日时间序列”接口。
STOCK_ENDPOINT = "https://www.alphavantage.co/query"
# NewsAPI 的“搜索全部新闻”接口。
NEWS_ENDPOINT = "https://newsapi.org/v2/everything"
# 两个密钥都写死成星号占位符 —— 这只是为了能公开源码,真实使用要填自己的 key。
ALPHA_VANTAGE_APIKEY = "****************"
NEWS_APIKEY = "********************************"


# 发 Telegram 消息。参数 bot_message:文本内容;返回接口响应的 JSON。
def telegram_bot_send_text(bot_message):
bot_token = "**********************************************"
bot_chatID = "**********"
# 三行用 续行拼成一个长 URL;parse_mode=Markdown 允许消息里用 *加粗* 等语法。
send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID
+ '&parse_mode=Markdown&text=' + bot_message
bot_response = requests.get(send_text)
return bot_response.json()


# 算涨跌幅百分比。参数 current:今天价,previous:昨天价;返回百分比数值。
def get_change(current, previous):
# ⚠ 这里逻辑有问题:价格没变应该返回 0%,返回 100.0 会让“没波动”被当成暴涨。
if current == previous:
return 100.0
try:
# 计算步骤:差值绝对值 ÷ 昨收 → 保留 5 位小数 → ×100 变成百分数。
# 注意 round 作用在比值上(精度约十万分之一),不是作用在最终百分比上。
performance = round(abs(current - previous) / previous, 5) * 100.0
# ⚠ 调试用的 print 留在库里,会导致这个函数被调用两次就打印两次。
print(performance)
return performance
# previous 为 0 时除零 —— 这里兜住并返回 0。
except ZeroDivisionError:
return 0


# Alpha Vantage 参数:function 指定接口名,symbol 指定股票代码,apikey 鉴权。
alpha_vantage_parameters = {
"function": "TIME_SERIES_DAILY",
"symbol": STOCK_NAME,
"apikey": ALPHA_VANTAGE_APIKEY,
}

# NewsAPI 参数:q 是搜索关键词,pageSize 限制条数,apiKey 鉴权(注意是 apiKey 不是 apikey)。
news_api_parameters = {
"q": f"{STOCK_NAME} Market Update",
"pageSize": 3,
"apiKey": NEWS_APIKEY,
}

alpha_vantage_response = requests.get(STOCK_ENDPOINT, params=alpha_vantage_parameters)
# 密钥错误/额度用尽时 Alpha Vantage 返回 200 + 一段提示文字,所以光靠这行不一定能发现,
# 还要检查返回里有没有 "Time Series (Daily)" 这个键。
alpha_vantage_response.raise_for_status()
stock_data = alpha_vantage_response.json()

news_api_response = requests.get(NEWS_ENDPOINT, params=news_api_parameters)
news_api_response.raise_for_status()
news_data = news_api_response.json()

closing_prices = []
# stock_data['Time Series (Daily)'] 是 {日期: {字段: 值}} 的字典,日期按“新→旧”排列。
# 遍历字典默认拿到的是键(日期字符串),所以要取 [date] 才能进到当天的数据。
# zip(range(3), 字典):把 0,1,2 和前三天的日期配成对,循环里 _ 是序号(不用)。
for _, date in zip(range(3), stock_data['Time Series (Daily)']):
# "4. close" 是 Alpha Vantage 固定的字段名(带 "4. " 前缀和空格),别写错。
closing_prices.append(stock_data['Time Series (Daily)'][date]['4. close'])
# 列表里是字符串(如 "101.5000"),比较大小前必须 float()。
yd_price = float(closing_prices[0])
dyd_price = float(closing_prices[1])

difference = yd_price - dyd_price
up_down = None
if difference > 0:
up_down = "🔺"
else:
up_down = "🔻"

# 只有波动 ≥ 5% 才推送(避免天天打扰)。
if get_change(yd_price, dyd_price) >= 5:
# ⚠ 这三个列表写在循环里,每轮都新建一次,等于每次都从头拼——
# 功能上能跑(每次只发一条),但更清楚的做法是把列表放到循环外面。
for article in range(3):
market_performance = []
news_headlines = []
news_description = []
# f-string 里再调一次 get_change(),所以这个百分比其实被算了第二遍。
market_performance.append(f"{STOCK_NAME}: {up_down} {get_change(yd_price, dyd_price)}% ")
news_headlines.append(f"Headline: {news_data['articles'][article]['title']}")
news_description.append(f"Description: {news_data['articles'][article]['description']}")
# 列表相加 = 拼接;得到三段文字组成的列表。
news = (market_performance + news_headlines + news_description)
# "n".join(列表):用换行把列表元素连成一个多行字符串。
joined_string = "n".join(news)
# 每轮发一条,共 3 条消息(更合理的是循环外拼好再发一次)。
telegram_bot_send_text(f"{joined_string}")

代码走读

  1. get_change(current, previous):返回百分比。注意 round(x, 5) * 100 先保留 5 位小数再乘 100——顺序反了会丢精度。
  2. 两个参数字典分别是 Alpha Vantage(股价)和 NewsAPI(新闻)的请求参数。
  3. 两次 requests.get + raise_for_status()。
  4. 取前 3 个交易日的收盘价,yd_price 是昨天、dyd_price 是前天(命名有点反直觉:yd = yesterday,dyd = day before yesterday)。
  5. difference > 0 决定用 🔺 还是 🔻。
  6. 涨跌幅 ≥ 5% 时,循环 3 次拼消息并发送。

这份代码的问题

(1) current == previous 时返回 100.0

1
2
if current == previous:
return 100.0

价格没变,涨跌幅应该是 0。返回 100 会让"没变化"被当成"暴涨",直接误报。这是一个典型的"边界条件写错"。

(2) 三个列表在循环里反复创建

1
2
3
4
for article in range(3):
market_performance = []
news_headlines = []
news_description = []

每个文章都新建空列表再 append 一个元素,等价于直接拼字符串。写在循环外更合理(市场表现只需要一条)。

(3) get_change 被调用两次

一次判断、一次拼消息,每次都 print,控制台会重复输出。

(4) 密钥硬编码

文件里能看到 ALPHA_VANTAGE_APIKEY = "****************"(作者已打码)。真实项目用 os.environ。

(5) 新闻查询词

q=f"{STOCK_NAME} Market Update" 把股票代码和"Market Update"当成一个短语搜,结果常常很少。应该用 q=TSLA 加 language=en、sortBy=publishedAt。

运行结果

1
2
3
TSLA: 🔺 5.23%
Headline: Tesla shares jump after earnings beat
Description: ...

易错点

  1. Alpha Vantage 免费额度只有 25 次/天,调试时容易用完,返回的是提示信息而不是数据(Note 字段),此时 stock_data['Time Series (Daily)'] 直接 KeyError。
  2. float() 转换:API 返回的价格是字符串 "245.1300"。
  3. 新闻可能不足 3 条:articles[2] 会 IndexError。
  4. Telegram 消息长度上限 4096 字符:拼太多会被截断。

动手改

  • 修掉 current == previous 返回 0。
  • 加"接口返回异常"的判断(检查 "Note" 或 "Error Message" 键)。
  • 把 3 条新闻合成一条消息,只发一次,而不是发 3 条。

源文件逐个讲解

2 个文件:main.py(75 行)、README.md(8 行)。

main.py(75 行)

结构:两个 API 常量 → 两个函数 → 两组参数 → 两次请求 → 一次比较 → 循环发消息

1
2
3
4
5
STOCK_NAME = "TSLA"
STOCK_ENDPOINT = "https://www.alphavantage.co/query"
NEWS_ENDPOINT = "https://newsapi.org/v2/everything"
ALPHA_VANTAGE_APIKEY = "****************"
NEWS_APIKEY = "********************************"

两个密钥都被星号遮掉了——作者提交前手动打码。这比硬编码真实密钥好,但也意味着这份代码原样跑不通,必须自己申请。

(1)get_change():涨跌幅计算

1
2
3
4
5
6
7
8
9
def get_change(current, previous):
if current == previous:
return 100.0
try:
performance = round(abs(current - previous) / previous, 5) * 100.0
print(performance)
return performance
except ZeroDivisionError:
return 0

这个函数有两个逻辑错误:

① 价格相等时返回 100.0

1
2
if current == previous:
return 100.0

价格没变,涨跌幅应该是 0%。返回 100 会让主逻辑 >= 5 成立,平盘也发新闻。

② round(..., 5) 只保留 5 位小数,然后才乘 100

1
round(abs(current - previous) / previous, 5) * 100.0

round 作用在比例上(比如 0.0123456 → 0.01235),再乘 100 得 1.235——精度只剩 3 位小数。想保留百分比的小数位,应该 round(ratio * 100, 2)。

③ try/except ZeroDivisionError 是死代码

上面已经 if current == previous 挡住了相等,previous 为 0 时 current == previous 也成立(除非 current 也是 0),直接返回了。这个 except 永远进不去。

④ print(performance) 是调试残留:函数里不该有输出。

(2)取最近两天收盘价

1
2
3
4
5
closing_prices = []
for _, date in zip(range(3), stock_data['Time Series (Daily)']):
closing_prices.append(stock_data['Time Series (Daily)'][date]['4. close'])
yd_price = float(closing_prices[0])
dyd_price = float(closing_prices[1])

zip(range(3), 字典) 只遍历前 3 个键(Alpha Vantage 默认返回最近 100 天)。_ 是丢弃的序号。

变量名 yd_price / dyd_price 大概是「yesterday」和「day before yesterday」的缩写——命名很差,读代码时极易混淆。应该叫 latest_close / prev_close。

float(...) 是必须的:API 返回的价格是字符串 "180.5500"。

(3)调两次 API

1
2
3
4
5
6
7
alpha_vantage_response = requests.get(STOCK_ENDPOINT, params=alpha_vantage_parameters)
alpha_vantage_response.raise_for_status()
stock_data = alpha_vantage_response.json()

news_api_response = requests.get(NEWS_ENDPOINT, params=news_api_parameters)
news_api_response.raise_for_status()
news_data = news_api_response.json()

注意新闻 API 的 q 参数:

1
"q": f"{STOCK_NAME} Market Update",

它会搜「TSLA Market Update」这个短语——NewsAPI 的 q 支持布尔语法,空格分隔默认是 AND。所以搜的是「同时含 TSLA 和 Market 和 Update」的文章,可能一条都搜不到。更合理的是 q="TSLA" 或 q="Tesla"。

(4)拼消息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
difference = yd_price - dyd_price
up_down = None
if difference > 0:
up_down = "🔺"
else:
up_down = "🔻"

if get_change(yd_price, dyd_price) >= 5:
for article in range(3):
market_performance = []
news_headlines = []
news_description = []
market_performance.append(f"{STOCK_NAME}: {up_down} {get_change(yd_price, dyd_price)}% ")
news_headlines.append(f"Headline: {news_data['articles'][article]['title']}")
news_description.append(f"Description: {news_data['articles'][article]['description']}")
news = (market_performance + news_headlines + news_description)
joined_string = "n".join(news)
telegram_bot_send_text(f"{joined_string}")

这段是全天最乱的:

  1. 三个列表各装一个元素(market_performance、news_headlines、news_description)——完全没必要,直接 "n".join([..., ..., ...]) 就行。
  2. get_change() 被调用三次(if 一次、消息里两次),每次还 print 一遍。
  3. up_down 用 None 初始化,然后 if/else 都赋值——up_down = "🔺" if difference > 0 else "🔻" 一行搞定。
  4. 三个列表在 for 循环内部重建,每轮都清空,浪费。
  5. 发 3 条独立消息(每篇文章一条),不是一条汇总消息——手机上会连响 3 下。

这里有个真正的好设计:if get_change(...) >= 5 —— 只有波动超过 5% 才发消息,避免天天骚扰。这是「告警阈值」的思路。

这份代码的问题

  1. 价格相等返回 100.0:平盘也触发。
  2. round 作用在比例上,百分比精度丢失。
  3. try/except ZeroDivisionError 是死代码。
  4. q="TSLA Market Update" 几乎搜不到结果。
  5. 三个单元素列表 + 三次 get_change():噪音。
  6. print 调试残留。
  7. 密钥是星号,跑不通。

README.md(8 行)

标题 Day 36 - Stock Trading News Alert Project,知识点:What is an API、API Keys, Authentication, Environment Variables、Sending SMS、Using Twilio to Send SMS、Use Python slice lists。

Use Python slice lists 在代码里没有体现(用的是 zip(range(3), ...) 而不是 [:3])。

Using Twilio 也没有——发的是 Telegram。

文件间关系

单文件,两个外部 API + 一个 Telegram Bot。

这个项目的结构就是「数据 → 判断 → 通知」三段:

1
2
3
Alpha Vantage(股价)─┐
├─▶ 比较涨跌幅 ──▶ 超过 5% ──▶ Telegram
NewsAPI(新闻)──────┘

Day 39 的机票监控、Day 95 的抢购提醒,都是这个形状——只是把「股价」换成「票价」「库存」。

微信收款码 微信
支付宝收款码 支付宝
评论