/
news.go
273 lines (235 loc) · 7.37 KB
/
news.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// Copyright (c) 2022 James Bury. All rights reserved.
// Project site: https://github.com/d3an/finviz
// Use of this source code is governed by a MIT-style license that
// can be found in the LICENSE file for the project.
package news
import (
"fmt"
"io"
"net"
"net/http"
"strings"
"sync"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/corpix/uarand"
"github.com/dnaeon/go-vcr/recorder"
"github.com/go-gota/gota/dataframe"
"github.com/d3an/finviz/utils"
)
const (
APIURL = "https://finviz.com/news.ashx"
)
var (
once sync.Once
instance *Client
)
type Config struct {
userAgent string
recorder *recorder.Recorder
}
type Client struct {
*http.Client
config Config
}
func New(config *Config) *Client {
once.Do(func() {
transport := &http.Transport{
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 30 * time.Second,
}
client := &http.Client{
Timeout: 30 * time.Second,
Transport: transport,
}
if config != nil {
instance = &Client{Client: client, config: *config}
}
instance = &Client{
Client: client,
config: Config{userAgent: uarand.GetRandom()},
}
})
return instance
}
func (c *Client) Do(req *http.Request) (*http.Response, error) {
req.Header.Set("User-Agent", c.config.userAgent)
return c.Client.Do(req)
}
// GetNews returns a DataFrame containing recent news data
func (c *Client) GetNews(view string) (*dataframe.DataFrame, error) {
url, err := GenerateURL(view)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodGet, url, http.NoBody)
if err != nil {
return nil, err
}
resp, err := c.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("error getting url: '%s', status code: '%d', body: '%s'", url, resp.StatusCode, string(body))
}
doc, err := utils.GenerateDocument(body)
if err != nil {
return nil, err
}
results, err := Scrape(view, doc)
if err != nil {
return nil, err
}
df := dataframe.LoadRecords(results)
return &df, nil
}
func GenerateURL(view string) (string, error) {
switch view {
case "time":
return APIURL, nil
case "source":
return fmt.Sprintf("%s?v=2", APIURL), nil
default:
return "", fmt.Errorf("error view '%s' not found", view)
}
}
func Scrape(view string, doc *goquery.Document) ([][]string, error) {
switch view {
case "time":
return ByTimeScrape(doc)
case "source":
return BySourceScrape(doc)
default:
return nil, fmt.Errorf("error view '%s' not found", view)
}
}
func ByTimeScrape(doc *goquery.Document) ([][]string, error) {
var newsDataSlice []map[string]interface{}
location, err := time.LoadLocation("EST5EDT")
if err != nil {
return nil, err
}
today := time.Now().In(location)
doc.Find("#news > div").Children().Eq(1).Find("tbody").Eq(0).Children().Eq(1).Children().Each(func(i int, newsColumn *goquery.Selection) {
var newsType string
switch i {
case 0:
newsType = "news"
case 2:
newsType = "blog"
}
if i != 1 {
newsColumn.Find("tbody").Eq(0).Children().Each(func(j int, newsItem *goquery.Selection) {
var rawNewsData = make(map[string]interface{})
var date time.Time
rawDate := newsItem.Children().Eq(1).Text()
if date, err = time.Parse("Jan-02-2006 MST", fmt.Sprintf("%s-%d EST", rawDate, today.Year())); err == nil {
rawNewsData["Article Date"] = date.Format(time.RFC3339)
} else if date, err = time.Parse("January-02-2006 3:04PM MST", fmt.Sprintf("%s-%d-%d %s EST", today.Month(), today.Day(), today.Year(), rawDate)); err == nil {
rawNewsData["Article Date"] = date.Format(time.RFC3339)
} else {
rawNewsData["Article Date"] = rawDate
}
rawNewsData["Article Title"] = newsItem.Children().Eq(2).Children().Eq(0).Text()
rawNewsData["Article URL"] = newsItem.Children().Eq(2).Children().Eq(0).AttrOr("href", "")
if classes := newsItem.Children().Eq(0).AttrOr("class", ""); classes != "" {
if val, exists := SourceAttributeLookup[strings.Split(classes, " ")[1]]; exists {
rawNewsData["Source Name"] = val
} else {
rawNewsData["Source Name"] = "Unknown"
}
}
rawNewsData["News Type"] = newsType
newsDataSlice = append(newsDataSlice, rawNewsData)
})
}
})
headers := []string{"Article Date", "Article Title", "Article URL", "Source Name", "News Type"}
return utils.GenerateRows(headers, newsDataSlice)
}
func BySourceScrape(doc *goquery.Document) ([][]string, error) {
var newsDataSlice []map[string]interface{}
location, err := time.LoadLocation("EST5EDT")
if err != nil {
return nil, err
}
today := time.Now().In(location)
for tableIndex := 2; tableIndex <= 4; tableIndex++ {
var newsType string
switch tableIndex {
case 2:
newsType = "news"
case 4:
newsType = "blog"
}
if tableIndex != 3 {
doc.Find("#news > div").Children().Eq(tableIndex).Find("tr").Children().Each(func(i int, newsColumn *goquery.Selection) {
if align := newsColumn.AttrOr("align", ""); align != "" {
newsColumn.Children().Each(func(j int, newsSource *goquery.Selection) {
var sourceName string
var sourceURL string
newsSource.Find("tbody").Eq(0).Children().Each(func(k int, item *goquery.Selection) {
if k == 1 {
sourceItem := item.Find("tr").Children().Eq(1).Find("a")
sourceName = sourceItem.Text()
sourceURL = sourceItem.AttrOr("href", "")
} else if k > 1 {
var rawNewsData = make(map[string]interface{})
var date time.Time
rawDate := item.Children().Eq(0).Text()
if date, err = time.Parse("Jan-02-2006 MST", fmt.Sprintf("%s-%d EST", rawDate, today.Year())); err == nil {
rawNewsData["Article Date"] = date.Format(time.RFC3339)
} else if date, err = time.Parse("January-02-2006 3:04PM MST", fmt.Sprintf("%s-%d-%d %s EST", today.Month(), today.Day(), today.Year(), rawDate)); err == nil {
rawNewsData["Article Date"] = date.Format(time.RFC3339)
} else {
rawNewsData["Article Date"] = rawDate
}
rawNewsData["Article Title"] = item.Children().Eq(1).Find("a").Text()
rawNewsData["Article URL"] = item.Children().Eq(1).Children().Eq(0).AttrOr("href", "")
rawNewsData["Source Name"] = sourceName
rawNewsData["Source URL"] = sourceURL
rawNewsData["News Type"] = newsType
newsDataSlice = append(newsDataSlice, rawNewsData)
}
})
})
}
})
}
}
headers := []string{"Article Date", "Article Title", "Article URL", "Source Name", "Source URL", "News Type"}
return utils.GenerateRows(headers, newsDataSlice)
}
// SourceAttributeLookup provides an interface for identifying news sources based on their CSS attributes
var SourceAttributeLookup = map[string]string{
"is-1": "MarketWatch",
"is-2": "WSJ",
"is-3": "Reuters",
"is-4": "Yahoo Finance",
"is-5": "CNN",
"is-6": "The New York Times",
"is-7": "Bloomberg",
"is-9": "BBC",
"is-10": "CNBC",
"is-11": "Fox Business",
"is-102": "Mish's Global Economic Trend Analysis",
"is-105": "Trader Feed",
"is-113": "Howard Lindzon",
"is-114": "Seeking Alpha",
"is-121": "The Disciplined Investor",
"is-123": "Fallond Stock Picks",
"is-132": "Zero Hedge",
"is-133": "market folly",
"is-136": "Daily Reckoning",
"is-137": "Vantage Point Trading",
"is-141": "Abnormal Returns",
"is-142": "Calculated Risk",
}