Path: blob/master/ invest-robot-contest_tinvest_robot-master/tinvest_robot_perevalov/_db.py
5932 views
"""This is the internal module for working with the database.1"""23import sqlite34import os56import logging78logging.basicConfig(9format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO10)1112logger = logging.getLogger(__name__)1314_DB_NAME = os.getenv("TINVEST_DB_NAME") or '../data/tinvest-perevalov.sqlite'1516def init_db():17"""Initializes database if not exists.18"""19try:20conn = sqlite3.connect(_DB_NAME)21c = conn.cursor()22# Create table for news23c.execute('''24CREATE TABLE IF NOT EXISTS news25([news_id] INTEGER PRIMARY KEY AUTOINCREMENT, [news_text] TEXT, [news_sentiment] TEXT, [is_checked] BOOLEAN NOT NULL)26''')27# Create table for orders28c.execute('''29CREATE TABLE IF NOT EXISTS orders30([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)31''')32except Exception as e:33logger.error(str(e))34finally:35c.close()36conn.commit()37conn.close()383940def check_if_exists(news_text: str) -> bool:41"""Checks if news with given text already exists in database.42Args:43news_text (str): Headline of the news4445Returns:46bool: Flag if news with given text already exists in database.47"""48try:49conn = sqlite3.connect(_DB_NAME)50c = conn.cursor()5152c.execute(f'''53SELECT news_id54FROM news55WHERE news_text LIKE "{news_text}"56''')5758data = c.fetchall()5960if len(data) > 0:61return True62except Exception as e:63logger.error(str(e))64finally:65c.close()66conn.commit()67conn.close()6869return False707172def put_in_db(news_text: str, sentiment: str):73try:74conn = sqlite3.connect(_DB_NAME)75c = conn.cursor()7677c.execute(f'''78INSERT INTO news (news_text, news_sentiment, is_checked)79VALUES ("{news_text}", "{sentiment}", 0)80''')81except Exception as e:82logger.error(str(e))83finally:84c.close()85conn.commit()86conn.close()8788def put_order_in_db(figi: str, quantity: int, price: float, direction: int, account_id: str, order_type: int, order_id: str, news_id: int):89try:90conn = sqlite3.connect(_DB_NAME)91c = conn.cursor()9293c.execute(f'''94INSERT INTO orders (figi, quantity, price, direction, account_id, order_type, order_id, order_date, news_id)95VALUES ("{figi}", {quantity}, {price}, {direction}, "{account_id}", {order_type}, "{order_id}", datetime('now'), {news_id})96''')97except Exception as e:98logger.error(str(e))99finally:100c.close()101conn.commit()102conn.close()103104def update_is_checked(news_id: int):105"""Updates is_checked flag to 1 for news with given id.106107Args:108news_id (int): News id to update.109"""110try:111conn = sqlite3.connect(_DB_NAME)112c = conn.cursor()113114c.execute(f'''115UPDATE news116SET is_checked = 1117WHERE news_id = {news_id}118''')119except Exception as e:120logger.error(str(e))121finally:122c.close()123conn.commit()124conn.close()125126def select_not_checked() -> list:127"""Selects news that are not checked yet.128129Returns:130list: a list of news that are not checked yet.131"""132try:133conn = sqlite3.connect(_DB_NAME)134c = conn.cursor()135136c.execute(f'''137SELECT news_id, news_text, news_sentiment138FROM news139WHERE is_checked = 0140''')141142data = [{'news_id': d[0], 'title': d[1], 'sentiment': d[2]} for d in c.fetchall()]143144return data145except Exception as e:146logger.error(str(e))147finally:148c.close()149conn.commit()150conn.close()151152return []153154