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

portfolio_generation.py 7.5 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
  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. # importing module
  10. import time
  11. import openai
  12. import pandas as pd
  13. def create_db():
  14. # create database:
  15. engine = db.create_engine('sqlite:///atradebot.db', echo=True)
  16. connection = engine.connect()
  17. metadata = db.MetaData()
  18. # create a single table:
  19. stocks = db.Table('stocks', metadata,
  20. db.Column('id', db.Integer(), primary_key=True),
  21. db.Column('symbol', db.String(255), nullable=True),
  22. db.Column('name', db.String(255), nullable=True),
  23. db.Column('sector', db.String(255), nullable=True),
  24. db.Column('industry', db.String(255), nullable=True),
  25. db.Column('live_price', db.Float(), nullable=True),
  26. db.Column('prev_close', db.Float(), nullable=True),
  27. db.Column('open', db.Float(), nullable=True),
  28. db.Column("volume", db.Integer(), nullable=True),
  29. )
  30. news = db.Table('news', metadata,
  31. db.Column('id', db.Integer(), primary_key=True),
  32. db.Column('symbol', db.String(255), nullable=True),
  33. db.Column('title', db.String(255), nullable=True),
  34. db.Column('news_date', db.String(255), nullable=True),
  35. db.Column('url', db.String(255), nullable=True),
  36. db.Column('source', db.String(255), nullable=True),
  37. db.Column('text', db.String(255), nullable=True),
  38. )
  39. # create table in database:
  40. metadata.create_all(engine)
  41. return engine, connection, stocks, news
  42. if __name__ == "__main__":
  43. engine, connection, stocks, news = create_db()
  44. connection.execute(text("PRAGMA journal_mode=WAL"))
  45. # get list of stocks:
  46. stock_df = pd.read_excel('src/atradebot/SP_500_Companies.xlsx')
  47. symbols = stock_df['Symbol'].tolist()
  48. ib = IB()
  49. ib.connect('127.0.0.1', 7496, clientId=1)
  50. news_providers = ib.reqNewsProviders()
  51. codes = '+'.join(news_provider.code for news_provider in news_providers)
  52. # get data for symbols:
  53. for i in symbols[:5]:
  54. trans = connection.begin_nested()
  55. try:
  56. # get stock info
  57. try:
  58. ticker = yf.Ticker(i)
  59. info = ticker.info
  60. stock_values = {
  61. "symbol": i,
  62. 'name': info.get('shortName', 'NA'),
  63. 'sector': info.get('sector', 'NA'),
  64. 'industry': info.get('industry', 'NA'),
  65. 'live_price': info.get('regularMarketPrice', 0.0),
  66. 'prev_close': info.get('previousClose', 0.0),
  67. 'open': info.get('open', 0.0),
  68. 'volume': info.get('volume', 0)
  69. }
  70. # Insert the stock into the database
  71. query_stock = db.insert(stocks)
  72. ResultProxy = connection.execute(query_stock, [stock_values])
  73. # Error handling for stock info fetching
  74. except requests.exceptions.HTTPError as error_terminal:
  75. print("HTTPError while fetching stock info for symbol:", i)
  76. except Exception as e: # General exception catch
  77. print("Unexpected error while fetching stock info for symbol:", i)
  78. # Fetch and store news articles
  79. try:
  80. stock = Stock(i, 'SMART', 'USD')
  81. ib.qualifyContracts(stock)
  82. headlines = ib.reqHistoricalNews(stock.conId, codes, '', '', 100)
  83. for headline in headlines:
  84. article_date = headline.time.date()
  85. article = ib.reqNewsArticle(headline.providerCode, headline.articleId)
  86. # Insert the article into the database
  87. news_info = {
  88. 'symbol': i,
  89. 'title': '', # Title not needed
  90. 'news_date': str(article_date),
  91. 'url': '', # URL not provided
  92. 'source': '', # Source not provided
  93. 'text': article.articleText
  94. }
  95. # Insert the news into the database
  96. query_news = db.insert(news)
  97. ResultProxy = connection.execute(query_news, [news_info])
  98. # Error handling for news fetching
  99. except requests.exceptions.HTTPError as error_terminal:
  100. print("HTTPError while fetching news for symbol:", i)
  101. except Exception as e: # General exception catch
  102. print("Unexpected error while fetching news for symbol:", i)
  103. trans.commit()
  104. time.sleep(1)
  105. # Error handling
  106. except Exception as e: # General exception catch
  107. print("Unexpected error:", e)
  108. trans.rollback()
  109. # Fetch and print the first 5 stocks from the database after processing
  110. #query = db.select([data]).limit(5)
  111. query = news.select().limit(5)
  112. ResultProxy = connection.execute(query)
  113. ResultSet = ResultProxy.fetchall()
  114. i = 0
  115. for result in ResultSet:
  116. print(f"\n {i}")
  117. print(result)
  118. i = i+1
  119. connection.execute(text("PRAGMA journal_mode=WAL"))
  120. # Close the connection
  121. connection.close()
  122. openai.api_key = 'sk-'
  123. def user_req():
  124. num_stocks = 3
  125. return num_stocks
  126. stock_df = pd.read_excel('src/atradebot/SP_500_Companies.xlsx')
  127. symbols = stock_df['Symbol'].tolist()
  128. stock_df['sentiment_counter'] = 0
  129. i = 0
  130. for result in ResultSet:
  131. print(result[1])
  132. print(result[5])
  133. print(type(result[1]))
  134. print(type(result[5]))
  135. text_to_analyze = result[2] + ' ' + result[6]
  136. messages = [
  137. {"role": "user", "content": f"Analyze the sentiment of the following text and provide a one-word sentiment: '{text_to_analyze}'. The answer should just be 1 word."}
  138. ]
  139. response = openai.ChatCompletion.create(
  140. model="gpt-3.5-turbo",
  141. messages=messages
  142. )
  143. # Extract the response content
  144. sentiment = response['choices'][0]['message']['content']
  145. sentiment = sentiment.lower()
  146. print(sentiment)
  147. if (sentiment == "positive"):
  148. sentiment_num = 1
  149. elif (sentiment == "negative"):
  150. sentiment_num = -1
  151. elif (sentiment == "neutral"):
  152. sentiment_num = 0
  153. else:
  154. sentiment_num = 0
  155. sent_count_index_x = symbols.index(result[1])
  156. stock_df.at[sent_count_index_x, 'sentiment_counter'] += sentiment_num
  157. i = i + 1
  158. if ( i >= 3):
  159. # adding 2 seconds time delay
  160. time.sleep(60)
  161. i = 0
  162. num_stocks = user_req()
  163. largest_values = stock_df['sentiment_counter'].nlargest(num_stocks)
  164. print(stock_df)
  165. # Convert to a DataFrame with index numbers and values
  166. result_df = pd.DataFrame({
  167. 'Index': largest_values.index,
  168. 'Value': largest_values.values
  169. })
  170. for i in list(result_df['Index']):
  171. print("Stock Name:", stock_df.loc[i, 'Symbol'])
Tip!

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

Comments

Loading...