Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wiseplat
GitHub Repository: wiseplat/python-code
Path: blob/master/ invest-robot-contest_tinvest_robot-master/tinvest_robot_perevalov/_db.py
5932 views
1
"""This is the internal module for working with the database.
2
"""
3
4
import sqlite3
5
import os
6
7
import logging
8
9
logging.basicConfig(
10
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
11
)
12
13
logger = logging.getLogger(__name__)
14
15
_DB_NAME = os.getenv("TINVEST_DB_NAME") or '../data/tinvest-perevalov.sqlite'
16
17
def init_db():
18
"""Initializes database if not exists.
19
"""
20
try:
21
conn = sqlite3.connect(_DB_NAME)
22
c = conn.cursor()
23
# Create table for news
24
c.execute('''
25
CREATE TABLE IF NOT EXISTS news
26
([news_id] INTEGER PRIMARY KEY AUTOINCREMENT, [news_text] TEXT, [news_sentiment] TEXT, [is_checked] BOOLEAN NOT NULL)
27
''')
28
# Create table for orders
29
c.execute('''
30
CREATE TABLE IF NOT EXISTS orders
31
([id] INTEGER PRIMARY KEY AUTOINCREMENT, [figi] TEXT, [quantity] INTEGER, [price] REAL, [direction] INTEGER, [account_id] TEXT, [order_type] INTEGER, [order_id] TEXT, [order_date] DATETIME, [news_id] INTEGER)
32
''')
33
except Exception as e:
34
logger.error(str(e))
35
finally:
36
c.close()
37
conn.commit()
38
conn.close()
39
40
41
def check_if_exists(news_text: str) -> bool:
42
"""Checks if news with given text already exists in database.
43
Args:
44
news_text (str): Headline of the news
45
46
Returns:
47
bool: Flag if news with given text already exists in database.
48
"""
49
try:
50
conn = sqlite3.connect(_DB_NAME)
51
c = conn.cursor()
52
53
c.execute(f'''
54
SELECT news_id
55
FROM news
56
WHERE news_text LIKE "{news_text}"
57
''')
58
59
data = c.fetchall()
60
61
if len(data) > 0:
62
return True
63
except Exception as e:
64
logger.error(str(e))
65
finally:
66
c.close()
67
conn.commit()
68
conn.close()
69
70
return False
71
72
73
def put_in_db(news_text: str, sentiment: str):
74
try:
75
conn = sqlite3.connect(_DB_NAME)
76
c = conn.cursor()
77
78
c.execute(f'''
79
INSERT INTO news (news_text, news_sentiment, is_checked)
80
VALUES ("{news_text}", "{sentiment}", 0)
81
''')
82
except Exception as e:
83
logger.error(str(e))
84
finally:
85
c.close()
86
conn.commit()
87
conn.close()
88
89
def put_order_in_db(figi: str, quantity: int, price: float, direction: int, account_id: str, order_type: int, order_id: str, news_id: int):
90
try:
91
conn = sqlite3.connect(_DB_NAME)
92
c = conn.cursor()
93
94
c.execute(f'''
95
INSERT INTO orders (figi, quantity, price, direction, account_id, order_type, order_id, order_date, news_id)
96
VALUES ("{figi}", {quantity}, {price}, {direction}, "{account_id}", {order_type}, "{order_id}", datetime('now'), {news_id})
97
''')
98
except Exception as e:
99
logger.error(str(e))
100
finally:
101
c.close()
102
conn.commit()
103
conn.close()
104
105
def update_is_checked(news_id: int):
106
"""Updates is_checked flag to 1 for news with given id.
107
108
Args:
109
news_id (int): News id to update.
110
"""
111
try:
112
conn = sqlite3.connect(_DB_NAME)
113
c = conn.cursor()
114
115
c.execute(f'''
116
UPDATE news
117
SET is_checked = 1
118
WHERE news_id = {news_id}
119
''')
120
except Exception as e:
121
logger.error(str(e))
122
finally:
123
c.close()
124
conn.commit()
125
conn.close()
126
127
def select_not_checked() -> list:
128
"""Selects news that are not checked yet.
129
130
Returns:
131
list: a list of news that are not checked yet.
132
"""
133
try:
134
conn = sqlite3.connect(_DB_NAME)
135
c = conn.cursor()
136
137
c.execute(f'''
138
SELECT news_id, news_text, news_sentiment
139
FROM news
140
WHERE is_checked = 0
141
''')
142
143
data = [{'news_id': d[0], 'title': d[1], 'sentiment': d[2]} for d in c.fetchall()]
144
145
return data
146
except Exception as e:
147
logger.error(str(e))
148
finally:
149
c.close()
150
conn.commit()
151
conn.close()
152
153
return []
154