-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathdaily.ts
More file actions
305 lines (285 loc) · 10.9 KB
/
daily.ts
File metadata and controls
305 lines (285 loc) · 10.9 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import "./_env";
import fs from "node:fs";
import path from "node:path";
import { sources, REPORT_LOCALE } from "../lib/sources/registry";
import { fetchSource } from "../lib/sources/dispatch";
import {
generateDailyReport,
type ArticleInput,
} from "../lib/ai/pipeline";
import { getModelTag, validateBackendCredentials } from "../lib/ai/llm";
import {
enrichFinanceNewsSummaries,
enrichGithubTrendingSummaries,
enrichTrendingPapersSummaries,
enrichXViralSummaries,
} from "../lib/ai/enrich";
import {
groupRaw,
isSportsArticle,
MERGED_SUBGROUP_LIMITS,
renderHtml,
renderMarkdown,
} from "../lib/output/render";
import { analyzeWatchlist } from "../lib/trading/runner";
import { fetchCryptoFearGreed } from "../lib/trading/fear-greed";
import { fetchCryptoGlobal } from "../lib/trading/coingecko";
import { generateTradingCommentary } from "../lib/ai/trading-commentary";
import type { TradingSection } from "../lib/ai/pipeline";
import { todayKey } from "../lib/utils";
const OUTPUT_DIR = "daily_reports";
async function fetchAll(): Promise<ArticleInput[]> {
const articles: ArticleInput[] = [];
const enabled = sources.filter((s) => s.enabled !== false);
for (const source of enabled) {
try {
const items = await fetchSource(source);
console.log(` ${source.id.padEnd(20)} ${items.length}`);
articles.push(...items.map((it) => ({ ...it, source: source.name })));
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
console.error(` ${source.id.padEnd(20)} FAILED — ${msg}`);
}
}
return articles;
}
async function enrichGhTrending(articles: ArticleInput[]): Promise<void> {
const gh = articles.filter((a) => a.sourceId === "github-trending");
if (gh.length === 0) return;
console.log(
`[daily] enriching ${gh.length} GitHub Trending repos with ${REPORT_LOCALE} summaries…`,
);
const t0 = Date.now();
const summaries = await enrichGithubTrendingSummaries(gh);
for (const a of gh) {
const s = summaries.get(a.url);
if (s) a.summary = s;
}
console.log(
`[daily] enrichment done in ${((Date.now() - t0) / 1000).toFixed(1)}s, matched ${summaries.size}/${gh.length}`,
);
}
/**
* finance:news is rendered as a merged time-sorted list (see
* MERGED_SUBGROUP_LIMITS in render.ts). Enrich exactly the items that
* will be displayed: take all enabled finance:news articles, sort by
* publishedAt desc, slice to the merge limit, ask Sonnet for Chinese
* factual summaries.
*/
async function enrichFinanceNews(articles: ArticleInput[]): Promise<void> {
await enrichMergedSubgroup(articles, "finance", "news");
}
async function enrichPolitics(articles: ArticleInput[]): Promise<void> {
await enrichMergedSubgroup(articles, "politics", "world");
}
async function enrichAiNews(articles: ArticleInput[]): Promise<void> {
await enrichMergedSubgroup(articles, "tech", "ai-news");
}
/**
* X 热帖 enrichment is different from merged subgroups — we preserve the
* AttentionVC API's heat-rank order (do NOT sort by date) and cap to the
* displayed limit (matches SOURCE_DISPLAY_LIMITS["tech:x-viral"]).
*
* The Sonnet prompt also differs (XVIRAL_SYSTEM_PROMPT in enrich.ts) — X
* tweet titles are clickbait, the previewText holds the actual claim.
*/
async function enrichXViral(articles: ArticleInput[]): Promise<void> {
const xPosts = articles
.filter((a) => a.sourceId === "attentionvc-ai")
.slice(0, 20);
if (xPosts.length === 0) return;
console.log(`[daily] enriching ${xPosts.length} X posts with ${REPORT_LOCALE} summaries…`);
const t0 = Date.now();
// Author handle is encoded in the URL (https://x.com/{handle}/status/{id})
// — extract it to help the model identify whose claim it is.
const summaries = await enrichXViralSummaries(
xPosts.map((a) => ({
url: a.url,
title: a.title,
excerpt: a.excerpt,
author: a.url.match(/x\.com\/([^/]+)\//)?.[1] ?? "",
})),
);
for (const a of xPosts) {
const s = summaries.get(a.url);
if (s) a.summary = s;
}
console.log(
`[daily] enrichment done in ${((Date.now() - t0) / 1000).toFixed(1)}s, matched ${summaries.size}/${xPosts.length}`,
);
}
/**
* Trending papers enrichment — preserves the fetcher's upvote-desc order
* (huggingface-papers is in PRESERVE_FETCH_ORDER_SOURCES) and caps to the
* displayed limit (matches SOURCE_DISPLAY_LIMITS["tech:trending-papers"]).
*/
async function enrichTrendingPapers(articles: ArticleInput[]): Promise<void> {
const papers = articles
.filter((a) => a.sourceId === "huggingface-papers")
.slice(0, 20);
if (papers.length === 0) return;
console.log(
`[daily] enriching ${papers.length} trending papers with ${REPORT_LOCALE} summaries…`,
);
const t0 = Date.now();
const summaries = await enrichTrendingPapersSummaries(
papers.map((a) => ({ url: a.url, title: a.title, excerpt: a.excerpt })),
);
for (const a of papers) {
const s = summaries.get(a.url);
if (s) a.summary = s;
}
console.log(
`[daily] enrichment done in ${((Date.now() - t0) / 1000).toFixed(1)}s, matched ${summaries.size}/${papers.length}`,
);
}
/**
* Shared implementation for "merged subgroup" enrichment: collect all
* enabled articles in (category, subcategory), sort by date desc, take
* the display cap (from MERGED_SUBGROUP_LIMITS), and ask the LLM to
* summarize them into REPORT_LOCALE in a single batch. Symmetric to the
* merge logic in render.ts groupRaw, so display and enrichment stay aligned.
*
* Sources whose `lang` already matches REPORT_LOCALE are skipped — no
* point translating English to English (en mode) or Chinese to Chinese
* (zh mode).
*/
async function enrichMergedSubgroup(
articles: ArticleInput[],
category: "tech" | "finance" | "politics",
subcategory: string,
): Promise<void> {
const subSources = sources.filter(
(s) =>
s.category === category &&
s.subcategory === subcategory &&
s.enabled !== false,
);
const enabledIds = new Set(subSources.map((s) => s.id));
const sameLocaleIds = new Set(
subSources.filter((s) => (s.lang ?? "en") === REPORT_LOCALE).map((s) => s.id),
);
const limit = MERGED_SUBGROUP_LIMITS[`${category}:${subcategory}`] ?? 12;
// Top-N respects all enabled sources (so we don't reshape the merged
// timeline). Enrichment only targets items NOT already in the target
// language within that slice.
const top = articles
.filter((a) => enabledIds.has(a.sourceId))
.filter((a) => category !== "politics" || !isSportsArticle(a.title))
.sort(
(a, b) =>
(b.publishedAt?.getTime() ?? 0) - (a.publishedAt?.getTime() ?? 0),
)
.slice(0, limit);
const toEnrich = top.filter((a) => !sameLocaleIds.has(a.sourceId));
if (toEnrich.length === 0) return;
console.log(
`[daily] enriching ${toEnrich.length}/${top.length} ${category}:${subcategory} items with ${REPORT_LOCALE} summaries…`,
);
const t0 = Date.now();
const summaries = await enrichFinanceNewsSummaries(toEnrich);
for (const a of toEnrich) {
const s = summaries.get(a.url);
if (s) a.summary = s;
}
console.log(
`[daily] enrichment done in ${((Date.now() - t0) / 1000).toFixed(1)}s, matched ${summaries.size}/${toEnrich.length}`,
);
}
/**
* Pull daily OHLCV from Yahoo for every ticker in the watchlist, compute
* indicators + signals, then ask Sonnet for a market overview + a
* picks-to-watch list. Returns null if no ticker came back.
*/
async function runTrading(): Promise<TradingSection | null> {
console.log(`[daily] analyzing watchlist + crypto context (Yahoo / alt.me / CoinGecko)…`);
const t0 = Date.now();
const [tickers, cryptoFearGreed, cryptoGlobal] = await Promise.all([
analyzeWatchlist(),
fetchCryptoFearGreed(),
fetchCryptoGlobal(),
]);
console.log(
`[daily] indicators ready in ${((Date.now() - t0) / 1000).toFixed(1)}s — ${tickers.length} tickers` +
(cryptoFearGreed ? `, F&G ${cryptoFearGreed.value}` : ", F&G ✗") +
(cryptoGlobal
? `, BTC dom ${cryptoGlobal.btcDominance.toFixed(1)}%`
: ", CG ✗"),
);
if (tickers.length === 0) return null;
console.log(`[daily] generating trading commentary with ${getModelTag()}…`);
const t1 = Date.now();
const commentary = await generateTradingCommentary({
tickers,
cryptoFearGreed: cryptoFearGreed ?? undefined,
cryptoGlobal: cryptoGlobal ?? undefined,
});
console.log(
`[daily] trading commentary ready in ${((Date.now() - t1) / 1000).toFixed(1)}s`,
);
return {
...commentary,
tickers,
crypto_fear_greed: cryptoFearGreed ?? undefined,
crypto_global: cryptoGlobal ?? undefined,
generated_at: new Date().toISOString(),
};
}
async function main() {
// Fail fast on misconfigured backend before we spend 30s fetching
// 500+ articles only to discover the LLM has no credentials.
validateBackendCredentials();
const date = todayKey();
console.log(`[daily] ${date} — fetching sources…\n`);
const articles = await fetchAll();
console.log(`\n[daily] total articles: ${articles.length}`);
if (articles.length === 0) {
throw new Error("no articles fetched — aborting");
}
// Enrich GH Trending, papers, finance news, and politics with summaries.
await enrichGhTrending(articles);
await enrichTrendingPapers(articles);
await enrichFinanceNews(articles);
await enrichPolitics(articles);
await enrichAiNews(articles);
await enrichXViral(articles);
// Trading signals: Yahoo fetch + indicators + commentary. Non-fatal —
// if it errors, we still ship the news digest.
let trading: TradingSection | null = null;
try {
trading = await runTrading();
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
console.warn(`[daily] trading section failed: ${msg}`);
}
console.log(`[daily] generating digest with ${getModelTag()}…`);
const t0 = Date.now();
const { report } = await generateDailyReport(articles);
if (trading) report.trading = trading;
console.log(`[daily] digest ready in ${((Date.now() - t0) / 1000).toFixed(1)}s`);
const dateDir = path.join(OUTPUT_DIR, date);
fs.mkdirSync(dateDir, { recursive: true });
const base = path.join(dateDir, date);
const raw = groupRaw(articles, sources);
fs.writeFileSync(`${base}.json`, JSON.stringify(report, null, 2), "utf8");
// Sidecar with all fetched articles + LLM-attached summary, so
// scripts/render.ts can rebuild HTML/MD for UI iteration without
// re-fetching or re-calling the LLM.
fs.writeFileSync(
`${base}-articles.json`,
JSON.stringify({ date, articles }, null, 2),
"utf8",
);
fs.writeFileSync(`${base}.html`, renderHtml(report, raw, date), "utf8");
if (process.env.OUTPUT_MARKDOWN === "true") {
fs.writeFileSync(`${base}.md`, renderMarkdown(report, date), "utf8");
console.log(`[daily] wrote ${base}.{json,html,md,articles.json}`);
} else {
console.log(`[daily] wrote ${base}.{json,html,articles.json}`);
}
console.log(`[daily] done.`);
}
main().catch((e) => {
console.error(`[daily] FAILED:`, e);
process.exit(1);
});