Compare commits

...

13 Commits

Author SHA1 Message Date
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
ArvinLovegood
a354ab8925 feat(news):添加新闻标题字段并更新测试代码
- 在 Telegraph 模型中新增 Title 字段以存储新闻标题
- 更新 market_news_api.go 文件以支持标题数据的提取和赋值
2025-12-11 16:47:35 +08:00
ArvinLovegood
6d50be8541 fix(main):添加全局panic捕获
- 增加defer函数捕获程序异常
- 记录panic堆栈信息便于调试
- 注释掉包含构建密钥的日志输出

chore(test): 新增字符串处理工具包引入

- 引入lancet/v2/strutil包用于测试
- 添加调试日志展示字符串截取功能
- 完善市场资讯API测试用例
2025-12-10 17:52:18 +08:00
ArvinLovegood
6303d535bc refactor(app):移除测试代码中的授权令牌并调整更新检查逻辑
移除app_test.go中硬编码的GitHub授权令牌,避免安全风险。在app.go的CheckUpdate方法中,将授权令牌从请求头中移除,改为无认证方式获取版本信息,同时优化VIP用户下载链接逻辑。
2025-12-10 16:26:09 +08:00
ArvinLovegood
b464d8f563 chore(config):更新访问令牌
- 替换 app.go 中的旧访问令牌为新令牌
- 注释掉 app_test.go 中的访问令牌以避免测试时使用
- 确保所有 GitHub API 请求使用最新的认证凭证
2025-12-10 16:24:03 +08:00
ArvinLovegood
eea0856c1c feat(stock):更新股票研究与市场新闻功能
- 修改股票研究工具描述,明确获取分析师研究报告
- 调整 TradingView 新闻接口参数,优化请求过滤条件
- 新增代理测试与通知推送测试方法
- 扩大股票搜索范围,提升数据获取数量
- 更新东方财富接口 User-Agent,增强请求稳定性
- 优化美股与港股数据抓取逻辑及休眠时间
- 增加前端消息墙展示标签页,集成外部链接页面
- 调整数据库操作注释,便于后续调试与维护
2025-12-10 15:55:06 +08:00
ArvinLovegood
1dd77d5c08 feat(stock):增强股票情感分析功能并优化GitHub请求
- 为GitHub API请求添加授权头部信息
- 禁用OpenAI接口中的思考模式
- 重构情感分析初始化逻辑,增加异常恢复机制
- 优化词典加载流程,提升系统稳定性
- 调整词语权重计算方式,提高准确性
- 更新测试用例,增强覆盖场景
- 移除无用的错误包引用,清理依赖项
- 修复URL格式化问题,确保请求正确性
2025-12-02 18:45:15 +08:00
ArvinLovegood
9c1c0382ca chore(deps):更新多个依赖库版本
-更新多个依赖库版本
2025-12-02 16:06:54 +08:00
ArvinLovegood
46065f448b feat(openai):启用模型思考模式并设置工具选择
- 在请求体中添加 thinking 字段以启用模型思考模式
- 设置 tool_choice 为 required 以强制使用工具调用
- 保持现有模型配置和其他参数不变
2025-12-02 14:23:52 +08:00
ArvinLovegood
a7cee69e68 chore(deps):更新模块依赖版本
- 更新 github.com/PuerkitoBio/goquery 从 v1.10.1 到 v1.11.0
- 更新 github.com/chromedp/chromedp 从 v0.14.1 到 v0.14.2
- 更新 github.com/cloudwego/eino 从 v0.4.1 到 v0.7.3
- 更新 github.com/cloudwego/eino-ext/components/model/ark 从 v0.1.19 到 v0.1.51
- 更新 github.com/cloudwego/eino-ext/components/model/deepseek 到最新提交
- 更新 github.com/cloudwego/eino-ext/components/model/openai 从 v0.0.0 到 v0.1.5
- 更新 github.com/duke-git/lancet/v2 从 v2.3.4 到 v2.3.8
- 更新 github.com/go-resty/resty/v2 从 v2.16.2 到 v2.17.0
- 更新 github.com/samber/lo 从 v1.49.1 到 v1.52.0
- 更新 github.com/stretchr/testify 从 v1.10.0 到 v1.11.1
- 更新 github.com/tidwall/gjson 从 v1.14.4 到 v1.18.0
- 更新 github.com/wailsapp/wails/v2 从 v2.10.1 到 v2.11.0
- 更新 go.uber.org/zap 从 v1.27.0 到 v1.27.1
- 更新 gorm.io/gorm 从 v1.25.12 到 v1.31.1
- 更新 gorm.io/plugin/dbresolver 从 v1.5.3 到 v1.6.2
- 移除 github.com/getkin/kin-openapi 间接依赖
- 移除 github.com/meguminnnnnnnnn/go-openai 旧版本,更新为 v0.1.0
- 移除 github.com/openai/openai-go 间接依赖
- 添加 github.com/bahlo/generic-list-go 作为间接依赖
- 添加 github.com/eino-contrib/jsonschema 作为间接依赖
- 添加 github.com/gorilla/websocket 作为间接依赖
- 添加 github.com/wk8/go-ordered-map/v2 作为间接依赖
- 添加 google.golang.org/protobuf 和 gopkg.in/check.v1 作为间接依赖
2025-11-30 19:43:30 +08:00
26 changed files with 1395 additions and 389 deletions

38
app.go
View File

@@ -62,7 +62,7 @@ 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{
@@ -88,7 +88,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 +110,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{
@@ -161,8 +161,8 @@ func AddTools(tools []data.Tool) []data.Tool {
Type: "function",
Function: data.ToolFunction{
Name: "GetStockResearchReport",
Description: "获取股票的分析/研究报告",
Parameters: data.FunctionParameters{
Description: "获取市场分析师的股票研究报告",
Parameters: &data.FunctionParameters{
Type: "object",
Properties: map[string]any{
"stockCode": map[string]any{
@@ -175,6 +175,14 @@ func AddTools(tools []data.Tool) []data.Tool {
},
})
tools = append(tools, data.Tool{
Type: "function",
Function: data.ToolFunction{
Name: "HotStrategyTable",
Description: "获取当前热门选股策略",
},
})
return tools
}
@@ -418,6 +426,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 +698,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 := ""
@@ -717,7 +729,7 @@ func refreshTelegraphList() *[]string {
response, err := resty.New().R().
SetHeader("Referer", "https://www.cls.cn/").
SetHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.60").
Get(fmt.Sprintf(url))
Get(url)
if err != nil {
return &[]string{}
}
@@ -1051,12 +1063,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 +1398,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

@@ -8,6 +8,8 @@ import (
"go-stock/backend/models"
"testing"
"time"
"github.com/go-resty/resty/v2"
)
// @Author spark
@@ -45,3 +47,18 @@ func TestJson(t *testing.T) {
db.Dao.Model(v).Updates(v)
}
func TestUpdateCheck(t *testing.T) {
releaseVersion := &models.GitHubReleaseVersion{}
_, err := resty.New().R().
SetResult(releaseVersion).
SetHeader("Accept", "application/vnd.github+json").
SetHeader("X-GitHub-Api-Version", "2022-11-28").
Get("https://api.github.com/repos/ArvinLovegood/go-stock/releases/latest")
// https://api.github.com/repos/OWNER/REPO/releases/latest
if err != nil {
logger.SugaredLogger.Errorf("get github release version error:%s", err.Error())
return
}
logger.SugaredLogger.Infof("releaseVersion:%+v", releaseVersion)
}

View File

@@ -55,8 +55,8 @@ 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),
Time: dataTime.Format("15:04:05"),
DataTime: &dataTime,
@@ -66,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
}
@@ -265,6 +269,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 {
@@ -288,7 +293,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)
@@ -651,7 +660,9 @@ func (m MarketNewsApi) TradingViewNews() *[]models.Telegraph {
TVNews := &[]models.TVNews{}
news := &[]models.Telegraph{}
// url := "https://news-mediator.tradingview.com/news-flow/v2/news?filter=lang:zh-Hans&filter=area:WLD&client=screener&streaming=false"
url := "https://news-mediator.tradingview.com/news-flow/v2/news?filter=area%3AWLD&filter=lang%3Azh-Hans&client=screener&streaming=false"
//url := "https://news-mediator.tradingview.com/news-flow/v2/news?filter=area%3AWLD&filter=lang%3Azh-Hans&client=screener&streaming=false"
url := "https://news-mediator.tradingview.com/news-flow/v2/news?filter=lang%3Azh-Hans&client=screener&streaming=false"
resp, err := client.SetTimeout(time.Duration(15)*time.Second).R().
SetHeader("Host", "news-mediator.tradingview.com").
SetHeader("Origin", "https://cn.tradingview.com").
@@ -699,7 +710,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

@@ -6,11 +6,14 @@ import (
"go-stock/backend/logger"
"go-stock/backend/models"
"go-stock/backend/util"
"path/filepath"
"strings"
"testing"
"github.com/coocood/freecache"
"github.com/duke-git/lancet/v2/random"
"github.com/duke-git/lancet/v2/strutil"
"github.com/go-resty/resty/v2"
"github.com/tidwall/gjson"
)
@@ -89,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))
}
}
@@ -253,3 +257,38 @@ func TestTelegraphList(t *testing.T) {
InitAnalyzeSentiment()
NewMarketNewsApi().TelegraphList(30)
}
func TestProxy(t *testing.T) {
response, err := resty.New().
SetProxy("http://go-stock:778d4ff2-73f3-4d56-b3c3-d9a730a06ae3@stock.sparkmemory.top:8888").
R().
SetHeader("Host", "news-mediator.tradingview.com").
SetHeader("Origin", "https://cn.tradingview.com").
SetHeader("Referer", "https://cn.tradingview.com/").
SetHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:140.0) Gecko/20100101 Firefox/140.0").
//Get("https://api.ipify.org")
Get("https://news-mediator.tradingview.com/news-flow/v2/news?filter=lang%3Azh-Hans&client=screener&streaming=false&user_prostatus=non_pro")
if err != nil {
logger.SugaredLogger.Error(err)
return
}
logger.SugaredLogger.Debugf("value: %s", response.String())
}
func TestNtfy(t *testing.T) {
//attach := "http://go-stock.sparkmemory.top/%E5%88%86%E6%9E%90%E6%8A%A5%E5%91%8A/%E8%B5%84%E9%87%91%E6%B5%81%E5%90%91/2025-12/AI%EF%BC%9A%E5%B8%82%E5%9C%BA%E5%88%86%E6%9E%90%E6%8A%A5%E5%91%8A-[2025.12.11_12.02.01].html"
//post, err := resty.New().SetBaseURL("https://go-stock.sparkmemory.top:16667").R().
// SetHeader("Filename", "AI市场分析报告-[2025.12.11_12.02.01].html").
// SetHeader("Icon", "https://go-stock.sparkmemory.top/appicon.png").
// SetHeader("Attach", attach).
// SetBody("AI市场分析报告-[2025.12.11_12.02.01]").Post("/go-stock")
//if err != nil {
// logger.SugaredLogger.Error(err)
// return
//}
//logger.SugaredLogger.Debugf("value: %s", post.String())
logger.SugaredLogger.Debugf("value: %s", filepath.Base("https://go-stock.sparkmemory.top/%E5%88%86%E6%9E%90%E6%8A%A5%E5%91%8A/2025/12/11/%E5%B8%82%E5%9C%BA%E8%B5%84%E8%AE%AF[%E5%B8%82%E5%9C%BA%E8%B5%84%E8%AE%AF]-(2025-12-11)AI%E5%88%86%E6%9E%90%E7%BB%93%E6%9E%9C_20251211131509.html"))
logger.SugaredLogger.Debugf("value: %s", strutil.After("/data/go-stock-site/docs/分析报告/2025/12/09/市场资讯[市场资讯]-(2025-12-09)AI分析结果.md", "/data/go-stock-site/docs/"))
}

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,12 @@ 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(7)
go func() {
defer wg.Done()
datas := NewMarketNewsApi().InteractiveAnswer(1, 100, "")
@@ -200,8 +203,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,8 +230,9 @@ 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(),
})
}()
@@ -250,8 +255,9 @@ func (o *OpenAi) NewSummaryStockNewsStreamWithTools(userQuestion string, sysProm
"content": "当前市场/大盘/行业/指数行情",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"content": "当前市场/大盘/行业/指数行情如下:\n" + market.String(),
"role": "assistant",
"reasoning_content": "使用工具查询",
"content": "当前市场/大盘/行业/指数行情如下:\n" + market.String(),
})
}()
@@ -280,8 +286,9 @@ 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(),
})
}()
@@ -300,8 +307,9 @@ func (o *OpenAi) NewSummaryStockNewsStreamWithTools(userQuestion string, sysProm
"content": "全球新闻资讯",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"content": newsText.String(),
"role": "assistant",
"reasoning_content": "使用工具查询",
"content": newsText.String(),
})
}()
@@ -318,27 +326,33 @@ func (o *OpenAi) NewSummaryStockNewsStreamWithTools(userQuestion string, sysProm
"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(),
})
go func() {
defer wg.Done()
news := NewMarketNewsApi().GetNewsList2("财联社电报", random.RandInt(100, 500))
messageText := strings.Builder{}
for _, telegraph := range *news {
messageText.WriteString("## " + telegraph.Time + ":" + "\n")
messageText.WriteString("### " + telegraph.Content + "\n")
}
msg = append(msg, map[string]interface{}{
"role": "user",
"content": "市场资讯",
})
msg = append(msg, map[string]interface{}{
"role": "assistant",
"reasoning_content": "使用工具查询",
"content": messageText.String(),
})
}()
wg.Wait()
if userQuestion == "" {
userQuestion = "请根据当前时间,总结和分析股票市场新闻中的投资机会"
}
@@ -346,12 +360,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,7 +409,7 @@ func (o *OpenAi) NewSummaryStockNewsStream(userQuestion string, sysPromptId *int
"content": "当前本地时间是:" + time.Now().Format("2006-01-02 15:04:05"),
})
wg := &sync.WaitGroup{}
wg.Add(4)
wg.Add(5)
go func() {
defer wg.Done()
var market strings.Builder
@@ -470,6 +484,27 @@ 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))
@@ -495,12 +530,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() {
@@ -856,15 +891,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,11 +908,18 @@ 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,
"model": o.Model,
"thinking": map[string]any{
"type": thinking,
},
"max_tokens": o.MaxTokens,
"temperature": o.Temperature,
"stream": true,
@@ -1005,7 +1047,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)
@@ -1014,11 +1059,20 @@ 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,
"model": o.Model,
"thinking": map[string]any{
//"type": "disabled",
//"type": "enabled",
"type": thinking,
},
"max_tokens": o.MaxTokens,
"temperature": o.Temperature,
"stream": true,
@@ -1046,6 +1100,8 @@ func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch
currentFuncName := ""
currentCallId := ""
var currentAIContent strings.Builder
var reasoningContentText strings.Builder
var contentText strings.Builder
for scanner.Scan() {
line := scanner.Text()
@@ -1081,6 +1137,7 @@ func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch
if err := json.Unmarshal([]byte(data), &streamResponse); err == nil {
for _, choice := range streamResponse.Choices {
if content := choice.Delta.Content; content != "" {
contentText.WriteString(content)
//ch <- content
//logger.SugaredLogger.Infof("Content data: %s", content)
@@ -1108,6 +1165,7 @@ func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch
}
if reasoningContent := choice.Delta.ReasoningContent; reasoningContent != "" {
reasoningContentText.WriteString(reasoningContent)
//ch <- reasoningContent
ch <- map[string]any{
"code": 1,
@@ -1154,7 +1212,7 @@ func AskAiWithTools(o *OpenAi, err error, messages []map[string]interface{}, ch
}
content := "无符合条件的数据"
res := NewSearchStockApi(words).SearchStock(random.RandInt(5, 20))
res := NewSearchStockApi(words).SearchStock(random.RandInt(50, 120))
if convertor.ToString(res["code"]) == "100" {
resData := res["data"].(map[string]any)
result := resData["result"].(map[string]any)
@@ -1191,8 +1249,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,
@@ -1210,6 +1269,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{
@@ -1264,8 +1326,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,
@@ -1284,6 +1347,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)
@@ -1297,8 +1362,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,
@@ -1316,6 +1382,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,
})
}
}
@@ -1344,8 +1412,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,
@@ -1363,6 +1432,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,
})
}
//
@@ -1478,8 +1549,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,
@@ -1497,11 +1569,50 @@ 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,
})
}
}
AskAiWithTools(o, err, messages, ch, question, tools)
AskAiWithTools(o, err, messages, ch, question, tools, thinkingMode)
}
if choice.FinishReason == "stop" {
@@ -1549,7 +1660,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

@@ -9,6 +9,7 @@ import (
func TestNewDeepSeekOpenAiConfig(t *testing.T) {
db.Init("../../data/stock.db")
InitAnalyzeSentiment()
var tools []Tool
tools = append(tools, Tool{
@@ -29,7 +30,7 @@ func TestNewDeepSeekOpenAiConfig(t *testing.T) {
},
})
ai := NewDeepSeekOpenAi(context.TODO(), 1)
ai := NewDeepSeekOpenAi(context.TODO(), 0)
//res := ai.NewChatStream("长电科技", "sh600584", "长电科技分析和总结", nil)
res := ai.NewSummaryStockNewsStreamWithTools("总结市场资讯,发掘潜力标的/行业/板块/概念,控制风险。调用工具函数验证", nil, tools)

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,16 @@ 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
}

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,20 @@ 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)
//}
}

View File

@@ -1484,11 +1484,11 @@ func (receiver StockDataApi) getDCStockInfo(market string, page, pageSize int) {
url := "https://push2.eastmoney.com/api/qt/clist/get?np=1&fltt=1&invt=2&cb=data&fs=%s&fields=f12,f13,f14,f1,f2,f4,f3,f152,f5,f6,f7,f15,f18,f16,f17,f10,f8,f9,f23,f100,f265&fid=f3&pn=%d&pz=%d&po=1&dect=1&wbp2u=|0|0|0|web&_=%d"
sprintfUrl := fmt.Sprintf(url, fs, page, pageSize, time.Now().UnixMilli())
logger.SugaredLogger.Infof("url:%s", sprintfUrl)
logger.SugaredLogger.Infof("page:%d url:%s", page, sprintfUrl)
resp, err := receiver.client.SetTimeout(time.Duration(receiver.config.CrawlTimeOut)*time.Second).R().
SetHeader("Host", "push2.eastmoney.com").
SetHeader("Referer", "https://quote.eastmoney.com/center/gridlist.html").
SetHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0").
SetHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:146.0) Gecko/20100101 Firefox/146.0").
Get(sprintfUrl)
if err != nil {
logger.SugaredLogger.Errorf("err:%s", err.Error())

View File

@@ -121,10 +121,10 @@ func TestGetHKStockInfo(t *testing.T) {
//NewStockDataApi().GetSinaHKStockInfo()
//m:105,m:106,m:107 //美股
//m:128+t:3,m:128+t:4,m:128+t:1,m:128+t:2 //港股
//287 224 605
for i := 1; i <= 605; i++ {
NewStockDataApi().getDCStockInfo("us", i, 20)
time.Sleep(time.Duration(random.RandInt(1, 3)) * time.Second)
//274 224 605
for i := 197; i <= 274; i++ {
NewStockDataApi().getDCStockInfo("", i, 20)
time.Sleep(time.Duration(random.RandInt(2, 5)) * time.Second)
}
}
@@ -270,15 +270,16 @@ func TestName(t *testing.T) {
db.Init("../../data/stock.db")
stockBasics := &[]StockBasic{}
resty.New().R().
resty.New().SetProxy("").R().
SetHeader("user", "go-stock").
SetResult(stockBasics).
Get("http://8.134.249.145:18080/go-stock/stock_basic.json")
db.Dao.Unscoped().Model(&StockBasic{}).Where("1=1").Delete(&StockBasic{})
err := db.Dao.CreateInBatches(stockBasics, 400).Error
if err != nil {
t.Log(err.Error())
}
logger.SugaredLogger.Infof("%+v", stockBasics)
//db.Dao.Unscoped().Model(&StockBasic{}).Where("1=1").Delete(&StockBasic{})
//err := db.Dao.CreateInBatches(stockBasics, 400).Error
//if err != nil {
// t.Log(err.Error())
//}
}

View File

@@ -3,7 +3,6 @@ package data
import (
"bufio"
_ "embed"
"errors"
"fmt"
"go-stock/backend/db"
"go-stock/backend/logger"
@@ -18,7 +17,6 @@ import (
"github.com/duke-git/lancet/v2/fileutil"
"github.com/duke-git/lancet/v2/strutil"
"github.com/go-ego/gse"
"github.com/vcaesar/cedar"
)
const basefreq float64 = 100
@@ -75,7 +73,17 @@ var baseDict string
var zhDict string
func InitAnalyzeSentiment() {
//err := seg.LoadDictEmbed()
defer func() {
if r := recover(); r != nil {
logger.SugaredLogger.Error(fmt.Sprintf("panic: %v", r))
}
}()
// 加载简体中文词典
//err := seg.LoadDict("zh_s")
//if err != nil {
// logger.SugaredLogger.Error(err.Error())
//}
err := seg.LoadDictEmbed(baseDict)
if err != nil {
logger.SugaredLogger.Error(err.Error())
@@ -98,6 +106,8 @@ func InitAnalyzeSentiment() {
logger.SugaredLogger.Errorf("添加%s失败:%s", stock.Name, err.Error())
}
}
logger.SugaredLogger.Info("加载股票名称词典成功")
stockhks := &[]models.StockInfoHK{}
db.Dao.Model(&models.StockInfoHK{}).Find(stockhks)
for _, stock := range *stockhks {
@@ -112,6 +122,7 @@ func InitAnalyzeSentiment() {
logger.SugaredLogger.Errorf("添加%s失败:%s", stock.Name, err.Error())
}
}
logger.SugaredLogger.Info("加载港股名称词典成功")
//stockus := &[]models.StockInfoUS{}
//db.Dao.Model(&models.StockInfoUS{}).Where("trim(name) != ?", "").Find(stockus)
//for _, stock := range *stockus {
@@ -123,16 +134,17 @@ func InitAnalyzeSentiment() {
tags := &[]models.Tags{}
db.Dao.Model(&models.Tags{}).Where("type = ?", "subject").Find(tags)
for _, tag := range *tags {
err := seg.ReAddToken(tag.Name, basefreq+100, "n")
if tag.Name == "" {
continue
}
err := seg.AddToken(tag.Name, basefreq+100, "n")
if err != nil {
if errors.Is(err, cedar.ErrNoKey) {
err := seg.AddToken(tag.Name, basefreq+100, "n")
if err != nil {
logger.SugaredLogger.Errorf("添加%s失败:%s", tag.Name, err.Error())
}
}
logger.SugaredLogger.Errorf("添加%s失败:%s", tag.Name, err.Error())
} else {
logger.SugaredLogger.Infof("添加tags词典[%s]成功", tag.Name)
}
}
logger.SugaredLogger.Info("加载tags词典成功")
seg.CalcToken()
//加载用户自定义词典 先判断用户词典是否存在
if fileutil.IsExist("data/dict/user.txt") {
@@ -181,18 +193,12 @@ func InitAnalyzeSentiment() {
} else {
logger.SugaredLogger.Infof("加载用户词典成功")
}
} else {
logger.SugaredLogger.Info("用户词典不存在")
}
seg.CalcToken()
}
// WordFreqWithWeight 词频统计结果,包含权重信息
type WordFreqWithWeight struct {
Word string
Frequency int
Weight float64
Score float64
}
// getWordWeight 获取词汇权重
func getWordWeight(word string) float64 {
// 从分词器获取词汇权重
@@ -200,15 +206,15 @@ func getWordWeight(word string) float64 {
freq, pos, ok := seg.Dictionary().Find([]byte(word))
if ok {
logger.SugaredLogger.Infof("获取%s的权重:%f,pos:%s,ok:%v", word, freq, pos, ok)
return basefreq + freq
return freq
}
return 0
}
// 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)
}
@@ -223,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)
@@ -232,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 {
// 过滤纯标点符号和分隔符
@@ -261,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:]]+$`)
@@ -277,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)
@@ -290,8 +296,8 @@ func countWordFrequencyWithWeight(text string) map[string]WordFreqWithWeight {
// 构建包含权重的结果
for word, frequency := range wordCount {
weight := getWordWeight(word)
if weight > basefreq {
freqMap[word] = WordFreqWithWeight{
if weight >= basefreq {
freqMap[word] = models.WordFreqWithWeight{
Word: word,
Frequency: frequency,
Weight: weight,
@@ -305,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)
@@ -315,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
@@ -374,7 +368,7 @@ func AnalyzeSentiment(text string) SentimentResult {
}
// 确定情感类别
var category SentimentType
var category models.SentimentType
switch {
case score > 1.0:
category = Positive
@@ -384,7 +378,7 @@ func AnalyzeSentiment(text string) SentimentResult {
category = Neutral
}
return SentimentResult{
return models.SentimentResult{
Score: score,
Category: category,
PositiveCount: positiveCount,
@@ -497,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 "看涨"
@@ -542,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

@@ -6,6 +6,8 @@ import (
"go-stock/backend/logger"
"strings"
"testing"
"github.com/duke-git/lancet/v2/random"
)
// @Author spark
@@ -19,15 +21,15 @@ func TestAnalyzeSentiment(t *testing.T) {
InitAnalyzeSentiment()
messageText := strings.Builder{}
//news := NewMarketNewsApi().GetNewsList2("", random.RandInt(500, 1000))
//for _, telegraph := range *news {
// messageText.WriteString(telegraph.Content + "\n")
//}
news := NewMarketNewsApi().GetNewsList2("", random.RandInt(500, 1000))
for _, telegraph := range *news {
messageText.WriteString(telegraph.Content + "\n")
}
text := messageText.String()
//text = " 【周六你需要知道的隔夜全球要闻:美联储鸽声重振 美股走势回稳】 1、纽约联储行长威廉姆斯表示随着劳动力市场走软美联储近期内仍有再次降息的空间。 2、美联储理事斯蒂芬·米兰表示自上次联邦公开市场委员会FOMC会议以来的经济数据应“促使人们偏向鸽派立场”。 3、波士顿联邦储备银行行长柯林斯表示由于通胀可能在一段时间内保持高位维持利率不变“目前合适”。 4、据CME“美联储观察”截至北京时间11月22日6时30分美联储12月降息25个基点的概率为69.4%维持利率不变的概率为30.6%。 5、美国劳工统计局表示11月CPI报告将于12月18日发布同时取消了10月CPI报告发布表示无法追溯采集政府停摆期间未能收集的部分数据。 6、俄罗斯总统普京表示已收到美提出解决俄乌冲突的计划俄罗斯愿意进行和平谈判。美国总统特朗普表示他认为27日是乌克兰接受美国支持的和平计划的最后期限。 7、美联储高官鸽派言论提振市场情绪美股三大指数收盘集体上涨道琼斯指数涨1.08%标普500指数涨0.98%纳斯达克综合指数涨0.88%。甲骨文跌超5%英伟达跌超1%。纳指本周累计跌2.74%标普500指数累跌1.95%道指累跌1.91%。英伟达本周累跌5.9%。 8、热门中概股多数上涨纳斯达克中国金龙指数收涨1.23%。蔚来涨超3%哔哩哔哩、理想汽车涨超2%京东、小鹏汽车涨超1%。 9、国际油价下跌交易员评估乌克兰与俄罗斯可能达成和平协议的前景。WTI 1月期货下跌1.6%结算价报每桶58.06美元为过去五个交易日中第四次下跌。布伦特1月期货下跌1.3%结算价报每桶62.56美元。 10、美联储延长压力测试改进方案征询期为银行反馈提供更多时间。 11、由于美国人对个人财务状况的看法恶化美国消费者信心在11月跌至接近纪录最低水平密歇根大学数据显示11月消费者信心指数降至5110月为53.6。 12、日本央行政策委员会委员Kazuyuki Masu表示日本央行接近作出加息决定。 13、穆迪将意大利信用评级从BAA3上调至BAA2展望稳定。\n"
text = "财联社电英伟达周五冲高回落股价涨幅收于1%,市场普遍认为其走势疲软"
text = "【本轮巴以冲突已致加沙地带69733人死亡】财联社11月22日电当地时间22日下午以军对加沙城西部一辆汽车发动空袭已造成5人死亡多人受伤。自2023年10月7日巴以新一轮大规模冲突爆发以来以色列对加沙地带的袭击已造成69733人死亡、170863人受伤。"
//text = "财联社电英伟达周五冲高回落股价涨幅收于1%,市场普遍认为其走势疲软"
//text = "【本轮巴以冲突已致加沙地带69733人死亡】财联社11月22日电当地时间22日下午以军对加沙城西部一辆汽车发动空袭已造成5人死亡多人受伤。自2023年10月7日巴以新一轮大规模冲突爆发以来以色列对加沙地带的袭击已造成69733人死亡、170863人受伤。"
//text = "【牛肉加工亏损 美国泰森公司关停缩减相关业务】财联社11月22日电受牛肉加工业务亏损影响当地时间21日美国泰森食品公司发布公告称将关闭位于内布拉斯加州的一家大型牛肉加工厂还计划缩小得克萨斯州一家牛肉加工厂的生产规模。根据泰森食品公司的公告被关闭的这家工厂位于内布拉斯加州列克星敦日均可宰杀并处理大约5000头牛约占全美日均牛肉屠宰数量的4.8%。与此同时公司还计划缩小得克萨斯州一家牛肉加工厂的生产规模这家工厂每天大约可屠宰6000头牛。据悉泰森此次业务调整影响两个工厂大约5000个工作岗位。《华尔街日报》报道称泰森是美国四大肉类加工公司中首家关闭主要牛肉加工厂的公司其最新财报显示2025财年牛肉加工是唯一亏损的业务部门调整后的营业亏损为4.26亿美元。"
// 分析情感
words := splitWords(text)

View File

@@ -719,3 +719,51 @@ 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:"-"`
}

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

@@ -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;
@@ -223,7 +224,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() {
@@ -704,6 +705,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

@@ -30,18 +30,26 @@ const updateMessage = () => {
</template>
<n-list-item v-for="item in newsList">
<n-space justify="start" >
<n-text justify="start" :bordered="false" :type="item.isRed?'error':'info'">
<!-- <n-text justify="start" :bordered="false" :type="item.isRed?'error':'info'" style="overflow-wrap: break-word;">-->
<!-- <n-tag size="small" :type="item.isRed?'error':'warning'" :bordered="false"> {{ item.time }}</n-tag>-->
<!-- <n-text size="small" v-if="item.title" type="warning" :bordered="false">{{ item.title }}&nbsp;&nbsp;</n-text>-->
<!-- <n-text style="overflow-wrap: break-word;word-break: break-all; word-wrap: break-word;" :type="item.isRed?'error':'info'">{{ item.content }}</n-text>-->
<!-- </n-text>-->
<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

@@ -24,6 +24,10 @@ import EmbeddedUrl from "./EmbeddedUrl.vue";
<n-tab-pane name="财联社-行情数据" tab="财联社-行情数据">
<embedded-url url="https://www.cls.cn/quotation" :height="'calc(100vh - 252px)'"/>
</n-tab-pane>
<n-tab-pane name="消息墙" tab="消息墙">
<embedded-url url="https://go-stock.sparkmemory.top:16667/go-stock" :height="'calc(100vh - 252px)'"/>
</n-tab-pane>
<n-tab-pane name="欢迎推荐更多有趣的财经网页" tab="欢迎推荐更多有趣的财经网页">

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

View File

@@ -48,6 +48,10 @@ export function EventsOff(eventName, ...additionalEventNames) {
return window.runtime.EventsOff(eventName, ...additionalEventNames);
}
export function EventsOffAll() {
return window.runtime.EventsOffAll();
}
export function EventsOnce(eventName, callback) {
return EventsOnMultiple(eventName, callback, 1);
}

105
go.mod
View File

@@ -3,96 +3,95 @@ module go-stock
go 1.25.0
require (
github.com/PuerkitoBio/goquery v1.10.1
github.com/chromedp/chromedp v0.14.1
github.com/cloudwego/eino v0.4.1
github.com/cloudwego/eino-ext/components/model/ark v0.1.19
github.com/cloudwego/eino-ext/components/model/deepseek v0.0.0-20250804092122-8845979a2228
github.com/cloudwego/eino-ext/components/model/openai v0.0.0-20250804092122-8845979a2228
github.com/PuerkitoBio/goquery v1.11.0
github.com/chromedp/chromedp v0.14.2
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
github.com/coocood/freecache v1.2.4
github.com/duke-git/lancet/v2 v2.3.4
github.com/duke-git/lancet/v2 v2.3.8
github.com/energye/systray v1.0.2
github.com/gen2brain/beeep v0.11.1
github.com/glebarez/sqlite v1.11.0
github.com/go-ego/gse v0.80.3
github.com/go-resty/resty/v2 v2.16.2
github.com/go-resty/resty/v2 v2.17.0
github.com/go-toast/toast v0.0.0-20190211030409-01e6764cf0a4
github.com/inconshreveable/go-update v0.0.0-20160112193335-8152e7eb6ccf
github.com/robertkrimen/otto v0.5.1
github.com/robfig/cron/v3 v3.0.1
github.com/samber/lo v1.49.1
github.com/stretchr/testify v1.10.0
github.com/tidwall/gjson v1.14.4
github.com/vcaesar/cedar v0.20.2
github.com/wailsapp/wails/v2 v2.10.1
go.uber.org/zap v1.27.0
github.com/samber/lo v1.52.0
github.com/stretchr/testify v1.11.1
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/net v0.47.0
golang.org/x/sys v0.38.0
golang.org/x/text v0.31.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1
gorm.io/gorm v1.25.12
gorm.io/plugin/dbresolver v1.5.3
gorm.io/gorm v1.31.1
gorm.io/plugin/dbresolver v1.6.2
gorm.io/plugin/soft_delete v1.2.1
)
require (
git.sr.ht/~jackmordaunt/go-toast v1.1.2 // indirect
github.com/andybalholm/cascadia v1.3.3 // indirect
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/bep/debounce v1.2.1 // indirect
github.com/bytedance/sonic v1.14.0 // indirect
github.com/bytedance/sonic/loader v0.3.0 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/buger/jsonparser v1.1.1 // indirect
github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic v1.14.2 // indirect
github.com/bytedance/sonic/loader v0.4.0 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d // indirect
github.com/chromedp/sysutil v1.1.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/cloudwego/eino-ext/libs/acl/openai v0.0.0-20250804062529-6e67726a4b3f // indirect
github.com/cloudwego/eino-ext/libs/acl/openai v0.1.6 // indirect
github.com/cohesion-org/deepseek-go v1.3.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/eino-contrib/jsonschema v1.0.3 // indirect
github.com/esiqveland/notify v0.13.3 // indirect
github.com/evanphx/json-patch v0.5.2 // indirect
github.com/getkin/kin-openapi v0.118.0 // indirect
github.com/glebarez/go-sqlite v1.21.2 // indirect
github.com/go-json-experiment/json v0.0.0-20250910080747-cc2cfa0554c3 // indirect
github.com/glebarez/go-sqlite v1.22.0 // indirect
github.com/go-json-experiment/json v0.0.0-20251027170946-4849db3c2f7e // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-openapi/jsonpointer v0.21.0 // indirect
github.com/go-openapi/swag v0.23.0 // indirect
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
github.com/gobwas/ws v1.4.0 // indirect
github.com/godbus/dbus/v5 v5.1.0 // indirect
github.com/godbus/dbus/v5 v5.2.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/goph/emperror v0.17.2 // indirect
github.com/invopop/yaml v0.1.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/jackmordaunt/icns/v3 v3.0.1 // indirect
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e // indirect
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/joho/godotenv v1.5.1 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/labstack/echo/v4 v4.13.3 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/labstack/echo/v4 v4.13.4 // indirect
github.com/labstack/gommon v0.4.2 // indirect
github.com/leaanthony/go-ansi-parser v1.6.1 // indirect
github.com/leaanthony/gosod v1.0.4 // indirect
github.com/leaanthony/slicer v1.6.0 // indirect
github.com/leaanthony/u v1.1.1 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mailru/easyjson v0.9.1 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/meguminnnnnnnnn/go-openai v0.0.0-20250723112853-3bce976e5ccc // indirect
github.com/meguminnnnnnnnn/go-openai v0.1.1 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect
github.com/nikolalohinski/gonja v1.5.3 // indirect
github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d // indirect
github.com/ollama/ollama v0.6.5 // indirect
github.com/openai/openai-go v1.10.1 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/perimeterx/marshmallow v1.1.5 // indirect
github.com/ollama/ollama v0.13.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
@@ -100,34 +99,36 @@ require (
github.com/rivo/uniseg v0.4.7 // indirect
github.com/rogpeppe/go-internal v1.14.1 // indirect
github.com/sergeymakinen/go-bmp v1.0.0 // indirect
github.com/sergeymakinen/go-ico v1.0.0-beta.0 // indirect
github.com/sergeymakinen/go-ico v1.0.0 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/slongfield/pyfmt v0.0.0-20220222012616-ea85ff4c361f // indirect
github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirect
github.com/tevino/abool v0.0.0-20220530134649-2bfc934cb23c // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/match v1.2.0 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/tidwall/sjson v1.2.5 // indirect
github.com/tkrajina/go-reflector v0.5.8 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
github.com/volcengine/volc-sdk-golang v1.0.23 // indirect
github.com/volcengine/volcengine-go-sdk v1.1.21 // indirect
github.com/wailsapp/go-webview2 v1.0.19 // indirect
github.com/vcaesar/cedar v0.20.2 // indirect
github.com/volcengine/volc-sdk-golang v1.0.229 // indirect
github.com/volcengine/volcengine-go-sdk v1.1.50 // indirect
github.com/wailsapp/go-webview2 v1.0.23 // indirect
github.com/wailsapp/mimetype v1.4.1 // indirect
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
github.com/yargevad/filepathx v1.0.0 // indirect
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/arch v0.20.0 // indirect
golang.org/x/crypto v0.44.0 // indirect
golang.org/x/exp v0.0.0-20250218142911-aa4b98e5adaa // indirect
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
gopkg.in/yaml.v3 v3.0.1 // indirect
modernc.org/libc v1.22.5 // indirect
modernc.org/mathutil v1.5.0 // indirect
modernc.org/memory v1.5.0 // indirect
modernc.org/sqlite v1.23.1 // indirect
modernc.org/libc v1.67.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
modernc.org/sqlite v1.40.1 // indirect
)
// replace github.com/wailsapp/wails/v2 v2.9.2 => C:\Users\spark\go\pkg\mod

917
go.sum

File diff suppressed because it is too large Load Diff

13
main.go
View File

@@ -58,6 +58,13 @@ var OFFICIAL_STATEMENT string
var BuildKey string
func main() {
defer func() {
if r := recover(); r != nil {
log.SugaredLogger.Error("panic: ", r)
log.SugaredLogger.Error("stack: ", string(debug.Stack()))
}
}()
checkDir("data")
db.Init("")
data.InitAnalyzeSentiment()
@@ -68,6 +75,10 @@ func main() {
// Sort: 0,
//})
log.SugaredLogger.Info("starting...")
log.SugaredLogger.Infof("version: %s commit: %s", Version, VersionCommit)
//log.SugaredLogger.Infof("build key: %s", BuildKey)
// Create an instance of the app structure
app := NewApp()
AppMenu := menu.NewMenu()
@@ -230,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()
}