Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

db_stocks+news+etfs.py 7.6 KB

You have to be logged in to leave a comment. Sign In
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
  1. import os
  2. import requests
  3. import sqlalchemy as db
  4. import yfinance as yf
  5. import pandas as pd
  6. from sqlalchemy import text
  7. import time
  8. from ib_insync import *
  9. def create_db():
  10. # create database:
  11. engine = db.create_engine('sqlite:///atradebot.db', echo=True)
  12. connection = engine.connect()
  13. metadata = db.MetaData()
  14. # create a single table:
  15. stocks = db.Table('stocks', metadata,
  16. db.Column('id', db.Integer(), primary_key=True),
  17. db.Column('symbol', db.String(255), nullable=True),
  18. db.Column('name', db.String(255), nullable=True),
  19. db.Column('sector', db.String(255), nullable=True),
  20. db.Column('industry', db.String(255), nullable=True),
  21. db.Column('live_price', db.Float(), nullable=True),
  22. db.Column('prev_close', db.Float(), nullable=True),
  23. db.Column('open', db.Float(), nullable=True),
  24. db.Column("volume", db.Integer(), nullable=True),
  25. )
  26. news = db.Table('news', metadata,
  27. db.Column('id', db.Integer(), primary_key=True),
  28. db.Column('symbol', db.String(255), nullable=True),
  29. db.Column('title', db.String(255), nullable=True),
  30. db.Column('news_date', db.String(255), nullable=True),
  31. db.Column('url', db.String(255), nullable=True),
  32. db.Column('source', db.String(255), nullable=True),
  33. db.Column('text', db.String(255), nullable=True),
  34. )
  35. etfs = db.Table("etfs", metadata,
  36. db.Column("id", db.Integer(), primary_key=True),
  37. db.Column("symbol", db.String(255), nullable=True),
  38. db.Column('name', db.String(255), nullable=True),
  39. db.Column('sector', db.String(255), nullable=True),
  40. db.Column('industry', db.String(255), nullable=True),
  41. db.Column('live_price', db.Float(), nullable=True),
  42. db.Column('prev_close', db.Float(), nullable=True),
  43. db.Column('open', db.Float(), nullable=True),
  44. db.Column("volume", db.Integer(), nullable=True),
  45. )
  46. # create table in database:
  47. metadata.create_all(engine)
  48. return engine, connection, stocks, news
  49. if __name__ == "__main__":
  50. engine, connection, stocks, news = create_db()
  51. connection.execute(text("PRAGMA journal_mode=WAL"))
  52. # get list of stocks:
  53. stock_df = pd.read_excel('SP_500_Companies.xlsx')
  54. symbols = stock_df['Symbol'].tolist()
  55. ib = IB()
  56. ib.connect('127.0.0.1', 7496, clientId=1)
  57. news_providers = ib.reqNewsProviders()
  58. codes = '+'.join(news_provider.code for news_provider in news_providers)
  59. # get list of etfs (top 10)
  60. etfs_symbols = ["SPY", "IVV", "VOO", "VTI", "QQQ", "VEA", "VTV", "IEFA", "BND", "VUG"]
  61. # get data for symbols:
  62. for i in symbols[:5]:
  63. trans = connection.begin_nested()
  64. try:
  65. # get stock info
  66. try:
  67. ticker = yf.Ticker(i)
  68. info = ticker.info
  69. stock_values = {
  70. "symbol": i,
  71. 'name': info.get('shortName', 'NA'),
  72. 'sector': info.get('sector', 'NA'),
  73. 'industry': info.get('industry', 'NA'),
  74. 'live_price': info.get('regularMarketPrice', 0.0),
  75. 'prev_close': info.get('previousClose', 0.0),
  76. 'open': info.get('open', 0.0),
  77. 'volume': info.get('volume', 0)
  78. }
  79. # Insert the stock into the database
  80. query_stock = db.insert(stocks)
  81. ResultProxy = connection.execute(query_stock, [stock_values])
  82. # Error handling for stock info fetching
  83. except requests.exceptions.HTTPError as error_terminal:
  84. print("HTTPError while fetching stock info for symbol:", i)
  85. except Exception as e: # General exception catch
  86. print("Unexpected error while fetching stock info for symbol:", i)
  87. # Fetch and store news articles
  88. try:
  89. stock = Stock(i, 'SMART', 'USD')
  90. ib.qualifyContracts(stock)
  91. headlines = ib.reqHistoricalNews(stock.conId, codes, '', '', 100)
  92. for headline in headlines:
  93. article_date = headline.time.date()
  94. article = ib.reqNewsArticle(headline.providerCode, headline.articleId)
  95. # Insert the article into the database
  96. news_info = {
  97. 'symbol': i,
  98. 'title': '', # Title not needed
  99. 'news_date': str(article_date),
  100. 'url': '', # URL not provided
  101. 'source': '', # Source not provided
  102. 'text': article.articleText
  103. }
  104. # Insert the news into the database
  105. query_news = db.insert(news)
  106. ResultProxy = connection.execute(query_news, [news_info])
  107. # Error handling for news fetching
  108. except requests.exceptions.HTTPError as error_terminal:
  109. print("HTTPError while fetching news for symbol:", i)
  110. except Exception as e: # General exception catch
  111. print("Unexpected error while fetching news for symbol:", i)
  112. trans.commit()
  113. time.sleep(1)
  114. # Error handling
  115. except Exception as e: # General exception catch
  116. print("Unexpected error:", e)
  117. trans.rollback()
  118. # get data for etf symbols
  119. for i in etfs_symbols:
  120. trans = connection.begin_nested()
  121. try:
  122. try:
  123. #get etf info
  124. ticker = yf.Ticker(i)
  125. info = ticker.info()
  126. etf_values = {
  127. "symbol": i,
  128. 'name': info.get('shortName', 'NA'),
  129. 'sector': info.get('sector', 'NA'),
  130. 'industry': info.get('industry', 'NA'),
  131. 'live_price': info.get('regularMarketPrice', 0.0),
  132. 'prev_close': info.get('previousClose', 0.0),
  133. 'open': info.get('open', 0.0),
  134. 'volume': info.get('volume', 0)
  135. }
  136. # Insert etfs into the database:
  137. query_etf = db.insert(etfs)
  138. ResultProxy = connection.execute(query_etf, [etf_values])
  139. # Error handling for ETF info fetching:
  140. except requests.exceptions.HTTPError as error_terminal:
  141. print("HTTPError while fetching stock info for symbol:", i)
  142. except Exception as e: # General exception catch
  143. print("Unexpected error while fetching stock info for symbol:", i)
  144. trans.commit()
  145. time.sleep(1)
  146. # Error handling:
  147. except Exception as e: # General exception catch
  148. print("Unexpected error:", e)
  149. trans.rollback()
  150. # Fetch and print the first 5 stocks from the database after processing
  151. #query = db.select([data]).limit(5)
  152. query = stocks.select().limit(5)
  153. ResultProxy = connection.execute(query)
  154. ResultSet = ResultProxy.fetchall()
  155. for result in ResultSet:
  156. print(result)
  157. connection.execute(text("PRAGMA journal_mode=WAL"))
  158. # Close the connection
  159. connection.close()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...