diff --git a/src/main/kotlin/network/NewsService.kt b/src/main/kotlin/network/NewsService.kt index ab8e0fb..92ddf52 100644 --- a/src/main/kotlin/network/NewsService.kt +++ b/src/main/kotlin/network/NewsService.kt @@ -89,10 +89,12 @@ object NewsService { header("X-Naver-Client-Secret", clientSecret) }.body() - val todayItems = response.items.filter { item -> + val scoredItems = response.items.mapNotNull { item -> try { val pubDate = ZonedDateTime.parse(item.pubDate, formatter) val isToday = pubDate.toLocalDate() == today + if (!isToday) return@mapNotNull null + val cleanTitle = item.title .replace("", "") .replace("", "") @@ -100,19 +102,43 @@ object NewsService { .replace("&", "&") .replace("<", "<") .replace(">", ">") + val cleanDesc = item.description + .replace("", "") + .replace("", "") + .replace(""", "\"") + .replace("&", "&") + .replace("<", "<") + .replace(">", ">") - // 기사 제목에 타겟 종목명 또는 회사명이 반드시 포함되어 있는지 엄격 검증 - val mentionsTarget = cleanTitle.contains(cleanStockName) || - (cleanCorpName.isNotBlank() && cleanTitle.contains(cleanCorpName)) + val titleMentions = countMentions(cleanTitle, cleanStockName, cleanCorpName) + val descMentions = countMentions(cleanDesc, cleanStockName, cleanCorpName) - isToday && mentionsTarget + // 기사 제목에 타겟 종목명이 반드시 1회 이상 포함되어야 함 + if (titleMentions == 0) return@mapNotNull null + + var priorityScore = titleMentions * 3 + descMentions + + // 실적/공시/수주/계약 등 펀더멘털 키워드 가산점 (+3) + val fundamentalKeywords = listOf("실적", "공시", "수주", "계약", "호조", "서프라이즈", "흑자", "배당", "자사주", "M&A", "특허", "신제품", "공급") + if (fundamentalKeywords.any { cleanTitle.contains(it) || cleanDesc.contains(it) }) { + priorityScore += 3 + } + + // 단순 특징주/시황 나열 기사 감점 (-2) + if (cleanTitle.contains("특징주") || cleanTitle.contains("시황") || cleanTitle.contains("테마주")) { + priorityScore -= 2 + } + + item to priorityScore } catch (e: Exception) { - false + null } } - // 중복 호스트 제거 및 최종 2건 선택 - val finalItems = todayItems + // 우선순위 점수 높은 순으로 정렬 후 중복 호스트 제거하여 상위 2건 선택 + val finalItems = scoredItems + .sortedByDescending { it.second } + .map { it.first } .distinctBy { Url(it.originallink).host } .take(2) @@ -218,4 +244,23 @@ object NewsService { println("❌ [Telegram] curl 발송 처리 중 에러: ${e.message}") } } + + private fun countMentions(text: String, stockName: String, corpName: String): Int { + var count = 0 + if (stockName.isNotBlank()) { + var idx = 0 + while (true) { + idx = text.indexOf(stockName, idx) + if (idx != -1) { count++; idx += stockName.length } else break + } + } + if (corpName.isNotBlank() && corpName != stockName) { + var idx = 0 + while (true) { + idx = text.indexOf(corpName, idx) + if (idx != -1) { count++; idx += corpName.length } else break + } + } + return count + } } diff --git a/src/main/kotlin/network/RagService.kt b/src/main/kotlin/network/RagService.kt index 83b93ee..18d565d 100644 --- a/src/main/kotlin/network/RagService.kt +++ b/src/main/kotlin/network/RagService.kt @@ -821,8 +821,14 @@ object RagService { val techDuration = System.currentTimeMillis() - techStartTime val newsStartTime = System.currentTimeMillis() - val (newsScore100, newsReason) = tempDecision.newsContext?.let { - getAiNewsScore(stockName, it, tempDecision.techSummary ?: "") + val (newsScore100, newsReason) = tempDecision.newsContext?.let { rawNews -> + val refinedNews = extractTargetNewsContext(rawNews, stockName) + if (refinedNews.isNotBlank()) { + getAiNewsScore(stockName, refinedNews, tempDecision.techSummary ?: "") + } else { + println("⚠️ [RagService] [$stockName] 뉴스 본문 내 해당 종목 직접 언급이 없어 LLM 분석을 건너뜁니다.") + 50.0 to "참조 뉴스 없음 (무관한 기사)" + } } ?: (50.0 to "참조 뉴스 없음") val newsDuration = System.currentTimeMillis() - newsStartTime @@ -936,6 +942,48 @@ object RagService { } } + /** + * 기사 원문에서 타겟 종목과 직접 관련된 문단/문장만 정밀 추출 (타사 잡음 제거) + */ + fun extractTargetNewsContext(fullNews: String, stockName: String, maxChars: Int = 1200): String { + val cleanName = stockName.replace("(주)", "").trim() + if (cleanName.isBlank() || fullNews.isBlank()) return fullNews + + // 줄바꿈 단위로 문단 분리 + val paragraphs = fullNews.split(Regex("\n+")) + .map { it.trim() } + .filter { it.isNotBlank() } + + val matchedParagraphs = paragraphs.filter { it.contains(cleanName) } + + if (matchedParagraphs.isNotEmpty()) { + val combined = matchedParagraphs.joinToString("\n\n") + println("✂️ [RagService.extractTargetNewsContext] [$stockName] 전체 ${fullNews.length}자 중 타겟 관련 문단 ${matchedParagraphs.size}개 추출 (${combined.length}자)") + return if (combined.length <= maxChars) combined else combined.take(maxChars) + "..." + } + + // 줄바꿈이 없는 단일 통문장인 경우 마침표 단위로 분리 + val sentences = fullNews.split(Regex("(?<=[.?!])\\s+")) + .map { it.trim() } + .filter { it.isNotBlank() } + + val matchedIndices = sentences.indices.filter { sentences[it].contains(cleanName) } + if (matchedIndices.isEmpty()) { + return "" + } + + val targetIndices = mutableSetOf() + for (idx in matchedIndices) { + if (idx - 1 >= 0) targetIndices.add(idx - 1) + targetIndices.add(idx) + if (idx + 1 < sentences.size) targetIndices.add(idx + 1) + } + + val combined = targetIndices.sorted().joinToString(" ") { sentences[it] } + println("✂️ [RagService.extractTargetNewsContext] [$stockName] 전체 ${fullNews.length}자 중 타겟 관련 문장 ${targetIndices.size}개 추출 (${combined.length}자)") + return if (combined.length <= maxChars) combined else combined.take(maxChars) + "..." + } + private suspend fun getAiNewsScore(stockName: String, news: String, techSummary: String): Pair { val prompt = """ # Role: Expert Quantitative & Sentiment Analyst @@ -946,7 +994,7 @@ object RagService { # Input 1: [Market Context] (Standardized Scores & Price History) $techSummary - # Input 2: [News Text] (Latest Headlines & Content) + # Input 2: [News Text] (Refined Facts & Headlines for $stockName) $news # Evaluation Logic (Internal Reasoning): @@ -978,7 +1026,7 @@ object RagService { println(""" ================================================================================ -📰 [LLM 전송 전 뉴스 원본 텍스트 - $stockName] (총 ${news.length}자) +📰 [LLM 전송 전 정제된 뉴스 텍스트 - $stockName] (총 ${news.length}자) -------------------------------------------------------------------------------- $news --------------------------------------------------------------------------------