Compare commits

...

19 Commits

Author SHA1 Message Date
ArvinLovegood
f9294fbffd feat(stock):添加热门股票排名功能
- 在选股自然语言描述中增加了近期趋势示例说明
- 新增HotStockTable工具函数用于获取热门股票数据
- 实现HotStockTable工具的调用逻辑和参数处理
- 集成雪球热门股票API接口
- 添加分页大小参数支持,默认为50条记录
- 实现Markdown表格格式的热门股票排名展示
2026-01-06 15:33:35 +08:00
ArvinLovegood
cc12a886c1 feat(news):扩展新闻标签匹配和添加热门股票数据功能
- 在新闻标签匹配中增加"外媒简讯"和"外媒"标签支持
- 过滤掉"rotating_light"和"loudspeaker"标签避免重复处理
- 优化GetSource函数支持多标签匹配判断新闻来源
- 添加THSHotStrategy数据模型定义热门策略数据结构
- 实现StrategySquare接口获取热门选股策略数据
- 在OpenAI接口中增加热门股票排名数据查询功能
- 为HotItem模型添加markdown标签支持表格显示
- 增加测试函数验证热门策略表格功能
2026-01-04 13:31:09 +08:00
ArvinLovegood
34ea989d47 refactor(data):优化数据API和测试用例
- 调整并发请求数量,移除市场指数行情的获取逻辑
- 注释掉多个市场指数行情查询的协程,减少不必要的数据请求
- 添加投资者互动数据和宏观经济数据的获取功能
- 更新24小时新闻列表的格式化方式,包含时间和内容标题
- 移除顶部新闻列表和外媒全球新闻资讯的获取逻辑
- 调整测试用例中的参数值,将历史数据天数从30改为5
- 修复股价数据检查逻辑,移除对空字符串的特殊处理
2026-01-01 22:34:19 +08:00
ArvinLovegood
aadff1c5eb ci(workflow):添加macOS平台的Intel和ARM64架构构建支持
- 添加 go-stock-darwin-intel 构建配置
- 添加 go-stock-darwin-arm64 构建配置
- 扩展 macOS 平台的架构覆盖范围
2026-01-01 16:18:29 +08:00
ArvinLovegood
6b7fed00a3 refactor(openai_api):优化新闻资讯获取逻辑
- 移除 TradingViewNews 和 ReutersNew 相关的 goroutine 调用
- 将 GetNewsList2 替换为 GetNews24HoursList 获取24小时市场资讯
- 添加 ClsCalendar 功能获取近期重大事件/会议信息
- 调整 WaitGroup 的计数以匹配新的并发任务数量
- 修改时间格式化显示为标准格式 "2006-01-02 15:04:05"
2026-01-01 13:58:07 +08:00
ArvinLovegood
5af0e28601 feat(telegraph):电报标签功能和前端显示优化
- 实现电报数据的标签关联功能,支持主题标签存储
- 添加电报列表分页查询接口,支持标签预加载
- 在前端新闻列表组件中添加时间显示功能
- 优化新闻列表按日期分组显示的布局结构
- 添加定时刷新财联社电报、新浪财经和外媒数据功能
- 根据新闻列表长度动态调整网格列数显示
2026-01-01 12:00:32 +08:00
ArvinLovegood
c4af77954e refactor(app):将syncNews函数改为方法并集成情感分析
- 将syncNews函数转换为App结构体的方法
- 在新闻同步逻辑中集成情感分析功能
- 添加新闻推送功能到同步流程中
- 修复VIP用户新闻同步的调用方式
2026-01-01 09:07:25 +08:00
ArvinLovegood
8236adb680 feat(news):添加新闻标签旋转灯标识处理
- 新增 rotating_light 标签检测逻辑
- 根据标签内容动态设置 isRed 属性
- 优化新闻电报数据结构的红色标识字段处理
2026-01-01 08:48:01 +08:00
ArvinLovegood
0adfdab441 feat(app):添加VIP2用户市场资讯自动同步功能
- 在VIP2级别中添加自动同步最近24小时市场资讯功能
- 实现自动同步外媒简讯、财联社电报、新浪财经资讯
- 重构VIP验证逻辑到独立的isVip方法中
- 添加syncNews方法实现资讯获取和存储功能
- 更新前端about组件中VIP2功能描述
- 更新README中VIP2功能说明
- 添加NtfyNews数据模型定义
- 添加golang.org/x/exp依赖包
2025-12-31 18:27:26 +08:00
ArvinLovegood
b1c618a9de feat(app):添加VIP用户市场资讯自动同步功能
- 在VIP2级别中添加自动同步最近24小时市场资讯功能
- 实现自动同步外媒简讯、财联社电报、新浪财经资讯
- 重构VIP验证逻辑到独立的isVip方法中
- 添加syncNews方法实现资讯获取和存储功能
- 更新前端about组件中VIP2功能描述
- 更新README中VIP2功能说明
- 添加NtfyNews数据模型定义
- 添加golang.org/x/exp依赖包
2025-12-31 18:27:08 +08:00
ArvinLovegood
709c372bf3 feat(app):添加VIP用户市场资讯自动同步功能
- 在VIP2级别中添加自动同步最近24小时市场资讯功能
- 实现自动同步外媒简讯、财联社电报、新浪财经资讯
- 重构VIP验证逻辑到独立的isVip方法中
- 添加syncNews方法实现资讯获取和存储功能
- 更新前端about组件中VIP2功能描述
- 更新README中VIP2功能说明
- 添加NtfyNews数据模型定义
- 添加golang.org/x/exp依赖包
2025-12-31 18:06:51 +08:00
ArvinLovegood
beb022c448 docs(readme): 更新重大更新部分
- 添加2025.11.21新增带频率权重的情感分析功能
- 插入新功能截图img_1.png
- 保留原有市场资讯AI分析和总结功能说明
- 维持市场行情模块介绍内容
2025-12-19 17:21:37 +08:00
ArvinLovegood
d1aed3419b docs(readme): 更新日志新增AI思考模式与热门选股策略功能
- 在更新日志中添加2025.12.16新增AI思考模式与热门选股策略功能
- 补充相关功能描述与日期信息
- 维护文档结构与格式一致性
2025-12-19 17:16:30 +08:00
ArvinLovegood
48511c61df docs(readme):更新README文档中的更新日志和功能描述
- 添加2025.11.21新增带频率权重的情感分析功能说明
- 添加2025.10.30 AI智能体功能开关及页面水印移除说明
- 添加2025.09.27机构研究报告AI工具函数说明
- 添加2025.08.09 AI智能体聊天功能说明
- 更新选股自然语言描述,增加技术指标和成交量筛选示例
2025-12-19 17:15:05 +08:00
ArvinLovegood
163e8800f9 docs(readme):更新技术支持联系方式
- 将技术支持微信联系方式改为QQ
- 移除微信二维码图片显示
- 更新表格中的联系方式描述
2025-12-17 22:59:20 +08:00
ArvinLovegood
70e0d19c58 feat(ai):新增AI思考模式与热门选股策略功能
- 在NewChatStream和SummaryStockNews接口中增加think参数以支持AI思考模式
- 更新前端组件market.vue和stock.vue,添加思考模式开关控件
- 升级github.com/cloudwego/eino依赖至v0.7.9版本
- 修改ToolFunction结构体,新增Strict字段并调整Parameters为指针类型
- 实现HotStrategyTable工具函数,用于获取并展示热门选股策略表格
- 优化市场新闻API中的去重逻辑,当标题为空时使用内容进行判重
- 在AI对话流中增加对reasoning_content的支持,提升推理过程可见性
- 完善AskAi和AskAiWithTools方法,支持传递thinkingMode参数控制模型推理行为
- 调整FunctionParameters结构体,新增AdditionalProperties字段以增强灵活性
- 修复测试文件中IndustryResearchReport调用参数及注释问题
2025-12-16 15:49:59 +08:00
ArvinLovegood
4e04bacf22 refactor(data):重构情感分析与词频统计模块
- 将 SentimentResult 和 WordFreqWithWeight 结构体移至 models 包统一管理
- 更新 AnalyzeSentiment 和 AnalyzeSentimentWithFreqWeight 函数返回值类型
- 优化 NewsAnalyze 函数实现新闻内容自动获取与分析
- 新增定时任务定期执行新闻情感分析
- 完善数据库模型迁移,支持词频与情感分析结果存储
- 调整前端接口声明文件,确保类型一致性
- 移除冗余代码注释,提升代码可读性
2025-12-12 15:35:50 +08:00
ArvinLovegood
8c75c8533a feat(news):优化新闻列表展示并提取标题
- 后端从富文本中提取 Telegraph 标题
- 前端使用折叠面板展示带标题的新闻项
- 无标题新闻项保持原有展示方式
- 调整标签和文字的排版与样式
- 支持展开/收起新闻详情内容
- 保留时间标签和高亮显示逻辑
2025-12-11 18:39:58 +08:00
ArvinLovegood
1ad02d4b0c style(newsList):优化新闻列表文本显示样式
- 为新闻标题和内容添加换行样式以防止文本溢出
- 使用条件渲染仅在存在标题时显示标题文本
- 调整新闻内容文本的断行属性以提高可读性
- 移除不再使用的渐变文本组件以简化模板结构
2025-12-11 18:26:11 +08:00
26 changed files with 1235 additions and 439 deletions

View File

@@ -29,6 +29,12 @@ jobs:
- name: 'go-stock-darwin-universal'
platform: 'darwin/universal'
os: 'macos-latest'
- name: 'go-stock-darwin-intel'
platform: 'darwin'
os: 'macos-latest'
- name: 'go-stock-darwin-arm64'
platform: 'darwin/arm64'
os: 'macos-latest'
runs-on: ${{ matrix.build.os }}
steps:

View File

@@ -53,7 +53,7 @@
|:--------------------------------|----------------|:-------------------------------------------------------|
| 每月 0 RMB | vip0 | 🌟 全部功能,软件自动更新(从GitHub下载),自行解决github平台网络问题。 |
| 每月赞助 18.8 RMB<br>每年赞助 120 RMB | vip1 | 💕 全部功能,软件自动更新(从CDN下载),更新快速便捷。AI配置指导提示词参考等 |
| 每月赞助 28.8 RMB<br>每年赞助 240 RMB | vip2 | 💕 💕 vip1全部功能,赠送硅基流动AI分析服务 |
| 每月赞助 28.8 RMB<br>每年赞助 240 RMB | vip2 | 💕 💕 vip1全部功能,赠送硅基流动AI分析服务,启动时自动同步最近24小时市场资讯(包括外媒简讯) |
| 每月赞助 X RMB | vipX | 🧩 更多计划视go-stock开源项目发展情况而定...(承接GitHub项目README广告推广💖) |
## 🧩 重大功能开发计划
@@ -69,6 +69,11 @@
| 不再强制依赖Chrome浏览器 | ✅ | 默认使用edge浏览器抓取新闻资讯 |
## 👀 更新日志
### 2025.12.16 新增AI思考模式与热门选股策略功能
### 2025.11.21 新增带频率权重的情感分析功能
### 2025.10.30 添加AI智能体功能开关(默认关闭,因为使用体验不理想),移除页面水印
### 2025.09.27 添加机构/券商的研究报告AI工具函数
### 2025.08.09 添加AI智能体聊天功能
### 2025.07.08 实现软件自动更新功能
### 2025.07.07 卡片添加迷你分时图
### 2025.07.05 MacOs支持
@@ -116,6 +121,8 @@
## 🦄 重大更新
### BIG NEWS !!! 重大更新!!!
- 2025.11.21 新增带频率权重的情感分析功能
![img_1.png](build/screenshot/img15.png)
- 2025.04.25 市场资讯支持AI分析和总结让AI帮你读市场
![img.png](img.png)
- 2025.04.24 新增市场行情模块:即时掌握全球市场行情资讯/动态从此再也不用偷摸去各大财经网站啦。go-stock一键帮你搞定
@@ -162,15 +169,15 @@
## 🐳 关于技术支持申明
- 本软件基于开源技术构建使用Wails、NaiveUI、Vue、AI大模型等开源项目。 技术上如有问题,可以先向对应的开源社区请求帮助。
- 开源不易,本人精力和时间有限,如需一对一技术支持,请先赞助。联系微信(备注 技术支持)ArvinLovegood
- 开源不易,本人精力和时间有限,如需一对一技术支持,请先赞助。联系QQ(备注 技术支持)506808970
<img src="./build/wx.jpg" width="301px" height="402px" alt="ArvinLovegood">
[//]: # (<img src="./build/wx.jpg" width="301px" height="402px" alt="ArvinLovegood">)
| 技术支持方式 | 赞助(元) |
|:--------------------------------|:-----:|
| 加 QQ506808970微信ArvinLovegood | 100/次 |
| 长期技术支持(不限次数,新功能优先体验等) | 5000 |
| 加 QQ506808970 | 100/次 |
| 长期技术支持(不限次数,新功能优先体验等) | 5000 |

264
app.go
View File

@@ -1,6 +1,7 @@
package main
import (
"bufio"
"bytes"
"context"
"encoding/base64"
@@ -18,6 +19,7 @@ import (
"github.com/duke-git/lancet/v2/cryptor"
"github.com/inconshreveable/go-update"
"golang.org/x/exp/slices"
"github.com/PuerkitoBio/goquery"
"github.com/coocood/freecache"
@@ -62,19 +64,22 @@ func AddTools(tools []data.Tool) []data.Tool {
Function: data.ToolFunction{
Name: "SearchStockByIndicators",
Description: "根据自然语言筛选股票,返回自然语言选股条件要求的股票所有相关数据。输入股票名称可以获取当前股票最新的股价交易数据和基础财务指标信息,多个股票名称使用,分隔。",
Parameters: data.FunctionParameters{
Parameters: &data.FunctionParameters{
Type: "object",
Properties: map[string]any{
"words": map[string]any{
"type": "string",
"description": "选股自然语言。" +
"例如,查看技术指标:上海贝岭,macd,rsi,kdj,boll,5日均线,14日均线,30日均线,60日均线,成交量,OBV,EMA" +
"例如查看近期趋势量比连续2天>1主力连续2日净流入且递增主力净额>3000万元行业股价在20日线上" +
"例如查看有潜力的成交量爆发股最近7日成交量量比大于3出现过一次非ST" +
"例1创新药,半导体;PE<30;净利润增长率>50%。 " +
"例2上证指数,科创50。 " +
"例3长电科技,上海贝岭。" +
"例4长电科技,上海贝岭;KDJ,MACD,RSI,BOLL,主力净流入/流出" +
"例4长电科技,上海贝岭;KDJ,MACD,RSI,BOLL,主力资金" +
"例5换手率大于3%小于25%.量比1以上. 10日内有过涨停.股价处于峰值的二分之一以下.流通股本<100亿.当日和连续四日净流入;股价在20日均线以上.分时图股价在均线之上.热门板块下涨幅领先的A股. 当日量能20000手以上.沪深个股.近一年市盈率波动小于150%.MACD金叉;不要ST股及不要退市股非北交所每股收益>0。" +
"例6沪深主板.流通市值小于100亿.市值大于10亿.60分钟dif大于dea.60分钟skdj指标k值大于d值.skdj指标k值小于90.换手率大于3%.成交额大于1亿元.量比大于2.涨幅大于2%小于7%.股价大于5小于50.创业板.10日均线大于20日均线;不要ST股及不要退市股;不要北交所;不要科创板;不要创业板。" +
"例7股价在20日线上一月之内涨停次数>=1量比大于1换手率大于3%,流通市值大于 50亿小于200亿。" +
"例7股价在20日线上一月之内涨停次数>=1量比大于1换手率大于3%" +
"例8基本条件前期有爆量回调到 10 日线,当日是缩量阴线,均线趋势向上。;优选条件:一月之内涨停次数>=1",
},
},
@@ -88,7 +93,7 @@ func AddTools(tools []data.Tool) []data.Tool {
Function: data.ToolFunction{
Name: "GetStockKLine",
Description: "获取股票日K线数据。",
Parameters: data.FunctionParameters{
Parameters: &data.FunctionParameters{
Type: "object",
Properties: map[string]any{
"days": map[string]any{
@@ -110,7 +115,7 @@ func AddTools(tools []data.Tool) []data.Tool {
Function: data.ToolFunction{
Name: "InteractiveAnswer",
Description: "获取投资者与上市公司互动问答的数据,反映当前投资者关注的热点问题",
Parameters: data.FunctionParameters{
Parameters: &data.FunctionParameters{
Type: "object",
Properties: map[string]any{
"page": map[string]any{
@@ -162,7 +167,7 @@ func AddTools(tools []data.Tool) []data.Tool {
Function: data.ToolFunction{
Name: "GetStockResearchReport",
Description: "获取市场分析师的股票研究报告",
Parameters: data.FunctionParameters{
Parameters: &data.FunctionParameters{
Type: "object",
Properties: map[string]any{
"stockCode": map[string]any{
@@ -175,6 +180,32 @@ func AddTools(tools []data.Tool) []data.Tool {
},
})
tools = append(tools, data.Tool{
Type: "function",
Function: data.ToolFunction{
Name: "HotStrategyTable",
Description: "获取当前热门选股策略",
},
})
tools = append(tools, data.Tool{
Type: "function",
Function: data.ToolFunction{
Name: "HotStockTable",
Description: "当前热门股票排名",
Parameters: &data.FunctionParameters{
Type: "object",
Properties: map[string]any{
"pageSize": map[string]any{
"type": "string",
"description": "分页大小",
},
},
Required: []string{"pageSize"},
},
},
})
return tools
}
@@ -245,8 +276,15 @@ func (a *App) CheckUpdate(flag int) {
return
}
logger.SugaredLogger.Infof("releaseVersion:%+v", releaseVersion.TagName)
if releaseVersion.TagName != Version {
if _, vipLevel, ok := a.isVip(sponsorCode, "", releaseVersion); ok {
level, _ := convertor.ToInt(vipLevel)
if level >= 2 {
go a.syncNews()
}
}
if releaseVersion.TagName != Version {
tag := &models.Tag{}
_, err = resty.New().R().
SetResult(tag).
@@ -271,59 +309,9 @@ func (a *App) CheckUpdate(flag int) {
if IsMacOS() {
downloadUrl = fmt.Sprintf("https://github.com/ArvinLovegood/go-stock/releases/download/%s/go-stock-darwin-universal", releaseVersion.TagName)
}
sponsorCode = strutil.Trim(a.GetConfig().SponsorCode)
if sponsorCode != "" {
encrypted, err := hex.DecodeString(sponsorCode)
if err != nil {
logger.SugaredLogger.Error(err.Error())
return
}
key, err := hex.DecodeString(BuildKey)
if err != nil {
logger.SugaredLogger.Error(err.Error())
return
}
decrypt := string(cryptor.AesEcbDecrypt(encrypted, key))
err = json.Unmarshal([]byte(decrypt), &a.SponsorInfo)
if err != nil {
logger.SugaredLogger.Error(err.Error())
return
}
vipStartTime, err := time.ParseInLocation("2006-01-02 15:04:05", a.SponsorInfo["vipStartTime"].(string), time.Local)
vipEndTime, err := time.ParseInLocation("2006-01-02 15:04:05", a.SponsorInfo["vipEndTime"].(string), time.Local)
vipAuthTime, err := time.ParseInLocation("2006-01-02 15:04:05", a.SponsorInfo["vipAuthTime"].(string), time.Local)
if err != nil {
logger.SugaredLogger.Error(err.Error())
return
}
isVip := false
if time.Now().After(vipAuthTime) && time.Now().After(vipStartTime) && time.Now().Before(vipEndTime) {
isVip = true
}
if IsWindows() {
if isVip {
if a.SponsorInfo["winDownUrl"] == nil {
downloadUrl = fmt.Sprintf("https://gitproxy.click/https://github.com/ArvinLovegood/go-stock/releases/download/%s/go-stock-windows-amd64.exe", releaseVersion.TagName)
} else {
downloadUrl = a.SponsorInfo["winDownUrl"].(string)
}
} else {
downloadUrl = fmt.Sprintf("https://github.com/ArvinLovegood/go-stock/releases/download/%s/go-stock-windows-amd64.exe", releaseVersion.TagName)
}
}
if IsMacOS() {
if isVip {
if a.SponsorInfo["macDownUrl"] == nil {
downloadUrl = fmt.Sprintf("https://gitproxy.click/https://github.com/ArvinLovegood/go-stock/releases/download/%s/go-stock-darwin-universal", releaseVersion.TagName)
} else {
downloadUrl = a.SponsorInfo["macDownUrl"].(string)
}
} else {
downloadUrl = fmt.Sprintf("https://github.com/ArvinLovegood/go-stock/releases/download/%s/go-stock-darwin-universal", releaseVersion.TagName)
}
}
downloadUrl, _, done := a.isVip(sponsorCode, downloadUrl, releaseVersion)
if !done {
return
}
go runtime.EventsEmit(a.ctx, "newsPush", map[string]any{
"time": "发现新版本:" + releaseVersion.TagName,
@@ -379,6 +367,144 @@ func (a *App) CheckUpdate(flag int) {
}
}
func (a *App) isVip(sponsorCode string, downloadUrl string, releaseVersion *models.GitHubReleaseVersion) (string, string, bool) {
isVip := false
vipLevel := "0"
sponsorCode = strutil.Trim(a.GetConfig().SponsorCode)
if sponsorCode != "" {
encrypted, err := hex.DecodeString(sponsorCode)
if err != nil {
logger.SugaredLogger.Error(err.Error())
return "", "0", false
}
key, err := hex.DecodeString(BuildKey)
if err != nil {
logger.SugaredLogger.Error(err.Error())
return "", "0", false
}
decrypt := string(cryptor.AesEcbDecrypt(encrypted, key))
err = json.Unmarshal([]byte(decrypt), &a.SponsorInfo)
if err != nil {
logger.SugaredLogger.Error(err.Error())
return "", "0", false
}
vipLevel = a.SponsorInfo["vipLevel"].(string)
vipStartTime, err := time.ParseInLocation("2006-01-02 15:04:05", a.SponsorInfo["vipStartTime"].(string), time.Local)
vipEndTime, err := time.ParseInLocation("2006-01-02 15:04:05", a.SponsorInfo["vipEndTime"].(string), time.Local)
vipAuthTime, err := time.ParseInLocation("2006-01-02 15:04:05", a.SponsorInfo["vipAuthTime"].(string), time.Local)
if err != nil {
logger.SugaredLogger.Error(err.Error())
return "", vipLevel, false
}
if time.Now().After(vipAuthTime) && time.Now().After(vipStartTime) && time.Now().Before(vipEndTime) {
isVip = true
}
if IsWindows() {
if isVip {
if a.SponsorInfo["winDownUrl"] == nil {
downloadUrl = fmt.Sprintf("https://gitproxy.click/https://github.com/ArvinLovegood/go-stock/releases/download/%s/go-stock-windows-amd64.exe", releaseVersion.TagName)
} else {
downloadUrl = a.SponsorInfo["winDownUrl"].(string)
}
} else {
downloadUrl = fmt.Sprintf("https://github.com/ArvinLovegood/go-stock/releases/download/%s/go-stock-windows-amd64.exe", releaseVersion.TagName)
}
}
if IsMacOS() {
if isVip {
if a.SponsorInfo["macDownUrl"] == nil {
downloadUrl = fmt.Sprintf("https://gitproxy.click/https://github.com/ArvinLovegood/go-stock/releases/download/%s/go-stock-darwin-universal", releaseVersion.TagName)
} else {
downloadUrl = a.SponsorInfo["macDownUrl"].(string)
}
} else {
downloadUrl = fmt.Sprintf("https://github.com/ArvinLovegood/go-stock/releases/download/%s/go-stock-darwin-universal", releaseVersion.TagName)
}
}
}
return downloadUrl, vipLevel, isVip
}
func (a *App) syncNews() {
defer PanicHandler()
client := resty.New()
url := fmt.Sprintf("http://go-stock.sparkmemory.top:16666/FinancialNews/json?since=%d", time.Now().Add(-24*time.Hour).Unix())
logger.SugaredLogger.Infof("syncNews:%s", url)
resp, err := client.R().SetDoNotParseResponse(true).Get(url)
body := resp.RawBody()
defer body.Close()
if err != nil {
logger.SugaredLogger.Errorf("syncNews error:%s", err.Error())
}
scanner := bufio.NewScanner(body)
for scanner.Scan() {
line := scanner.Text()
logger.SugaredLogger.Infof("Received data: %s", line)
news := &models.NtfyNews{}
err := json.Unmarshal(scanner.Bytes(), news)
if err != nil {
return
}
dataTime := time.UnixMilli(int64(news.Time * 1000))
if slice.ContainAny(news.Tags, []string{"外媒资讯", "财联社电报", "新浪财经", "外媒简讯", "外媒"}) {
isRed := false
if slice.Contain(news.Tags, "rotating_light") {
isRed = true
}
telegraph := &models.Telegraph{
Title: news.Title,
Content: news.Message,
DataTime: &dataTime,
IsRed: isRed,
Time: dataTime.Format("15:04:05"),
Source: GetSource(news.Tags),
SentimentResult: data.AnalyzeSentiment(news.Message).Description,
}
cnt := int64(0)
if telegraph.Title == "" {
db.Dao.Model(telegraph).Where("content=?", telegraph.Content).Count(&cnt)
} else {
db.Dao.Model(telegraph).Where("title=?", telegraph.Title).Count(&cnt)
}
if cnt == 0 {
db.Dao.Model(telegraph).Create(&telegraph)
a.NewsPush(&[]models.Telegraph{*telegraph})
tags := slice.Filter(news.Tags, func(index int, item string) bool {
return !(item == "rotating_light" || item == "loudspeaker")
})
for _, subject := range tags {
tag := &models.Tags{
Name: subject,
Type: "subject",
}
db.Dao.Model(tag).Where("name=? and type=?", subject, "subject").FirstOrCreate(&tag)
db.Dao.Model(models.TelegraphTags{}).Where("telegraph_id=? and tag_id=?", telegraph.ID, tag.ID).FirstOrCreate(&models.TelegraphTags{
TelegraphId: telegraph.ID,
TagId: tag.ID,
})
}
}
}
}
}
func GetSource(tags []string) string {
if slice.ContainAny(tags, []string{"外媒简讯", "外媒资讯", "外媒"}) {
return "外媒"
}
if slices.Contains(tags, "财联社电报") {
return "财联社电报"
}
if slices.Contains(tags, "新浪财经") {
return "新浪财经"
}
return ""
}
// domReady is called after front-end resources have been loaded
func (a *App) domReady(ctx context.Context) {
defer PanicHandler()
@@ -418,6 +544,10 @@ func (a *App) domReady(ctx context.Context) {
if interval <= 0 {
interval = 1
}
a.cron.AddFunc(fmt.Sprintf("@every %ds", interval+60), func() {
data.NewsAnalyze("", true)
})
//ticker := time.NewTicker(time.Second * time.Duration(interval))
//defer ticker.Stop()
//for range ticker.C {
@@ -686,7 +816,7 @@ func (a *App) AddCronTask(follow data.FollowedStock) func() {
return func() {
go runtime.EventsEmit(a.ctx, "warnMsg", "开始自动分析"+follow.Name+"_"+follow.StockCode)
ai := data.NewDeepSeekOpenAi(a.ctx, follow.AiConfigId)
msgs := ai.NewChatStream(follow.Name, follow.StockCode, "", nil, a.AiTools)
msgs := ai.NewChatStream(follow.Name, follow.StockCode, "", nil, a.AiTools, true)
var res strings.Builder
chatId := ""
@@ -1051,12 +1181,12 @@ func (a *App) SendDingDingMessageByType(message string, stockCode string, msgTyp
return data.NewDingDingAPI().SendDingDingMessage(message)
}
func (a *App) NewChatStream(stock, stockCode, question string, aiConfigId int, sysPromptId *int, enableTools bool) {
func (a *App) NewChatStream(stock, stockCode, question string, aiConfigId int, sysPromptId *int, enableTools bool, think bool) {
var msgs <-chan map[string]any
if enableTools {
msgs = data.NewDeepSeekOpenAi(a.ctx, aiConfigId).NewChatStream(stock, stockCode, question, sysPromptId, a.AiTools)
msgs = data.NewDeepSeekOpenAi(a.ctx, aiConfigId).NewChatStream(stock, stockCode, question, sysPromptId, a.AiTools, think)
} else {
msgs = data.NewDeepSeekOpenAi(a.ctx, aiConfigId).NewChatStream(stock, stockCode, question, sysPromptId, []data.Tool{})
msgs = data.NewDeepSeekOpenAi(a.ctx, aiConfigId).NewChatStream(stock, stockCode, question, sysPromptId, []data.Tool{}, think)
}
for msg := range msgs {
runtime.EventsEmit(a.ctx, "newChatStream", msg)
@@ -1386,12 +1516,12 @@ func (a *App) GlobalStockIndexes() map[string]any {
return data.NewMarketNewsApi().GlobalStockIndexes(30)
}
func (a *App) SummaryStockNews(question string, aiConfigId int, sysPromptId *int, enableTools bool) {
func (a *App) SummaryStockNews(question string, aiConfigId int, sysPromptId *int, enableTools bool, think bool) {
var msgs <-chan map[string]any
if enableTools {
msgs = data.NewDeepSeekOpenAi(a.ctx, aiConfigId).NewSummaryStockNewsStreamWithTools(question, sysPromptId, a.AiTools)
msgs = data.NewDeepSeekOpenAi(a.ctx, aiConfigId).NewSummaryStockNewsStreamWithTools(question, sysPromptId, a.AiTools, think)
} else {
msgs = data.NewDeepSeekOpenAi(a.ctx, aiConfigId).NewSummaryStockNewsStream(question, sysPromptId)
msgs = data.NewDeepSeekOpenAi(a.ctx, aiConfigId).NewSummaryStockNewsStream(question, sysPromptId, think)
}
for msg := range msgs {

View File

@@ -4,7 +4,6 @@ import (
"go-stock/backend/agent"
"go-stock/backend/data"
"go-stock/backend/models"
"strings"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
@@ -32,7 +31,7 @@ func (a *App) EMDictCode(code string) []any {
return data.NewMarketNewsApi().EMDictCode(code, a.cache)
}
func (a *App) AnalyzeSentiment(text string) data.SentimentResult {
func (a *App) AnalyzeSentiment(text string) models.SentimentResult {
return data.AnalyzeSentiment(text)
}
@@ -75,17 +74,7 @@ func (a *App) ChatWithAgent(question string, aiConfigId int, sysPromptId *int) {
}
func (a *App) AnalyzeSentimentWithFreqWeight(text string) map[string]any {
if text == "" {
telegraphs := data.NewMarketNewsApi().GetNews24HoursList("", 1000*10)
messageText := strings.Builder{}
for _, telegraph := range *telegraphs {
messageText.WriteString(telegraph.Content + "\n")
}
text = messageText.String()
}
result, frequencies := data.AnalyzeSentimentWithFreqWeight(text)
// 过滤标点符号和分隔符
cleanFrequencies := data.FilterAndSortWords(frequencies)
result, cleanFrequencies := data.NewsAnalyze(text, false)
return map[string]any{
"result": result,
"frequencies": cleanFrequencies,

View File

@@ -55,7 +55,6 @@ func (m MarketNewsApi) TelegraphList(crawlTimeOut int64) *[]models.Telegraph {
news := v.(map[string]any)
ctime, _ := convertor.ToInt(news["ctime"])
dataTime := time.Unix(ctime, 0).Local()
logger.SugaredLogger.Debugf("dataTime: %s", dataTime)
telegraph := models.Telegraph{
Title: news["title"].(string),
Content: news["content"].(string),
@@ -67,7 +66,11 @@ func (m MarketNewsApi) TelegraphList(crawlTimeOut int64) *[]models.Telegraph {
SentimentResult: AnalyzeSentiment(news["content"].(string)).Description,
}
cnt := int64(0)
db.Dao.Model(telegraph).Where("time=? and content=?", telegraph.Time, telegraph.Content).Count(&cnt)
if telegraph.Title == "" {
db.Dao.Model(telegraph).Where("content=?", telegraph.Content).Count(&cnt)
} else {
db.Dao.Model(telegraph).Where("title=?", telegraph.Title).Count(&cnt)
}
if cnt > 0 {
continue
}
@@ -225,6 +228,29 @@ func (m MarketNewsApi) GetTelegraphList(source string) *[]*models.Telegraph {
}
return news
}
func (m MarketNewsApi) GetTelegraphListWithPaging(source string, page, pageSize int) *[]*models.Telegraph {
// 计算偏移量
offset := (page - 1) * pageSize
news := &[]*models.Telegraph{}
if source != "" {
db.Dao.Model(news).Preload("TelegraphTags").Where("source=?", source).Order("data_time desc,time desc").Limit(pageSize).Offset(offset).Find(news)
} else {
db.Dao.Model(news).Preload("TelegraphTags").Order("data_time desc,time desc").Limit(pageSize).Offset(offset).Find(news)
}
for _, item := range *news {
tags := &[]models.Tags{}
db.Dao.Model(&models.Tags{}).Where("id in ?", lo.Map(item.TelegraphTags, func(item models.TelegraphTags, index int) uint {
return item.TagId
})).Find(&tags)
tagNames := lo.Map(*tags, func(item models.Tags, index int) string {
return item.Name
})
item.SubjectTags = tagNames
logger.SugaredLogger.Infof("tagNames %v SubjectTags%s", tagNames, item.SubjectTags)
}
return news
}
func (m MarketNewsApi) GetSinaNews(crawlTimeOut uint) *[]models.Telegraph {
news := &[]models.Telegraph{}
@@ -266,6 +292,7 @@ func (m MarketNewsApi) GetSinaNews(crawlTimeOut uint) *[]models.Telegraph {
data := item.(map[string]any)
//logger.SugaredLogger.Infof("%s:%s", data["create_time"], data["rich_text"])
telegraph.Content = data["rich_text"].(string)
telegraph.Title = strutil.SubInBetween(data["rich_text"].(string), "【", "】")
telegraph.Time = strings.Split(data["create_time"].(string), " ")[1]
dataTime, _ := time.ParseInLocation("2006-01-02 15:04:05", data["create_time"].(string), time.Local)
if &dataTime != nil {
@@ -289,7 +316,11 @@ func (m MarketNewsApi) GetSinaNews(crawlTimeOut uint) *[]models.Telegraph {
if telegraph.Content != "" {
telegraph.SentimentResult = AnalyzeSentiment(telegraph.Content).Description
cnt := int64(0)
db.Dao.Model(telegraph).Where("content=? and source=?", telegraph.Content, telegraph.Source).Count(&cnt)
if telegraph.Title == "" {
db.Dao.Model(telegraph).Where("content=?", telegraph.Content).Count(&cnt)
} else {
db.Dao.Model(telegraph).Where("title=?", telegraph.Title).Count(&cnt)
}
if cnt == 0 {
db.Dao.Create(&telegraph)
telegraphs = append(telegraphs, telegraph)
@@ -702,7 +733,11 @@ func (m MarketNewsApi) TradingViewNews() *[]models.Telegraph {
SentimentResult: sentimentResult,
}
cnt := int64(0)
db.Dao.Model(telegraph).Where("time=? and title=? and source=?", telegraph.Time, telegraph.Title, "外媒").Count(&cnt)
if telegraph.Title == "" {
db.Dao.Model(telegraph).Where("content=?", telegraph.Content).Count(&cnt)
} else {
db.Dao.Model(telegraph).Where("title=?", telegraph.Title).Count(&cnt)
}
if cnt > 0 {
continue
}

View File

@@ -92,12 +92,13 @@ func TestStockResearchReport(t *testing.T) {
func TestIndustryResearchReport(t *testing.T) {
db.Init("../../data/stock.db")
resp := NewMarketNewsApi().IndustryResearchReport("456", 7)
resp := NewMarketNewsApi().IndustryResearchReport("", 7)
for _, a := range resp {
logger.SugaredLogger.Debugf("value: %+v", a)
data := a.(map[string]any)
logger.SugaredLogger.Debugf("value: %s infoCode:%s", data["title"], data["infoCode"])
NewMarketNewsApi().GetIndustryReportInfo(data["infoCode"].(string))
logger.SugaredLogger.Debugf("url: https://pdf.dfcfw.com/pdf/H3_%s_1.pdf", data["infoCode"])
//NewMarketNewsApi().GetIndustryReportInfo(data["infoCode"].(string))
}
}
@@ -141,6 +142,8 @@ func TestXUEQIUHotStock(t *testing.T) {
logger.SugaredLogger.Debugf("value: %+v", a)
}
md := util.MarkdownTableWithTitle("当前热门股票排名", res)
logger.SugaredLogger.Debugf(md)
}
func TestHotEvent(t *testing.T) {
@@ -234,7 +237,7 @@ func TestReutersNew(t *testing.T) {
func TestInteractiveAnswer(t *testing.T) {
db.Init("../../data/stock.db")
datas := NewMarketNewsApi().InteractiveAnswer(1, 100, "")
datas := NewMarketNewsApi().InteractiveAnswer(1, 100, "立讯精密")
logger.SugaredLogger.Debugf("PageSize:%d", datas.PageSize)
md := util.MarkdownTableWithTitle("投资互动", datas.Results)
logger.SugaredLogger.Debugf(md)

View File

@@ -17,6 +17,7 @@ import (
"github.com/PuerkitoBio/goquery"
"github.com/chromedp/chromedp"
"github.com/duke-git/lancet/v2/convertor"
"github.com/duke-git/lancet/v2/mathutil"
"github.com/duke-git/lancet/v2/random"
"github.com/duke-git/lancet/v2/strutil"
"github.com/go-resty/resty/v2"
@@ -135,17 +136,19 @@ type Tool struct {
Function ToolFunction `json:"function"`
}
type FunctionParameters struct {
Type string `json:"type"`
Properties map[string]any `json:"properties"`
Required []string `json:"required"`
Type string `json:"type"`
Properties map[string]any `json:"properties"`
Required []string `json:"required"`
AdditionalProperties bool `json:"additionalProperties"`
}
type ToolFunction struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters FunctionParameters `json:"parameters"`
Name string `json:"name"`
Strict bool `json:"strict"`
Description string `json:"description"`
Parameters *FunctionParameters `json:"parameters"`
}
func (o *OpenAi) NewSummaryStockNewsStreamWithTools(userQuestion string, sysPromptId *int, tools []Tool) <-chan map[string]any {
func (o *OpenAi) NewSummaryStockNewsStreamWithTools(userQuestion string, sysPromptId *int, tools []Tool, thinking bool) <-chan map[string]any {
ch := make(chan map[string]any, 512)
defer func() {
if err := recover(); err != nil {
@@ -185,12 +188,27 @@ func (o *OpenAi) NewSummaryStockNewsStreamWithTools(userQuestion string, sysProm
"content": "当前时间",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"content": "当前本地时间是:" + time.Now().Format("2006-01-02 15:04:05"),
"role": "assistant",
"reasoning_content": "使用工具查询",
"content": "当前本地时间是:" + time.Now().Format("2006-01-02 15:04:05"),
})
wg := &sync.WaitGroup{}
wg.Add(6)
wg.Add(5)
go func() {
defer wg.Done()
res := NewMarketNewsApi().XUEQIUHotStock(50, "10")
md := util.MarkdownTableWithTitle("当前热门股票排名", res)
msg = append(msg, map[string]interface{}{
"role": "user",
"content": "当前热门股票排名数据",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"reasoning_content": "使用工具查询",
"content": md,
})
}()
go func() {
defer wg.Done()
datas := NewMarketNewsApi().InteractiveAnswer(1, 100, "")
@@ -200,8 +218,9 @@ func (o *OpenAi) NewSummaryStockNewsStreamWithTools(userQuestion string, sysProm
"content": "投资者互动数据",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"content": content,
"role": "assistant",
"reasoning_content": "使用工具查询",
"content": content,
})
}()
@@ -226,34 +245,36 @@ func (o *OpenAi) NewSummaryStockNewsStreamWithTools(userQuestion string, sysProm
"content": "国内宏观经济数据",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"content": "\n# 国内宏观经济数据:\n" + market.String(),
"role": "assistant",
"reasoning_content": "使用工具查询",
"content": "\n# 国内宏观经济数据:\n" + market.String(),
})
}()
go func() {
defer wg.Done()
var market strings.Builder
market.WriteString(GetZSInfo("上证指数", "sh000001", 30) + "\n")
market.WriteString(GetZSInfo("深证成指", "sz399001", 30) + "\n")
market.WriteString(GetZSInfo("创业板指数", "sz399006", 30) + "\n")
market.WriteString(GetZSInfo("科创50", "sh000688", 30) + "\n")
market.WriteString(GetZSInfo("沪深300指数", "sh000300", 30) + "\n")
market.WriteString(GetZSInfo("中证银行", "sz399986", 30) + "\n")
market.WriteString(GetZSInfo("科创芯片", "sh000685", 30) + "\n")
market.WriteString(GetZSInfo("上证医药", "sh000037", 30) + "\n")
market.WriteString(GetZSInfo("证券龙头", "sz399437", 30) + "\n")
market.WriteString(GetZSInfo("中证白酒", "sz399997", 30) + "\n")
//logger.SugaredLogger.Infof("NewChatStream getZSInfo=\n%s", market.String())
msg = append(msg, map[string]interface{}{
"role": "user",
"content": "当前市场/大盘/行业/指数行情",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"content": "当前市场/大盘/行业/指数行情如下:\n" + market.String(),
})
}()
//go func() {
// defer wg.Done()
// var market strings.Builder
// market.WriteString(GetZSInfo("上证指数", "sh000001", 5) + "\n")
// market.WriteString(GetZSInfo("深证成指", "sz399001", 5) + "\n")
// market.WriteString(GetZSInfo("创业板指数", "sz399006", 5) + "\n")
// market.WriteString(GetZSInfo("科创50", "sh000688", 5) + "\n")
// market.WriteString(GetZSInfo("沪深300指数", "sh000300", 5) + "\n")
// market.WriteString(GetZSInfo("中证银行", "sz399986", 5) + "\n")
// //market.WriteString(GetZSInfo("科创芯片", "sh000685", 30) + "\n")
// //market.WriteString(GetZSInfo("上证医药", "sh000037", 30) + "\n")
// //market.WriteString(GetZSInfo("证券龙头", "sz399437", 30) + "\n")
// //market.WriteString(GetZSInfo("中证白酒", "sz399997", 30) + "\n")
// //logger.SugaredLogger.Infof("NewChatStream getZSInfo=\n%s", market.String())
// msg = append(msg, map[string]interface{}{
// "role": "user",
// "content": "当前市场/大盘/行业/指数行情",
// })
// msg = append(msg, map[string]interface{}{
// "role": "assistant",
// "reasoning_content": "使用工具查询",
// "content": "当前市场/大盘/行业/指数行情如下:\n" + market.String(),
// })
//}()
go func() {
defer wg.Done()
@@ -280,65 +301,73 @@ func (o *OpenAi) NewSummaryStockNewsStreamWithTools(userQuestion string, sysProm
"content": "近期重大事件/会议",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"content": "近期重大事件/会议如下:\n" + md.String(),
"role": "assistant",
"reasoning_content": "使用工具查询",
"content": "近期重大事件/会议如下:\n" + md.String(),
})
}()
go func() {
defer wg.Done()
resp := NewMarketNewsApi().TradingViewNews()
var newsText strings.Builder
//go func() {
// defer wg.Done()
// resp := NewMarketNewsApi().TradingViewNews()
// var newsText strings.Builder
//
// for _, a := range *resp {
// logger.SugaredLogger.Debugf("TradingViewNews: %s", a.Title)
// newsText.WriteString(a.Title + "\n")
// }
// msg = append(msg, map[string]interface{}{
// "role": "user",
// "content": "全球新闻资讯",
// })
// msg = append(msg, map[string]interface{}{
// "role": "assistant",
// "reasoning_content": "使用工具查询",
// "content": newsText.String(),
// })
//}()
for _, a := range *resp {
logger.SugaredLogger.Debugf("TradingViewNews: %s", a.Title)
newsText.WriteString(a.Title + "\n")
}
msg = append(msg, map[string]interface{}{
"role": "user",
"content": "全球新闻资讯",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"content": newsText.String(),
})
}()
//go func() {
// defer wg.Done()
// news := NewMarketNewsApi().ReutersNew()
// messageText := strings.Builder{}
// for _, article := range news.Result.Articles {
// messageText.WriteString("## " + article.Title + "\n")
// messageText.WriteString("### " + article.Description + "\n")
// }
// msg = append(msg, map[string]interface{}{
// "role": "user",
// "content": "外媒全球新闻资讯",
// })
// msg = append(msg, map[string]interface{}{
// "role": "assistant",
// "reasoning_content": "使用工具查询",
// "content": messageText.String(),
// })
//}()
go func() {
defer wg.Done()
news := NewMarketNewsApi().ReutersNew()
news := NewMarketNewsApi().GetNews24HoursList("最新24小时市场资讯", random.RandInt(200, 1000))
messageText := strings.Builder{}
for _, article := range news.Result.Articles {
messageText.WriteString("## " + article.Title + "\n")
messageText.WriteString("### " + article.Description + "\n")
for _, telegraph := range *news {
messageText.WriteString("## " + telegraph.DataTime.Format("2006-01-02 15:04:05") + ":" + "\n")
messageText.WriteString("### " + telegraph.Content + "\n")
}
msg = append(msg, map[string]interface{}{
"role": "user",
"content": "外媒全球新闻资讯",
"content": "市场资讯",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"content": messageText.String(),
"role": "assistant",
"reasoning_content": "使用工具查询",
"content": messageText.String(),
})
}()
wg.Wait()
news := NewMarketNewsApi().GetNewsList2("财联社电报", random.RandInt(100, 500))
messageText := strings.Builder{}
for _, telegraph := range *news {
messageText.WriteString("## " + telegraph.Time + ":" + "\n")
messageText.WriteString("### " + telegraph.Content + "\n")
}
//logger.SugaredLogger.Infof("市场资讯 messageText=\n%s", messageText.String())
msg = append(msg, map[string]interface{}{
"role": "user",
"content": "市场资讯",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"content": messageText.String(),
})
wg.Wait()
if userQuestion == "" {
userQuestion = "请根据当前时间,总结和分析股票市场新闻中的投资机会"
}
@@ -346,12 +375,12 @@ func (o *OpenAi) NewSummaryStockNewsStreamWithTools(userQuestion string, sysProm
"role": "user",
"content": userQuestion,
})
AskAiWithTools(o, errors.New(""), msg, ch, userQuestion, tools)
AskAiWithTools(o, errors.New(""), msg, ch, userQuestion, tools, thinking)
}()
return ch
}
func (o *OpenAi) NewSummaryStockNewsStream(userQuestion string, sysPromptId *int) <-chan map[string]any {
func (o *OpenAi) NewSummaryStockNewsStream(userQuestion string, sysPromptId *int, think bool) <-chan map[string]any {
ch := make(chan map[string]any, 512)
defer func() {
if err := recover(); err != nil {
@@ -395,66 +424,98 @@ func (o *OpenAi) NewSummaryStockNewsStream(userQuestion string, sysPromptId *int
"content": "当前本地时间是:" + time.Now().Format("2006-01-02 15:04:05"),
})
wg := &sync.WaitGroup{}
wg.Add(4)
go func() {
defer wg.Done()
var market strings.Builder
market.WriteString(GetZSInfo("上证指数", "sh000001", 30) + "\n")
market.WriteString(GetZSInfo("深证成指", "sz399001", 30) + "\n")
market.WriteString(GetZSInfo("创业板指数", "sz399006", 30) + "\n")
market.WriteString(GetZSInfo("科创50", "sh000688", 30) + "\n")
market.WriteString(GetZSInfo("沪深300指数", "sh000300", 30) + "\n")
market.WriteString(GetZSInfo("中证银行", "sz399986", 30) + "\n")
market.WriteString(GetZSInfo("科创芯片", "sh000685", 30) + "\n")
market.WriteString(GetZSInfo("上证医药", "sh000037", 30) + "\n")
market.WriteString(GetZSInfo("证券龙头", "sz399437", 30) + "\n")
market.WriteString(GetZSInfo("中证白酒", "sz399997", 30) + "\n")
//logger.SugaredLogger.Infof("NewChatStream getZSInfo=\n%s", market.String())
msg = append(msg, map[string]interface{}{
"role": "user",
"content": "当前市场指数行情",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"content": "当前市场指数行情情况如下:\n" + market.String(),
})
}()
go func() {
defer wg.Done()
resp := NewMarketNewsApi().TradingViewNews()
var newsText strings.Builder
for _, a := range *resp {
logger.SugaredLogger.Debugf("TradingViewNews: %s", a.Title)
newsText.WriteString(a.Title + "\n")
}
msg = append(msg, map[string]interface{}{
"role": "user",
"content": "外媒全球新闻资讯",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"content": newsText.String(),
})
}()
wg.Add(3)
//go func() {
// defer wg.Done()
// var market strings.Builder
// market.WriteString(GetZSInfo("上证指数", "sh000001", 5) + "\n")
// market.WriteString(GetZSInfo("深证成指", "sz399001", 5) + "\n")
// market.WriteString(GetZSInfo("创业板指数", "sz399006", 5) + "\n")
// market.WriteString(GetZSInfo("科创50", "sh000688", 5) + "\n")
// market.WriteString(GetZSInfo("沪深300指数", "sh000300", 5) + "\n")
// market.WriteString(GetZSInfo("中证银行", "sz399986", 5) + "\n")
// //market.WriteString(GetZSInfo("科创芯片", "sh000685", 30) + "\n")
// //market.WriteString(GetZSInfo("上证医药", "sh000037", 30) + "\n")
// //market.WriteString(GetZSInfo("证券龙头", "sz399437", 30) + "\n")
// //market.WriteString(GetZSInfo("中证白酒", "sz399997", 30) + "\n")
// //logger.SugaredLogger.Infof("NewChatStream getZSInfo=\n%s", market.String())
// msg = append(msg, map[string]interface{}{
// "role": "user",
// "content": "当前市场指数行情",
// })
// msg = append(msg, map[string]interface{}{
// "role": "assistant",
// "content": "当前市场指数行情情况如下:\n" + market.String(),
// })
//}()
go func() {
defer wg.Done()
news := NewMarketNewsApi().ReutersNew()
messageText := strings.Builder{}
for _, article := range news.Result.Articles {
messageText.WriteString("## " + article.Title + "\n")
messageText.WriteString("### " + article.Description + "\n")
md := strings.Builder{}
res := NewMarketNewsApi().ClsCalendar()
for _, a := range res {
bytes, err := json.Marshal(a)
if err != nil {
continue
}
//logger.SugaredLogger.Debugf("value: %+v", string(bytes))
date := gjson.Get(string(bytes), "calendar_day")
md.WriteString("\n### 事件/会议日期:" + date.String())
list := gjson.Get(string(bytes), "items")
//logger.SugaredLogger.Debugf("value: %+v,list: %+v", date.String(), list)
list.ForEach(func(key, value gjson.Result) bool {
logger.SugaredLogger.Debugf("key: %+v,value: %+v", key.String(), gjson.Get(value.String(), "title"))
md.WriteString("\n- " + gjson.Get(value.String(), "title").String())
return true
})
}
msg = append(msg, map[string]interface{}{
"role": "user",
"content": "外媒全球新闻资讯",
"content": "近期重大事件/会议",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"content": messageText.String(),
"role": "assistant",
"reasoning_content": "使用工具查询",
"content": "近期重大事件/会议如下:\n" + md.String(),
})
}()
//go func() {
// defer wg.Done()
// resp := NewMarketNewsApi().TradingViewNews()
// var newsText strings.Builder
//
// for _, a := range *resp {
// logger.SugaredLogger.Debugf("TradingViewNews: %s", a.Title)
// newsText.WriteString(a.Title + "\n")
// }
// msg = append(msg, map[string]interface{}{
// "role": "user",
// "content": "外媒全球新闻资讯",
// })
// msg = append(msg, map[string]interface{}{
// "role": "assistant",
// "content": newsText.String(),
// })
//}()
//go func() {
// defer wg.Done()
// news := NewMarketNewsApi().ReutersNew()
// messageText := strings.Builder{}
// for _, article := range news.Result.Articles {
// messageText.WriteString("## " + article.Title + "\n")
// messageText.WriteString("### " + article.Description + "\n")
// }
// msg = append(msg, map[string]interface{}{
// "role": "user",
// "content": "外媒全球新闻资讯",
// })
// msg = append(msg, map[string]interface{}{
// "role": "assistant",
// "content": messageText.String(),
// })
//}()
go func() {
defer wg.Done()
@@ -470,9 +531,30 @@ func (o *OpenAi) NewSummaryStockNewsStream(userQuestion string, sysPromptId *int
})
}()
go func() {
defer wg.Done()
markdownTable := ""
res := NewSearchStockApi("").HotStrategy()
bytes, _ := json.Marshal(res)
strategy := &models.HotStrategy{}
json.Unmarshal(bytes, strategy)
for _, data := range strategy.Data {
data.Chg = mathutil.RoundToFloat(100*data.Chg, 2)
}
markdownTable = util.MarkdownTableWithTitle("当前热门选股策略", strategy.Data)
msg = append(msg, map[string]interface{}{
"role": "user",
"content": "当前热门选股策略",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"content": markdownTable,
})
}()
wg.Wait()
news := NewMarketNewsApi().GetNewsList2("财联社电报", random.RandInt(100, 500))
news := NewMarketNewsApi().GetNews24HoursList("最近24小时市场资讯", random.RandInt(200, 1000))
messageText := strings.Builder{}
for _, telegraph := range *news {
messageText.WriteString("## " + telegraph.Time + ":" + "\n")
@@ -495,12 +577,12 @@ func (o *OpenAi) NewSummaryStockNewsStream(userQuestion string, sysPromptId *int
"role": "user",
"content": userQuestion,
})
AskAi(o, errors.New(""), msg, ch, userQuestion)
AskAi(o, errors.New(""), msg, ch, userQuestion, think)
}()
return ch
}
func (o *OpenAi) NewChatStream(stock, stockCode, userQuestion string, sysPromptId *int, tools []Tool) <-chan map[string]any {
func (o *OpenAi) NewChatStream(stock, stockCode, userQuestion string, sysPromptId *int, tools []Tool, thinking bool) <-chan map[string]any {
ch := make(chan map[string]any, 512)
defer func() {
@@ -588,21 +670,103 @@ func (o *OpenAi) NewChatStream(stock, stockCode, userQuestion string, sysPromptI
go func() {
defer wg.Done()
var market strings.Builder
market.WriteString(GetZSInfo("创业板指数", "sz399006", 30) + "\n")
market.WriteString(GetZSInfo("上证综合指数", "sh000001", 30) + "\n")
market.WriteString(GetZSInfo("沪深300指数", "sh000300", 30) + "\n")
//logger.SugaredLogger.Infof("NewChatStream getZSInfo=\n%s", market.String())
datas := NewMarketNewsApi().InteractiveAnswer(1, 100, stock)
content := util.MarkdownTableWithTitle("当前最新投资者互动数据", datas.Results)
msg = append(msg, map[string]interface{}{
"role": "user",
"content": "市场指数",
"content": "投资者互动数据",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"content": "市场指数情况如下:\n" + market.String(),
"role": "assistant",
"reasoning_content": "使用工具查询",
"content": content,
})
}()
go func() {
defer wg.Done()
var market strings.Builder
res := NewMarketNewsApi().GetGDP()
md := util.MarkdownTableWithTitle("国内生产总值(GDP)", res.GDPResult.Data)
market.WriteString(md)
res2 := NewMarketNewsApi().GetCPI()
md2 := util.MarkdownTableWithTitle("居民消费价格指数(CPI)", res2.CPIResult.Data)
market.WriteString(md2)
res3 := NewMarketNewsApi().GetPPI()
md3 := util.MarkdownTableWithTitle("工业品出厂价格指数(PPI)", res3.PPIResult.Data)
market.WriteString(md3)
res4 := NewMarketNewsApi().GetPMI()
md4 := util.MarkdownTableWithTitle("采购经理人指数(PMI)", res4.PMIResult.Data)
market.WriteString(md4)
msg = append(msg, map[string]interface{}{
"role": "user",
"content": "国内宏观经济数据",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"reasoning_content": "使用工具查询",
"content": "\n# 国内宏观经济数据:\n" + market.String(),
})
}()
//go func() {
// defer wg.Done()
// var market strings.Builder
// market.WriteString(GetZSInfo("上证指数", "sh000001", 5) + "\n")
// market.WriteString(GetZSInfo("深证成指", "sz399001", 5) + "\n")
// market.WriteString(GetZSInfo("创业板指数", "sz399006", 5) + "\n")
// market.WriteString(GetZSInfo("科创50", "sh000688", 5) + "\n")
// market.WriteString(GetZSInfo("沪深300指数", "sh000300", 5) + "\n")
// market.WriteString(GetZSInfo("中证银行", "sz399986", 5) + "\n")
// //market.WriteString(GetZSInfo("科创芯片", "sh000685", 30) + "\n")
// //market.WriteString(GetZSInfo("上证医药", "sh000037", 30) + "\n")
// //market.WriteString(GetZSInfo("证券龙头", "sz399437", 30) + "\n")
// //market.WriteString(GetZSInfo("中证白酒", "sz399997", 30) + "\n")
// //logger.SugaredLogger.Infof("NewChatStream getZSInfo=\n%s", market.String())
// msg = append(msg, map[string]interface{}{
// "role": "user",
// "content": "当前市场/大盘/行业/指数行情",
// })
// msg = append(msg, map[string]interface{}{
// "role": "assistant",
// "reasoning_content": "使用工具查询",
// "content": "当前市场/大盘/行业/指数行情如下:\n" + market.String(),
// })
//}()
go func() {
defer wg.Done()
md := strings.Builder{}
res := NewMarketNewsApi().ClsCalendar()
for _, a := range res {
bytes, err := json.Marshal(a)
if err != nil {
continue
}
//logger.SugaredLogger.Debugf("value: %+v", string(bytes))
date := gjson.Get(string(bytes), "calendar_day")
md.WriteString("\n### 事件/会议日期:" + date.String())
list := gjson.Get(string(bytes), "items")
//logger.SugaredLogger.Debugf("value: %+v,list: %+v", date.String(), list)
list.ForEach(func(key, value gjson.Result) bool {
logger.SugaredLogger.Debugf("key: %+v,value: %+v", key.String(), gjson.Get(value.String(), "title"))
md.WriteString("\n- " + gjson.Get(value.String(), "title").String())
return true
})
}
msg = append(msg, map[string]interface{}{
"role": "user",
"content": "近期重大事件/会议",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"reasoning_content": "使用工具查询",
"content": "近期重大事件/会议如下:\n" + md.String(),
})
}()
go func() {
defer wg.Done()
//endDate := time.Now().Format("20060102")
@@ -720,7 +884,7 @@ func (o *OpenAi) NewChatStream(stock, stockCode, userQuestion string, sysPromptI
go func() {
defer wg.Done()
messages := GetTelegraphList(o.CrawlTimeOut)
messages := NewMarketNewsApi().GetNews24HoursList("", random.RandInt(200, 1000))
if messages == nil || len(*messages) == 0 {
logger.SugaredLogger.Error("获取市场资讯失败")
//ch <- "***❗获取市场资讯失败,分析结果可能不准确***<hr>"
@@ -728,8 +892,9 @@ func (o *OpenAi) NewChatStream(stock, stockCode, userQuestion string, sysPromptI
return
}
var messageText strings.Builder
for _, message := range *messages {
messageText.WriteString(message + "\n")
for _, telegraph := range *messages {
messageText.WriteString("## " + telegraph.Time + ":" + "\n")
messageText.WriteString("### " + telegraph.Content + "\n")
}
msg = append(msg, map[string]interface{}{
"role": "user",
@@ -739,26 +904,6 @@ func (o *OpenAi) NewChatStream(stock, stockCode, userQuestion string, sysPromptI
"role": "assistant",
"content": messageText.String(),
})
messages = GetTopNewsList(o.CrawlTimeOut)
if messages == nil || len(*messages) == 0 {
logger.SugaredLogger.Error("获取新闻资讯失败")
//ch <- "***❗获取新闻资讯失败,分析结果可能不准确***<hr>"
//go runtime.EventsEmit(o.ctx, "warnMsg", "❗获取新闻资讯失败,分析结果可能不准确")
return
}
var newsText strings.Builder
for _, message := range *messages {
newsText.WriteString(message + "\n")
}
msg = append(msg, map[string]interface{}{
"role": "user",
"content": "新闻资讯",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"content": newsText.String(),
})
}()
//go func() {
@@ -800,54 +945,8 @@ func (o *OpenAi) NewChatStream(stock, stockCode, userQuestion string, sysPromptI
})
}()
go func() {
defer wg.Done()
if checkIsIndexBasic(stock) {
return
}
//messages := SearchGuShiTongStockInfo(stockCode, o.CrawlTimeOut)
//if messages == nil || len(*messages) == 0 {
// logger.SugaredLogger.Error("获取股势通资讯失败")
// //ch <- "***❗获取股势通资讯失败,分析结果可能不准确***<hr>"
// //go runtime.EventsEmit(o.ctx, "warnMsg", "❗获取股势通资讯失败,分析结果可能不准确")
// return
//}
//var newsText strings.Builder
//for _, message := range *messages {
// newsText.WriteString(message + "\n")
//}
//msg = append(msg, map[string]interface{}{
// "role": "user",
// "content": stock + "相关新闻资讯",
//})
//msg = append(msg, map[string]interface{}{
// "role": "assistant",
// "content": newsText.String(),
//})
}()
go func() {
defer wg.Done()
resp := NewMarketNewsApi().TradingViewNews()
var newsText strings.Builder
for _, a := range *resp {
logger.SugaredLogger.Debugf("value: %s", a.Title)
newsText.WriteString(a.Title + "\n")
}
msg = append(msg, map[string]interface{}{
"role": "user",
"content": "外媒全球新闻资讯",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"content": newsText.String(),
})
}()
wg.Wait()
msg = append(msg, map[string]interface{}{
"role": "user",
"content": question,
@@ -856,15 +955,15 @@ func (o *OpenAi) NewChatStream(stock, stockCode, userQuestion string, sysPromptI
//reqJson, _ := json.Marshal(msg)
//logger.SugaredLogger.Errorf("Stream request: \n%s\n", reqJson)
if tools != nil && len(tools) > 0 {
AskAiWithTools(o, err, msg, ch, question, tools)
AskAiWithTools(o, err, msg, ch, question, tools, thinking)
} else {
AskAi(o, err, msg, ch, question)
AskAi(o, err, msg, ch, question, thinking)
}
}()
return ch
}
func AskAi(o *OpenAi, err error, messages []map[string]interface{}, ch chan map[string]any, question string) {
func AskAi(o *OpenAi, err error, messages []map[string]interface{}, ch chan map[string]any, question string, think bool) {
client := resty.New()
client.SetBaseURL(strutil.Trim(o.BaseUrl))
client.SetHeader("Authorization", "Bearer "+o.ApiKey)
@@ -873,13 +972,17 @@ func AskAi(o *OpenAi, err error, messages []map[string]interface{}, ch chan map[
if o.TimeOut <= 0 {
o.TimeOut = 300
}
thinking := "disabled"
if think {
thinking = "enabled"
}
client.SetTimeout(time.Duration(o.TimeOut) * time.Second)
resp, err := client.R().
SetDoNotParseResponse(true).
SetBody(map[string]interface{}{
"model": o.Model,
"thinking": map[string]any{
"type": "disabled",
"type": thinking,
},
"max_tokens": o.MaxTokens,
"temperature": o.Temperature,
@@ -1008,7 +1111,10 @@ func AskAi(o *OpenAi, err error, messages []map[string]interface{}, ch chan map[
}
}
func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch chan map[string]any, question string, tools []Tool) {
func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch chan map[string]any, question string, tools []Tool, thinkingMode bool) {
bytes, _ := json.Marshal(messages)
logger.SugaredLogger.Debugf("Stream request: \n%s\n", string(bytes))
client := resty.New()
client.SetBaseURL(strutil.Trim(o.BaseUrl))
client.SetHeader("Authorization", "Bearer "+o.ApiKey)
@@ -1017,14 +1123,19 @@ func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch
if o.TimeOut <= 0 {
o.TimeOut = 300
}
thinking := "disabled"
if thinkingMode {
thinking = "enabled"
}
client.SetTimeout(time.Duration(o.TimeOut) * time.Second)
resp, err := client.R().
SetDoNotParseResponse(true).
SetBody(map[string]interface{}{
"model": o.Model,
"thinking": map[string]any{
"type": "disabled",
//"type": "disabled",
//"type": "enabled",
"type": thinking,
},
"max_tokens": o.MaxTokens,
"temperature": o.Temperature,
@@ -1202,8 +1313,9 @@ func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch
logger.SugaredLogger.Infof("SearchStockByIndicators:words:%s --> \n%s", words, content)
messages = append(messages, map[string]interface{}{
"role": "assistant",
"content": currentAIContent.String(),
"role": "assistant",
"content": currentAIContent.String(),
"reasoning_content": reasoningContentText.String(),
"tool_calls": []map[string]any{
{
"id": currentCallId,
@@ -1221,6 +1333,9 @@ func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch
"role": "tool",
"content": content,
"tool_call_id": currentCallId,
//"reasoning_content": reasoningContentText.String(),
//"tool_calls": choice.Delta.ToolCalls,
})
//ch <- map[string]any{
@@ -1275,8 +1390,9 @@ func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch
logger.SugaredLogger.Infof("getKLineData=\n%s", markdownTable)
messages = append(messages, map[string]interface{}{
"role": "assistant",
"content": currentAIContent.String(),
"role": "assistant",
"content": currentAIContent.String(),
"reasoning_content": reasoningContentText.String(),
"tool_calls": []map[string]any{
{
"id": currentCallId,
@@ -1295,6 +1411,8 @@ func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch
"role": "tool",
"content": res,
"tool_call_id": currentCallId,
//"reasoning_content": reasoningContentText.String(),
//"tool_calls": choice.Delta.ToolCalls,
})
logger.SugaredLogger.Infof("GetStockKLine:stockCode:%s days:%s --> \n%s", stockCode, days, res)
@@ -1308,8 +1426,9 @@ func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch
//}
} else {
messages = append(messages, map[string]interface{}{
"role": "assistant",
"content": currentAIContent.String(),
"role": "assistant",
"content": currentAIContent.String(),
"reasoning_content": reasoningContentText.String(),
"tool_calls": []map[string]any{
{
"id": currentCallId,
@@ -1327,6 +1446,8 @@ func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch
"role": "tool",
"content": "无数据可能股票代码错误。A股sh,sz开头;港股hk开头,美股us开头",
"tool_call_id": currentCallId,
//"reasoning_content": reasoningContentText.String(),
//"tool_calls": choice.Delta.ToolCalls,
})
}
}
@@ -1355,8 +1476,9 @@ func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch
content := util.MarkdownTableWithTitle("投资互动数据", datas.Results)
logger.SugaredLogger.Infof("InteractiveAnswer=\n%s", content)
messages = append(messages, map[string]interface{}{
"role": "assistant",
"content": currentAIContent.String(),
"role": "assistant",
"content": currentAIContent.String(),
"reasoning_content": reasoningContentText.String(),
"tool_calls": []map[string]any{
{
"id": currentCallId,
@@ -1374,6 +1496,8 @@ func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch
"role": "tool",
"content": content,
"tool_call_id": currentCallId,
//"reasoning_content": reasoningContentText.String(),
//"tool_calls": choice.Delta.ToolCalls,
})
}
//
@@ -1489,8 +1613,9 @@ func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch
}
logger.SugaredLogger.Infof("stockCode:%s StockResearchReport:\n %s", stockCode, md.String())
messages = append(messages, map[string]interface{}{
"role": "assistant",
"content": currentAIContent.String(),
"role": "assistant",
"content": currentAIContent.String(),
"reasoning_content": reasoningContentText.String(),
"tool_calls": []map[string]any{
{
"id": currentCallId,
@@ -1508,11 +1633,95 @@ func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch
"role": "tool",
"content": md.String(),
"tool_call_id": currentCallId,
//"reasoning_content": reasoningContentText.String(),
//"tool_calls": choice.Delta.ToolCalls,
})
}
if funcName == "HotStrategyTable" {
ch <- map[string]any{
"code": 1,
"question": question,
"chatId": streamResponse.Id,
"model": streamResponse.Model,
"content": "\r\n```\r\n开始调用工具HotStrategyTable\n参数" + funcArguments + "\r\n```\r\n",
"time": time.Now().Format(time.DateTime),
}
table := NewSearchStockApi("").HotStrategyTable()
logger.SugaredLogger.Infof("%s", table)
messages = append(messages, map[string]interface{}{
"role": "assistant",
"content": currentAIContent.String(),
"reasoning_content": reasoningContentText.String(),
"tool_calls": []map[string]any{
{
"id": currentCallId,
"tool_call_id": currentCallId,
"type": "function",
"function": map[string]string{
"name": funcName,
"arguments": funcArguments,
"parameters": funcArguments,
},
},
},
})
messages = append(messages, map[string]interface{}{
"role": "tool",
"content": table,
"tool_call_id": currentCallId,
//"reasoning_content": reasoningContentText.String(),
//"tool_calls": choice.Delta.ToolCalls,
})
}
if funcName == "HotStockTable" {
pageSize := gjson.Get(funcArguments, "pageSize").String()
ch <- map[string]any{
"code": 1,
"question": question,
"chatId": streamResponse.Id,
"model": streamResponse.Model,
"content": "\r\n```\r\n开始调用工具HotStockTable\n参数" + funcArguments + "\r\n```\r\n",
"time": time.Now().Format(time.DateTime),
}
pageSizeNum, err := convertor.ToInt(pageSize)
if err != nil {
pageSizeNum = 50
}
res := NewMarketNewsApi().XUEQIUHotStock(int(pageSizeNum), "10")
md := util.MarkdownTableWithTitle("当前热门股票排名", res)
logger.SugaredLogger.Infof("pageSize:%s HotStockTable:\n %s", pageSize, md)
messages = append(messages, map[string]interface{}{
"role": "assistant",
"content": currentAIContent.String(),
"reasoning_content": reasoningContentText.String(),
"tool_calls": []map[string]any{
{
"id": currentCallId,
"tool_call_id": currentCallId,
"type": "function",
"function": map[string]string{
"name": funcName,
"arguments": funcArguments,
"parameters": funcArguments,
},
},
},
})
messages = append(messages, map[string]interface{}{
"role": "tool",
"content": md,
"tool_call_id": currentCallId,
//"reasoning_content": reasoningContentText.String(),
//"tool_calls": choice.Delta.ToolCalls,
})
}
}
AskAiWithTools(o, err, messages, ch, question, tools)
AskAiWithTools(o, err, messages, ch, question, tools, thinkingMode)
}
if choice.FinishReason == "stop" {
@@ -1560,7 +1769,7 @@ func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch
}
newMessages = append(newMessages, message)
}
AskAi(o, err, newMessages, ch, question)
AskAi(o, err, newMessages, ch, question, thinkingMode)
} else {
ch <- map[string]any{
"code": 0,

View File

@@ -17,7 +17,7 @@ func TestNewDeepSeekOpenAiConfig(t *testing.T) {
Function: ToolFunction{
Name: "SearchStockByIndicators",
Description: "根据自然语言筛选股票,返回自然语言选股条件要求的股票所有相关数据",
Parameters: FunctionParameters{
Parameters: &FunctionParameters{
Type: "object",
Properties: map[string]any{
"words": map[string]any{
@@ -32,7 +32,7 @@ func TestNewDeepSeekOpenAiConfig(t *testing.T) {
ai := NewDeepSeekOpenAi(context.TODO(), 0)
//res := ai.NewChatStream("长电科技", "sh600584", "长电科技分析和总结", nil)
res := ai.NewSummaryStockNewsStreamWithTools("总结市场资讯,发掘潜力标的/行业/板块/概念,控制风险。调用工具函数验证", nil, tools)
res := ai.NewSummaryStockNewsStreamWithTools("总结市场资讯,发掘潜力标的/行业/板块/概念,控制风险。调用工具函数验证", nil, tools, true)
for {
select {
@@ -65,6 +65,6 @@ func TestSearchGuShiTongStockInfo(t *testing.T) {
func TestGetZSInfo(t *testing.T) {
db.Init("../../data/stock.db")
GetZSInfo("中证银行", "sz399986", 30)
GetZSInfo("上海贝岭", "sh600171", 30)
GetZSInfo("中证银行", "sz399986", 5)
GetZSInfo("上海贝岭", "sh600171", 5)
}

View File

@@ -4,8 +4,11 @@ import (
"encoding/json"
"fmt"
"go-stock/backend/logger"
"go-stock/backend/models"
"go-stock/backend/util"
"time"
"github.com/duke-git/lancet/v2/mathutil"
"github.com/go-resty/resty/v2"
)
@@ -81,3 +84,35 @@ func (s SearchStockApi) HotStrategy() map[string]any {
json.Unmarshal(resp.Body(), &respMap)
return respMap
}
func (s SearchStockApi) HotStrategyTable() string {
markdownTable := ""
res := s.HotStrategy()
bytes, _ := json.Marshal(res)
strategy := &models.HotStrategy{}
json.Unmarshal(bytes, strategy)
for _, data := range strategy.Data {
data.Chg = mathutil.RoundToFloat(100*data.Chg, 2)
}
markdownTable = util.MarkdownTableWithTitle("当前热门选股策略", strategy.Data)
return markdownTable
}
func (s SearchStockApi) StrategySquare() map[string]any {
//https://backtest.10jqka.com.cn/strategysquare/list?order=desc&page=1&pageNum=10&sortType=hot&keyword=
url := "https://backtest.10jqka.com.cn/strategysquare/list?order=desc&page=1&pageNum=10&sortType=hot&keyword="
resp, err := resty.New().SetTimeout(time.Duration(30)*time.Second).R().
SetHeader("Host", "backtest.10jqka.com.cn").
SetHeader("Origin", "https://backtest.10jqka.com.cn").
SetHeader("Referer", "https://backtest.10jqka.com.cn/strategysquare/list").
SetHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:140.0) Gecko/20100101 Firefox/140.0").
Get(url)
if err != nil {
logger.SugaredLogger.Errorf("StrategySquare-err:%+v", err)
return map[string]any{}
}
respMap := map[string]any{}
json.Unmarshal(resp.Body(), &respMap)
logger.SugaredLogger.Infof("resp:%+v", respMap["data"])
return respMap
}

View File

@@ -4,10 +4,13 @@ import (
"encoding/json"
"go-stock/backend/db"
"go-stock/backend/logger"
"go-stock/backend/models"
"go-stock/backend/util"
"math"
"testing"
"github.com/duke-git/lancet/v2/convertor"
"github.com/duke-git/lancet/v2/mathutil"
"github.com/duke-git/lancet/v2/random"
)
@@ -60,10 +63,25 @@ func TestSearchStock(t *testing.T) {
func TestSearchStockApi_HotStrategy(t *testing.T) {
db.Init("../../data/stock.db")
res := NewSearchStockApi("").HotStrategy()
logger.SugaredLogger.Infof("res:%+v", res)
dataList := res["data"].([]any)
for _, v := range dataList {
d := v.(map[string]any)
logger.SugaredLogger.Infof("v:%+v", d)
bytes, err := json.Marshal(res)
if err != nil {
return
}
strategy := &models.HotStrategy{}
json.Unmarshal(bytes, strategy)
for _, data := range strategy.Data {
data.Chg = mathutil.RoundToFloat(100*data.Chg, 2)
}
markdownTable := util.MarkdownTable(strategy.Data)
logger.SugaredLogger.Infof("res:%s", markdownTable)
//dataList := res["data"].([]any)
//for _, v := range dataList {
// d := v.(map[string]any)
// logger.SugaredLogger.Infof("v:%+v", d)
//}
}
func TestSearchStockApi_HotStrategyTable(t *testing.T) {
db.Init("../../data/stock.db")
res := NewSearchStockApi("").StrategySquare()
logger.SugaredLogger.Infof("res:%+v", res)
}

View File

@@ -1203,7 +1203,7 @@ func GetZSInfo(name, stockCode string, crawlTimeOut int64) string {
price := strutil.RemoveWhiteSpace(document.Find("div#price").First().Text(), false)
hqTime := strutil.RemoveWhiteSpace(document.Find("div#hqTime").First().Text(), false)
if strutil.ContainsAny(price, []string{"-", "--", ""}) {
if strutil.ContainsAny(price, []string{"-", "--"}) {
return "暂无数据"
}

View File

@@ -199,14 +199,6 @@ func InitAnalyzeSentiment() {
seg.CalcToken()
}
// WordFreqWithWeight 词频统计结果,包含权重信息
type WordFreqWithWeight struct {
Word string
Frequency int
Weight float64
Score float64
}
// getWordWeight 获取词汇权重
func getWordWeight(word string) float64 {
// 从分词器获取词汇权重
@@ -220,9 +212,9 @@ func getWordWeight(word string) float64 {
}
// SortByWeightAndFrequency 按权重和频次排序词频结果
func SortByWeightAndFrequency(frequencies map[string]WordFreqWithWeight) []WordFreqWithWeight {
func SortByWeightAndFrequency(frequencies map[string]models.WordFreqWithWeight) []models.WordFreqWithWeight {
// 将map转换为slice以便排序
freqSlice := make([]WordFreqWithWeight, 0, len(frequencies))
freqSlice := make([]models.WordFreqWithWeight, 0, len(frequencies))
for _, freq := range frequencies {
freqSlice = append(freqSlice, freq)
}
@@ -237,7 +229,7 @@ func SortByWeightAndFrequency(frequencies map[string]WordFreqWithWeight) []WordF
}
// FilterAndSortWords 过滤标点符号并按权重频次排序
func FilterAndSortWords(frequencies map[string]WordFreqWithWeight) []WordFreqWithWeight {
func FilterAndSortWords(frequencies map[string]models.WordFreqWithWeight) []models.WordFreqWithWeight {
// 先过滤标点符号和分隔符
cleanFrequencies := FilterPunctuationAndSeparators(frequencies)
@@ -246,8 +238,8 @@ func FilterAndSortWords(frequencies map[string]WordFreqWithWeight) []WordFreqWit
return sortedFrequencies
}
func FilterPunctuationAndSeparators(frequencies map[string]WordFreqWithWeight) map[string]WordFreqWithWeight {
filteredWords := make(map[string]WordFreqWithWeight)
func FilterPunctuationAndSeparators(frequencies map[string]models.WordFreqWithWeight) map[string]models.WordFreqWithWeight {
filteredWords := make(map[string]models.WordFreqWithWeight)
for word, freqInfo := range frequencies {
// 过滤纯标点符号和分隔符
@@ -275,8 +267,8 @@ func isPunctuationOrSeparator(word string) bool {
}
// FilterWithRegex 使用正则表达式过滤标点和特殊字符
func FilterWithRegex(frequencies map[string]WordFreqWithWeight) map[string]WordFreqWithWeight {
filteredWords := make(map[string]WordFreqWithWeight)
func FilterWithRegex(frequencies map[string]models.WordFreqWithWeight) map[string]models.WordFreqWithWeight {
filteredWords := make(map[string]models.WordFreqWithWeight)
// 匹配标点符号、特殊字符的正则表达式
punctuationRegex := regexp.MustCompile(`^[[:punct:][:space:]]+$`)
@@ -291,9 +283,9 @@ func FilterWithRegex(frequencies map[string]WordFreqWithWeight) map[string]WordF
}
// countWordFrequencyWithWeight 统计词频并包含权重信息
func countWordFrequencyWithWeight(text string) map[string]WordFreqWithWeight {
func countWordFrequencyWithWeight(text string) map[string]models.WordFreqWithWeight {
words := splitWords(text)
freqMap := make(map[string]WordFreqWithWeight)
freqMap := make(map[string]models.WordFreqWithWeight)
// 统计词频
wordCount := make(map[string]int)
@@ -305,7 +297,7 @@ func countWordFrequencyWithWeight(text string) map[string]WordFreqWithWeight {
for word, frequency := range wordCount {
weight := getWordWeight(word)
if weight >= basefreq {
freqMap[word] = WordFreqWithWeight{
freqMap[word] = models.WordFreqWithWeight{
Word: word,
Frequency: frequency,
Weight: weight,
@@ -319,7 +311,7 @@ func countWordFrequencyWithWeight(text string) map[string]WordFreqWithWeight {
}
// AnalyzeSentimentWithFreqWeight 带权重词频统计的情感分析
func AnalyzeSentimentWithFreqWeight(text string) (SentimentResult, map[string]WordFreqWithWeight) {
func AnalyzeSentimentWithFreqWeight(text string) (models.SentimentResult, map[string]models.WordFreqWithWeight) {
// 原有情感分析逻辑
result := AnalyzeSentiment(text)
@@ -329,26 +321,14 @@ func AnalyzeSentimentWithFreqWeight(text string) (SentimentResult, map[string]Wo
return result, frequencies
}
// SentimentResult 情感分析结果类型
type SentimentResult struct {
Score float64 // 情感得分
Category SentimentType // 情感类别
PositiveCount int // 正面词数量
NegativeCount int // 负面词数量
Description string // 情感描述
}
// SentimentType 情感类型枚举
type SentimentType int
const (
Positive SentimentType = iota
Positive models.SentimentType = iota
Negative
Neutral
)
// AnalyzeSentiment 判断文本的情感
func AnalyzeSentiment(text string) SentimentResult {
func AnalyzeSentiment(text string) models.SentimentResult {
// 初始化得分
score := 0.0
positiveCount := 0
@@ -388,7 +368,7 @@ func AnalyzeSentiment(text string) SentimentResult {
}
// 确定情感类别
var category SentimentType
var category models.SentimentType
switch {
case score > 1.0:
category = Positive
@@ -398,7 +378,7 @@ func AnalyzeSentiment(text string) SentimentResult {
category = Neutral
}
return SentimentResult{
return models.SentimentResult{
Score: score,
Category: category,
PositiveCount: positiveCount,
@@ -511,7 +491,7 @@ func splitWords(text string) []string {
}
// GetSentimentDescription 获取情感类别的文本描述
func GetSentimentDescription(category SentimentType) string {
func GetSentimentDescription(category models.SentimentType) string {
switch category {
case Positive:
return "看涨"
@@ -556,3 +536,43 @@ func main() {
result.NegativeCount)
}
}
func SaveAnalyzeSentimentWithFreqWeight(frequencies []models.WordFreqWithWeight) {
sort.Slice(frequencies, func(i, j int) bool {
return frequencies[i].Frequency > frequencies[j].Frequency
})
wordAnalyzes := make([]models.WordAnalyze, 0)
for _, freq := range frequencies[:10] {
wordAnalyze := models.WordAnalyze{
WordFreqWithWeight: freq,
}
wordAnalyzes = append(wordAnalyzes, wordAnalyze)
}
db.Dao.CreateInBatches(wordAnalyzes, 1000)
}
func SaveStockSentimentAnalysis(result models.SentimentResult) {
db.Dao.Create(&models.SentimentResultAnalyze{
SentimentResult: result,
})
}
func NewsAnalyze(text string, save bool) (models.SentimentResult, []models.WordFreqWithWeight) {
if text == "" {
telegraphs := NewMarketNewsApi().GetNews24HoursList("", 1000*10)
messageText := strings.Builder{}
for _, telegraph := range *telegraphs {
messageText.WriteString(telegraph.Content + "\n")
}
text = messageText.String()
}
result, frequencies := AnalyzeSentimentWithFreqWeight(text)
// 过滤标点符号和分隔符
cleanFrequencies := FilterAndSortWords(frequencies)
if save {
go SaveAnalyzeSentimentWithFreqWeight(cleanFrequencies)
go SaveStockSentimentAnalysis(result)
}
return result, cleanFrequencies
}

View File

@@ -359,29 +359,29 @@ type XUEQIUHot struct {
}
type HotItem struct {
Type int `json:"type"`
Code string `json:"code"`
Name string `json:"name"`
Value float64 `json:"value"`
Increment int `json:"increment"`
RankChange int `json:"rank_change"`
HasExist interface{} `json:"has_exist"`
Symbol string `json:"symbol"`
Percent float64 `json:"percent"`
Current float64 `json:"current"`
Chg float64 `json:"chg"`
Exchange string `json:"exchange"`
StockType int `json:"stock_type"`
SubType string `json:"sub_type"`
Ad int `json:"ad"`
AdId interface{} `json:"ad_id"`
ContentId interface{} `json:"content_id"`
Page interface{} `json:"page"`
Model interface{} `json:"model"`
Location interface{} `json:"location"`
TradeSession interface{} `json:"trade_session"`
CurrentExt interface{} `json:"current_ext"`
PercentExt interface{} `json:"percent_ext"`
Type int `json:"type" md:"-"`
Code string `json:"code" md:"股票代码"`
Name string `json:"name" md:"股票名称"`
Value float64 `json:"value" md:"热度"`
Increment int `json:"increment" md:"热度变化"`
RankChange int `json:"rank_change" md:"排名变化"`
HasExist interface{} `json:"has_exist" md:"-"`
Symbol string `json:"symbol" md:"-"`
Percent float64 `json:"percent" md:"涨跌幅(%)"`
Current float64 `json:"current" md:"股价"`
Chg float64 `json:"chg" md:"股价变化"`
Exchange string `json:"exchange" md:"交易所代码"`
StockType int `json:"stock_type" md:"-"`
SubType string `json:"sub_type" md:"-"`
Ad int `json:"ad" md:"-"`
AdId interface{} `json:"ad_id" md:"-"`
ContentId interface{} `json:"content_id" md:"-"`
Page interface{} `json:"page" md:"-"`
Model interface{} `json:"model" md:"-"`
Location interface{} `json:"location" md:"-"`
TradeSession interface{} `json:"trade_session" md:"-"`
CurrentExt interface{} `json:"current_ext" md:"-"`
PercentExt interface{} `json:"percent_ext" md:"-"`
}
type HotEvent struct {
@@ -719,3 +719,96 @@ type BKDict struct {
func (b BKDict) TableName() string {
return "bk_dict"
}
type WordAnalyze struct {
gorm.Model
DataTime *time.Time `json:"dataTime" gorm:"index;autoCreateTime"`
WordFreqWithWeight
}
// WordFreqWithWeight 词频统计结果,包含权重信息
type WordFreqWithWeight struct {
Word string
Frequency int
Weight float64
Score float64
}
// SentimentResult 情感分析结果类型
type SentimentResult struct {
Score float64 // 情感得分
Category SentimentType // 情感类别
PositiveCount int // 正面词数量
NegativeCount int // 负面词数量
Description string // 情感描述
}
type SentimentResultAnalyze struct {
gorm.Model
DataTime *time.Time `json:"dataTime" gorm:"index;autoCreateTime"`
SentimentResult
}
// SentimentType 情感类型枚举
type SentimentType int
type HotStrategy struct {
ChgEffect bool `json:"chgEffect"`
Code int `json:"code"`
Data []*HotStrategyData `json:"data"`
Message string `json:"message"`
}
type HotStrategyData struct {
Chg float64 `json:"chg" md:"平均涨幅(%)"`
Code string `json:"code" md:"-"`
HeatValue int `json:"heatValue" md:"热度值"`
Market string `json:"market" md:"-"`
Question string `json:"question" md:"选股策略"`
Rank int `json:"rank" md:"-"`
}
type NtfyNews struct {
Id string `json:"id"`
Time int `json:"time"`
Expires int `json:"expires"`
Event string `json:"event"`
Topic string `json:"topic"`
Title string `json:"title"`
Message string `json:"message"`
Tags []string `json:"tags"`
Icon string `json:"icon"`
}
type THSHotStrategy struct {
Result struct {
Num int `json:"num"`
List []struct {
Author struct {
Avatar string `json:"avatar"`
UserName string `json:"userName"`
UserId int `json:"userId"`
} `json:"author"`
Property struct {
Id int `json:"id"`
Name string `json:"name"`
Query string `json:"query"`
Logic string `json:"logic"`
BuyPosition interface{} `json:"buyPosition"`
Ctime string `json:"ctime"`
Tags []string `json:"tags"`
WinRate string `json:"winRate"`
AnnualYield string `json:"annualYield"`
Type int `json:"type"`
} `json:"property"`
Interaction struct {
CommentNum int `json:"commentNum"`
CollectNum int `json:"collectNum"`
IsCollected bool `json:"isCollected"`
IsSubscribe int `json:"isSubscribe"`
IsPublish int `json:"isPublish"`
Pid int `json:"pid"`
} `json:"interaction"`
} `json:"list"`
} `json:"result"`
}

BIN
build/screenshot/img15.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 205 KiB

193
data/dict/user.txt Normal file
View File

@@ -0,0 +1,193 @@
# 补充热点概念与板块Jieba/gse兼容格式
# 权重说明核心热点500-700分事件类400分负权重词汇按需求保留
# 一、负权重低优先级词汇(减少无差别匹配干扰)
公司 -0.1 n
国家 -0.1 n
国际 -0.1 n
会议 -0.1 n
市场 -0.1 n
经济 -0.1 n
技术 -0.1 n
记者 -0.1 n
时间 -0.1 n
项目 -0.1 n
问题 -0.1 n
企业 -0.1 n
财联社 -0.1 n
上涨 -0.1 v
下跌 -0.1 v
期货 -0.1 n
跌幅 -0.1 n
跌超 -0.1 adj
股票 -0.1 n
基金 -0.1 n
电讯 -0.1 n
建筑 -0.1 n
平开 -0.1 n
保险 -0.1 n
行业 -0.1 n
其他 -0.1 n
a股 -0.1 n
港股 -0.1 n
etf -0.1 n
涨幅 -0.1 n
交易所 -0.1 n
证券 -0.1 n
ai -0.1 n
# 二、核心热点概念700分最高优先级
端侧AI 700 n
AI应用 700 n
比特币 700 n
摩尔线程 700 n
摩尔线程概念 700 n
AI算力 700 n
生成式AI 700 n
量子计算 700 n
脑机接口 700 n
6G通信 700 n
人形机器人 700 n
固态电池 700 n
ChatGPT概念 700 n
Web3.0 700 n
元宇宙 700 n
数字孪生 700 n
量子通信 700 n
# 三、重点赛道板块500分高优先级
冰雪旅游 500 n
特高压 500 n
跨境电商 500 n
新能源汽车 500 n
机器人 500 n
具身智能 500 n
油气 500 n
商业航天 500 n
光伏储能 500 n
锂电材料 500 n
半导体设备 500 n
集成电路 500 n
创新药 500 n
CXO 500 n
医疗器械 500 n
数字经济 500 n
数字货币 500 n
区块链 500 n
低空经济 500 n
工业互联网 500 n
物联网 500 n
5G应用 500 n
充电桩 500 n
氢能源 500 n
核聚变 500 n
工业母机 500 n
新材料 500 n
生物制造 500 n
智能网联汽车 500 n
乡村振兴 500 n
国企改革 500 n
央企重组 500 n
跨境金融 500 n
自贸港 500 n
一带一路 500 n
绿色低碳 500 n
碳交易 500 n
数据要素 500 n
数字基建 500 n
东数西算 500 n
国产替代 500 n
信创 500 n
网络安全 500 n
算力网络 500 n
边缘计算 500 n
虚拟现实 500 n
增强现实 500 n
智能穿戴 500 n
智能家居 500 n
车联网 500 n
激光雷达 500 n
氮化镓 500 n
碳化硅 500 n
第三代半导体 500 n
EDA工具 500 n
光刻胶 500 n
芯片设计 500 n
封装测试 500 n
储能电池 500 n
钠离子电池 500 n
氢燃料电池 500 n
光伏组件 500 n
风电设备 500 n
特高压设备 500 n
电力物联网 500 n
智能电网 500 n
轨道交通 500 n
航空航天 500 n
海洋工程 500 n
高端装备 500 n
军工电子 500 n
卫星互联网 500 n
北斗导航 500 n
国产大飞机 500 n
生物医药 500 n
基因测序 500 n
疫苗 500 n
医疗美容 500 n
养老产业 500 n
教育信息化 500 n
体育产业 500 n
文化创意 500 n
旅游复苏 500 n
预制菜 500 n
白酒 500 n
食品饮料 500 n
家电下乡 500 n
房地产复苏 500 n
基建投资 500 n
新型城镇化 500 n
冷链物流 500 n
快递物流 500 n
跨境支付 500 n
金融科技 500 n
消费电子 500 n
元宇宙基建 500 n
数字藏品 500 n
NFT 500 n
绿色电力 500 n
节能降碳 500 n
抽水蓄能 500 n
生物质能 500 n
地热能 500 n
潮汐能 500 n
# 四、事件驱动型概念400分中优先级
俄乌冲突 400 n
中东局势 400 n
美联储加息 400 n
降息预期 400 n
贸易摩擦 400 n
供应链重构 400 n
能源危机 400 n
粮食安全 400 n
疫情复苏 400 n
政策利好 400 n
产业扶持 400 n
技术突破 400 n
并购重组 400 n
IPO提速 400 n
解禁潮 400 n
北向资金流入 400 n
南向资金流入 400 n
主力资金异动 400 n
行业景气度 400 n
业绩预增 400 n
商誉减值 400 n
退市风险 400 n
监管新规 400 n
税收优惠 400 n
补贴政策 400 n
基建刺激 400 n
消费刺激 400 n
新能源补贴 400 n
碳达峰政策 400 n
碳中和目标 400 n

View File

@@ -75,7 +75,6 @@ function getIndex() {
function handleChart(){
const formatUtil = echarts.format;
AnalyzeSentimentWithFreqWeight("").then((res) => {
//console.log(res)
const treemapchart = echarts.init(chartRef.value);
const gaugeChart=echarts.init(gaugeChartRef.value);
let data = res['frequencies'].map(item => ({

View File

@@ -166,7 +166,7 @@ EventsOn("updateVersion",async (msg) => {
<n-td>赞助 18.8 RMB/<br>赞助 120 RMB/</n-td><n-td>vip1</n-td><n-td>💕 全部功能,软件自动更新(从CDN下载),更新快速便捷AI配置指导提示词参考等</n-td>
</n-tr>
<n-tr>
<n-td>赞助 28.8 RMB/<br>赞助 240 RMB/</n-td><n-td>vip2</n-td><n-td>💕 vip1全部功能,赠送硅基流动AI分析服务💕</n-td>
<n-td>赞助 28.8 RMB/<br>赞助 240 RMB/</n-td><n-td>vip2</n-td><n-td>💕 vip1全部功能,赠送硅基流动AI分析服务启动时自动同步最近24小时市场资讯(包括外媒简讯) 💕</n-td>
</n-tr>
<n-tr>
<n-td>每月赞助 X RMB</n-td><n-td>vipX</n-td><n-td>🧩 更多计划视go-stock开源项目发展情况而定...(承接GitHub项目README广告推广💖)</n-td>

View File

@@ -78,6 +78,7 @@ const indexInterval = ref(null)
const indexIndustryRank = ref(null)
const stockCode= ref('')
const enableTools= ref(true)
const thinkingMode = ref(true)
const treemapRef = ref(null);
let treemapchart =null;
@@ -127,6 +128,9 @@ onBeforeMount(() => {
indexIndustryRank.value = setInterval(() => {
industryRank()
ReFlesh("财联社电报")
ReFlesh("新浪财经")
ReFlesh("外媒")
}, 1000 * 10)
@@ -223,7 +227,7 @@ function reAiSummary() {
aiSummary.value = ""
summaryModal.value = true
loading.value = true
SummaryStockNews(question.value,aiConfigId.value, sysPromptId.value,enableTools.value)
SummaryStockNews(question.value,aiConfigId.value, sysPromptId.value,enableTools.value,thinkingMode.value)
}
function getAiSummary() {
@@ -353,14 +357,14 @@ function ReFlesh(source) {
<AnalyzeMartket :dark-theme="darkTheme" :chart-height="300" :kDays="1" :name="'最近24小时热词'" />
</n-gi>
<n-gi>
<n-grid :cols="httpProxyEnabled?3:2" :y-gap="0">
<n-grid :cols="foreignNewsList.length?3:2" :y-gap="0">
<n-gi>
<news-list :newsList="telegraphList" :header-title="'财联社电报'" @update:message="ReFlesh"></news-list>
</n-gi>
<n-gi>
<news-list :newsList="sinaNewsList" :header-title="'新浪财经'" @update:message="ReFlesh"></news-list>
</n-gi>
<n-gi v-if="httpProxyEnabled">
<n-gi v-if="foreignNewsList.length>0">
<news-list :newsList="foreignNewsList" :header-title="'外媒'" @update:message="ReFlesh"></news-list>
</n-gi>
@@ -704,6 +708,16 @@ function ReFlesh(source) {
不启用AI函数工具调用
</template>
</n-switch>
<n-switch v-model:value="thinkingMode" :round="false">
<template #checked>
启用思考模式
</template>
<template #unchecked>
不启用思考模式
</template>
</n-switch>
<n-gradient-text type="error" style="margin-left: 10px">*AI函数工具调用可以增强AI获取数据的能力,但会消耗更多tokens</n-gradient-text>
</n-flex>
<n-flex justify="space-between" style="margin-bottom: 10px">

View File

@@ -1,6 +1,7 @@
<script setup>
import {ReFleshTelegraphList} from "../../wailsjs/go/main/App";
import {RefreshCircle, RefreshCircleSharp, RefreshOutline} from "@vicons/ionicons5";
import {computed, h, onBeforeMount, onBeforeUnmount, onMounted,onUnmounted, ref} from 'vue'
const { headerTitle,newsList } = defineProps({
headerTitle: {
@@ -18,6 +19,30 @@ const emits = defineEmits(['update:message'])
const updateMessage = () => {
emits('update:message', headerTitle)
}
// 使用 ref 创建响应式时间数据
const time = ref(new Date())
// 更新时间的函数
const updateTime = () => {
time.value = new Date()
}
let timer = null
// 组件挂载时启动定时器
onMounted(() => {
if (headerTitle === '财联社电报') {
// 每秒更新一次时间
timer = setInterval(updateTime, 1000)
}
})
// 组件卸载时清除定时器
onUnmounted(() => {
if (timer) {
clearInterval(timer)
}
})
</script>
<template>
@@ -25,23 +50,32 @@ const updateMessage = () => {
<template #header>
<n-flex justify="space-between">
<n-tag :bordered="false" size="large" type="success" >{{ headerTitle }}</n-tag>
<n-tag :bordered="false" size="large" type="info" v-if="headerTitle==='财联社电报'"> <n-time :time="time"/></n-tag>
<n-button :bordered="false" @click="updateMessage"><n-icon color="#409EFF" size="25" :component="RefreshCircleSharp"/></n-button>
</n-flex>
</template>
<n-list-item v-for="item in newsList">
<n-list-item v-for="(item,idx) in newsList" :key="item.ID">
<n-space justify="center" v-if="idx!==0 && item.dataTime.substring(0,10) !== newsList[idx-1].dataTime.substring(0,10)">
<n-divider>
{{ item.dataTime.substring(0,10) }}
</n-divider>
</n-space>
<n-space justify="start" >
<n-text justify="start" :bordered="false" :type="item.isRed?'error':'info'">
<n-collapse v-if="item.title" arrow-placement="right" >
<n-collapse-item :name="item.title">
<template #header>
<n-tag size="small" :type="item.isRed?'error':'warning'" :bordered="false"> {{ item.time }}</n-tag>
<n-text size="small" :type="item.isRed?'error':'info'" :bordered="false">{{ item.title }}</n-text>
</template>
<n-text justify="start" :bordered="false" :type="item.isRed?'error':'info'">
{{ item.content }}
</n-text>
</n-collapse-item>
</n-collapse>
<n-text v-if="!item.title" justify="start" :bordered="false" :type="item.isRed?'error':'info'">
<n-tag size="small" :type="item.isRed?'error':'warning'" :bordered="false"> {{ item.time }}</n-tag>
<n-gradient-text :size="14" :type="'warning'" :bordered="false">{{ item.title }}</n-gradient-text> <n-text :type="item.isRed?'error':'info'">{{ item.content }}</n-text>
{{ item.content }}
</n-text>
<!-- <n-collapse v-if="item.title">-->
<!-- <n-collapse-item :title="item.title" :name="item.title">-->
<!-- <n-text justify="start" :bordered="false" :type="item.isRed?'error':'info'">-->
<!-- <n-tag size="small" :type="item.isRed?'error':'warning'" :bordered="false"> {{ item.time }}</n-tag>-->
<!-- {{ item.content }}-->
<!-- </n-text>-->
<!-- </n-collapse-item>-->
<!-- </n-collapse>-->
</n-space>
<n-space v-if="item.subjects" style="margin-top: 2px">
<n-tag :bordered="false" type="success" size="small" v-for="sub in item.subjects">

View File

@@ -110,6 +110,7 @@ const modalShow4 = ref(false)
const modalShow5 = ref(false)
const addBTN = ref(true)
const enableTools = ref(false)
const thinkingMode = ref(false)
const formModel = ref({
name: "",
code: "",
@@ -1580,7 +1581,7 @@ function aiReCheckStock(stock, stockCode) {
//
//message.info("sysPromptId:"+data.sysPromptId)
NewChatStream(stock, stockCode, data.question, data.aiConfigId, data.sysPromptId, enableTools.value)
NewChatStream(stock, stockCode, data.question, data.aiConfigId, data.sysPromptId, enableTools.value,thinkingMode.value)
}
function aiCheckStock(stock, stockCode) {
@@ -2353,6 +2354,14 @@ function searchStockReport(stockCode) {
不启用AI函数工具调用
</template>
</n-switch>
<n-switch v-model:value="thinkingMode" :round="false">
<template #checked>
启用思考模式
</template>
<template #unchecked>
不启用思考模式
</template>
</n-switch>
<n-gradient-text type="error" style="margin-left: 10px">
*AI函数工具调用可以增强AI获取数据的能力,但会消耗更多tokens
</n-gradient-text>

View File

@@ -12,7 +12,7 @@ export function AddPrompt(arg1:models.Prompt):Promise<string>;
export function AddStockGroup(arg1:number,arg2:string):Promise<string>;
export function AnalyzeSentiment(arg1:string):Promise<data.SentimentResult>;
export function AnalyzeSentiment(arg1:string):Promise<models.SentimentResult>;
export function AnalyzeSentimentWithFreqWeight(arg1:string):Promise<Record<string, any>>;
@@ -96,7 +96,7 @@ export function InvestCalendarTimeLine(arg1:string):Promise<Array<any>>;
export function LongTigerRank(arg1:string):Promise<any>;
export function NewChatStream(arg1:string,arg2:string,arg3:string,arg4:number,arg5:any,arg6:boolean):Promise<void>;
export function NewChatStream(arg1:string,arg2:string,arg3:string,arg4:number,arg5:any,arg6:boolean,arg7:boolean):Promise<void>;
export function NewsPush(arg1:any):Promise<void>;
@@ -136,7 +136,7 @@ export function StockNotice(arg1:string):Promise<Array<any>>;
export function StockResearchReport(arg1:string):Promise<Array<any>>;
export function SummaryStockNews(arg1:string,arg2:number,arg3:any,arg4:boolean):Promise<void>;
export function SummaryStockNews(arg1:string,arg2:number,arg3:any,arg4:boolean,arg5:boolean):Promise<void>;
export function UnFollow(arg1:string):Promise<string>;

View File

@@ -186,8 +186,8 @@ export function LongTigerRank(arg1) {
return window['go']['main']['App']['LongTigerRank'](arg1);
}
export function NewChatStream(arg1, arg2, arg3, arg4, arg5, arg6) {
return window['go']['main']['App']['NewChatStream'](arg1, arg2, arg3, arg4, arg5, arg6);
export function NewChatStream(arg1, arg2, arg3, arg4, arg5, arg6, arg7) {
return window['go']['main']['App']['NewChatStream'](arg1, arg2, arg3, arg4, arg5, arg6, arg7);
}
export function NewsPush(arg1) {
@@ -266,8 +266,8 @@ export function StockResearchReport(arg1) {
return window['go']['main']['App']['StockResearchReport'](arg1);
}
export function SummaryStockNews(arg1, arg2, arg3, arg4) {
return window['go']['main']['App']['SummaryStockNews'](arg1, arg2, arg3, arg4);
export function SummaryStockNews(arg1, arg2, arg3, arg4, arg5) {
return window['go']['main']['App']['SummaryStockNews'](arg1, arg2, arg3, arg4, arg5);
}
export function UnFollow(arg1) {

View File

@@ -342,26 +342,6 @@ export namespace data {
export class SentimentResult {
Score: number;
Category: number;
PositiveCount: number;
NegativeCount: number;
Description: string;
static createFrom(source: any = {}) {
return new SentimentResult(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.Score = source["Score"];
this.Category = source["Category"];
this.PositiveCount = source["PositiveCount"];
this.NegativeCount = source["NegativeCount"];
this.Description = source["Description"];
}
}
export class SettingConfig {
ID: number;
// Go type: time
@@ -745,6 +725,26 @@ export namespace models {
this.type = source["type"];
}
}
export class SentimentResult {
Score: number;
Category: number;
PositiveCount: number;
NegativeCount: number;
Description: string;
static createFrom(source: any = {}) {
return new SentimentResult(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.Score = source["Score"];
this.Category = source["Category"];
this.PositiveCount = source["PositiveCount"];
this.NegativeCount = source["NegativeCount"];
this.Description = source["Description"];
}
}
export class VersionInfo {
ID: number;
// Go type: time

4
go.mod
View File

@@ -5,7 +5,7 @@ go 1.25.0
require (
github.com/PuerkitoBio/goquery v1.11.0
github.com/chromedp/chromedp v0.14.2
github.com/cloudwego/eino v0.7.3
github.com/cloudwego/eino v0.7.9
github.com/cloudwego/eino-ext/components/model/ark v0.1.52
github.com/cloudwego/eino-ext/components/model/deepseek v0.1.0
github.com/cloudwego/eino-ext/components/model/openai v0.1.5
@@ -25,6 +25,7 @@ require (
github.com/tidwall/gjson v1.18.0
github.com/wailsapp/wails/v2 v2.11.0
go.uber.org/zap v1.27.1
golang.org/x/exp v0.0.0-20251125195548-87e1e737ad39
golang.org/x/net v0.47.0
golang.org/x/sys v0.38.0
golang.org/x/text v0.31.0
@@ -120,7 +121,6 @@ require (
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/arch v0.23.0 // indirect
golang.org/x/crypto v0.45.0 // indirect
golang.org/x/exp v0.0.0-20251125195548-87e1e737ad39 // indirect
google.golang.org/protobuf v1.36.10 // indirect
gopkg.in/sourcemap.v1 v1.0.5 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect

4
go.sum
View File

@@ -118,8 +118,8 @@ github.com/clbanning/mxj v1.8.4/go.mod h1:BVjHeAH+rl9rs6f+QIpeRl0tfu10SXn1pUSa5P
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/cloudwego/eino v0.7.3 h1:+byYvxX3d9C12XfSyXBH2blZlReTuqcPPbPqsdNiYGU=
github.com/cloudwego/eino v0.7.3/go.mod h1:nA8Vacmuqv3pqKBQbTWENBLQ8MmGmPt/WqiyLeB8ohQ=
github.com/cloudwego/eino v0.7.9 h1:wrkVFKa/gqe5b7EUl/hyKVXxwcAltI0OdOzABmDS5IE=
github.com/cloudwego/eino v0.7.9/go.mod h1:nA8Vacmuqv3pqKBQbTWENBLQ8MmGmPt/WqiyLeB8ohQ=
github.com/cloudwego/eino-ext/components/model/ark v0.1.52 h1:/qqHpgvS5hoC7Z2U0JOFJL75q/odMlR26VEsoV1bjo0=
github.com/cloudwego/eino-ext/components/model/ark v0.1.52/go.mod h1:dC4wNeUdnjo4s/1r+YG7fMQcnfQ3bOFWw8Penh86vOI=
github.com/cloudwego/eino-ext/components/model/deepseek v0.1.0 h1:LutIVpQaqXaXNhn3RkSB0dWyBldQ0oxq2pecyW4jqyU=

View File

@@ -241,6 +241,8 @@ func AutoMigrate() {
db.Dao.AutoMigrate(&models.LongTigerRankData{})
db.Dao.AutoMigrate(&data.AIConfig{})
db.Dao.AutoMigrate(&models.BKDict{})
db.Dao.AutoMigrate(&models.WordAnalyze{})
db.Dao.AutoMigrate(&models.SentimentResultAnalyze{})
updateMultipleModel()
}