Skip to content

Commit b00bddc

Browse files
author
spark
committed
refactor(stock-data): 重构股票数据获取逻辑
- 移除了不必要的并发请求,简化了代码结构 - 新增 FetchPrice 函数,用于获取股票价格信息 - 优化 SearchStockInfo 函数,提高了搜索效率和准确性 - 新增 SearchStockInfoByCode 函数,用于根据股票代码获取相关信息- 修复了一些潜在的错误和性能问题
1 parent 64b37b6 commit b00bddc

File tree

4 files changed

+92
-34
lines changed

4 files changed

+92
-34
lines changed

backend/data/openai_api.go

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ func (o OpenAi) NewChatStream(stock, stockCode string) <-chan string {
142142
}
143143

144144
wg := &sync.WaitGroup{}
145-
wg.Add(4)
145+
wg.Add(2)
146146

147147
go func() {
148148
defer wg.Done()
@@ -168,26 +168,26 @@ func (o OpenAi) NewChatStream(stock, stockCode string) <-chan string {
168168
}
169169
}()
170170

171-
go func() {
172-
defer wg.Done()
173-
messages := SearchStockInfo(stock, "depth")
174-
for _, message := range *messages {
175-
msg = append(msg, map[string]interface{}{
176-
"role": "assistant",
177-
"content": message,
178-
})
179-
}
180-
}()
181-
go func() {
182-
defer wg.Done()
183-
messages := SearchStockInfo(stock, "telegram")
184-
for _, message := range *messages {
185-
msg = append(msg, map[string]interface{}{
186-
"role": "assistant",
187-
"content": message,
188-
})
189-
}
190-
}()
171+
//go func() {
172+
// defer wg.Done()
173+
// messages := SearchStockInfo(stock, "depth")
174+
// for _, message := range *messages {
175+
// msg = append(msg, map[string]interface{}{
176+
// "role": "assistant",
177+
// "content": message,
178+
// })
179+
// }
180+
//}()
181+
//go func() {
182+
// defer wg.Done()
183+
// messages := SearchStockInfo(stock, "telegram")
184+
// for _, message := range *messages {
185+
// msg = append(msg, map[string]interface{}{
186+
// "role": "assistant",
187+
// "content": message,
188+
// })
189+
// }
190+
//}()
191191
wg.Wait()
192192

193193
msg = append(msg, map[string]interface{}{

backend/data/openai_api_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ func TestNewDeepSeekOpenAiConfig(t *testing.T) {
1313
select {
1414
case msg := <-res:
1515
if msg == "" {
16-
return
16+
continue
1717
}
1818
t.Log(msg)
1919
}

backend/data/stock_data_api.go

Lines changed: 66 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -524,16 +524,8 @@ func SearchStockPriceInfo(stockCode string) *[]string {
524524
tasks = append(tasks, chromedp.Navigate(url))
525525
tasks = append(tasks, chromedp.WaitVisible("div.quote-change-box", chromedp.ByQuery))
526526
tasks = append(tasks, chromedp.ActionFunc(func(ctx context.Context) error {
527-
chromedp.WaitVisible("span.quote-price", chromedp.ByQuery)
528-
price := ""
529-
for {
530-
chromedp.Text("span.quote-price", &price, chromedp.BySearch).Do(ctx)
531-
logger.SugaredLogger.Infof("price:%s", price)
532-
if price != "" && validator.IsNumberStr(price) {
533-
break
534-
}
535-
}
536-
527+
price, _ := FetchPrice(ctx)
528+
logger.SugaredLogger.Infof("price:%s", price)
537529
return nil
538530
}))
539531
tasks = append(tasks, chromedp.OuterHTML("html", &htmlContent, chromedp.ByQuery))
@@ -557,6 +549,29 @@ func SearchStockPriceInfo(stockCode string) *[]string {
557549
})
558550
return &messages
559551
}
552+
func FetchPrice(ctx context.Context) (string, error) {
553+
var price string
554+
timeout := time.After(10 * time.Second) // 设置超时时间为10秒
555+
ticker := time.NewTicker(1 * time.Second) // 每秒尝试一次
556+
defer ticker.Stop()
557+
558+
for {
559+
select {
560+
case <-timeout:
561+
return "", fmt.Errorf("timeout reached while fetching price")
562+
case <-ticker.C:
563+
err := chromedp.Run(ctx, chromedp.Text("span.quote-price", &price, chromedp.BySearch))
564+
if err != nil {
565+
logger.SugaredLogger.Errorf("failed to fetch price: %v", err)
566+
continue
567+
}
568+
logger.SugaredLogger.Infof("price:%s", price)
569+
if price != "" && validator.IsNumberStr(price) {
570+
return price, nil
571+
}
572+
}
573+
}
574+
}
560575
func SearchStockInfo(stock, msgType string) *[]string {
561576
// 创建一个 chromedp 上下文
562577
ctx, cancel := chromedp.NewContext(
@@ -567,11 +582,50 @@ func SearchStockInfo(stock, msgType string) *[]string {
567582
defer cancel()
568583
var htmlContent string
569584
url := fmt.Sprintf("https://www.cls.cn/searchPage?keyword=%s&type=%s", stock, msgType)
585+
err := chromedp.Run(ctx,
586+
chromedp.Navigate(url),
587+
// 等待页面加载完成,可以根据需要调整等待时间
588+
chromedp.Sleep(3*time.Second),
589+
//chromedp.WaitVisible("a.search-content", chromedp.ByQuery),
590+
chromedp.OuterHTML("html", &htmlContent, chromedp.ByQuery),
591+
)
592+
if err != nil {
593+
logger.SugaredLogger.Error(err.Error())
594+
return &[]string{}
595+
}
596+
document, err := goquery.NewDocumentFromReader(strings.NewReader(htmlContent))
597+
if err != nil {
598+
logger.SugaredLogger.Error(err.Error())
599+
return &[]string{}
600+
}
601+
var messages []string
602+
document.Find("a.search-content").Each(func(i int, selection *goquery.Selection) {
603+
text := strutil.RemoveNonPrintable(selection.Text())
604+
if strings.Contains(text, stock) {
605+
messages = append(messages, text)
606+
logger.SugaredLogger.Infof("搜索到消息: %s", text)
607+
}
608+
})
609+
return &messages
610+
}
611+
612+
func SearchStockInfoByCode(stock string) *[]string {
613+
// 创建一个 chromedp 上下文
614+
ctx, cancel := chromedp.NewContext(
615+
context.Background(),
616+
chromedp.WithLogf(logger.SugaredLogger.Infof),
617+
chromedp.WithErrorf(logger.SugaredLogger.Errorf),
618+
)
619+
defer cancel()
620+
var htmlContent string
621+
stock = strings.ReplaceAll(stock, "sh", "")
622+
stock = strings.ReplaceAll(stock, "sz", "")
623+
url := fmt.Sprintf("https://gushitong.baidu.com/stock/ab-%s", stock)
570624
err := chromedp.Run(ctx,
571625
chromedp.Navigate(url),
572626
// 等待页面加载完成,可以根据需要调整等待时间
573627
//chromedp.Sleep(3*time.Second),
574-
chromedp.WaitVisible("div.search-content,a.search-content", chromedp.ByQuery),
628+
chromedp.WaitVisible("a.news-item-link", chromedp.ByQuery),
575629
chromedp.OuterHTML("html", &htmlContent, chromedp.ByQuery),
576630
)
577631
if err != nil {
@@ -584,7 +638,7 @@ func SearchStockInfo(stock, msgType string) *[]string {
584638
return &[]string{}
585639
}
586640
var messages []string
587-
document.Find("div.search-telegraph-list,a.search-content").Each(func(i int, selection *goquery.Selection) {
641+
document.Find("a.news-item-link").Each(func(i int, selection *goquery.Selection) {
588642
text := strutil.RemoveNonPrintable(selection.Text())
589643
if strings.Contains(text, stock) {
590644
messages = append(messages, text)

backend/data/stock_data_api_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,10 @@ func TestGetTelegraphSearch(t *testing.T) {
5050

5151
//https://www.cls.cn/stock?code=sh600745
5252
}
53+
func TestSearchStockInfoByCode(t *testing.T) {
54+
SearchStockInfoByCode("sh600745")
55+
}
56+
5357
func TestSearchStockPriceInfo(t *testing.T) {
5458
SearchStockPriceInfo("sh600745")
5559
}

0 commit comments

Comments
 (0)