Merge pull request #144 from WebEngineering2/bot

Working for all isins and new requirements
This commit is contained in:
Linus E 2022-05-08 10:44:02 +02:00 committed by GitHub
commit 10ef92693d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 122 additions and 28 deletions

View File

@ -41,10 +41,10 @@ print("Webserver Token: " + str(api_handler.token))
bot = telebot.TeleBot(os.getenv('BOT_API_KEY')) bot = telebot.TeleBot(os.getenv('BOT_API_KEY'))
@bot.message_handler(commands=['start', 'Start']) # /start -> saving as new user and sending welcome @bot.message_handler(commands=['start', 'Start'])
def send_start(message): def send_start(message):
""" Description """ Sending welcome message to new user
:type message: message object bot :type message: message object bot
:param message: message that was reacted to, in this case always containing '/start' :param message: message that was reacted to, in this case always containing '/start'
@ -52,7 +52,10 @@ def send_start(message):
:rtype: none :rtype: none
""" """
bot.reply_to(message, "Welcome to this share bot project. Type /help to get information on what this bot can do") bot.reply_to(message, "Welcome to this share bot project. \
\nType /help to get information on what this bot can do. \
\nAlso see https://gruppe1.testsites.info \
to start configuring your bot")
@bot.message_handler(commands=['version', 'Version']) @bot.message_handler(commands=['version', 'Version'])
@ -273,14 +276,12 @@ def send_share_update(message):
""" """
user_id = int(message.from_user.id) user_id = int(message.from_user.id)
#Get Information for user with this id bot.send_message(chat_id=user_id, text='Send Symbol/ISIN of share or name of company:')
bot.send_message(chat_id=user_id, text='Send symbol of share:')
#str_share_price = shares.wait_for_share.main_loop(bot)
bot.register_next_step_handler(message, send_share_price) bot.register_next_step_handler(message, send_share_price)
def send_share_price(message): def send_share_price(message):
str_share_price = share_fetcher.get_share_price(str(message.text)) str_share_price = share_fetcher.get_share_information(str(message.text))
bot.reply_to(message, str_share_price) # add dollar symbol etc. bot.reply_to(message, str_share_price)
@bot.message_handler(commands=['allnews', 'Allnews']) # /allnews -> get all news @bot.message_handler(commands=['allnews', 'Allnews']) # /allnews -> get all news
@ -465,13 +466,13 @@ def set_new_transaction(message):
:rtype: none :rtype: none
""" """
user_id = int(message.from_user.id) user_id = int(message.from_user.id)
bot.send_message(chat_id=user_id, text='Type "<name of stock>,<isin>,<amount>,<price_per_stock_usd>" (time of transaction will be set to now):') bot.send_message(chat_id=user_id, text='Type "<name of stock>,<isin/name/symbol>,<amount>,<price_per_stock_usd>" (time of transaction will be set to now, negative amount is selling, positive is buying):')
bot.register_next_step_handler(message, set_new_transaction_step) bot.register_next_step_handler(message, set_new_transaction_step)
def set_new_transaction_step(message): def set_new_transaction_step(message):
user_id = int(message.from_user.id) user_id = int(message.from_user.id)
if not re.match(r"[A-Za-z0-9]+,[A-Za-z0-9]+,[0-9]+(.[0-9]+)?,[0-9]+(.[0-9]+)?", message.text): if not re.match(r"[A-Za-z0-9]+,[A-Za-z0-9]+,(-)?[0-9]+(.[0-9]+)?,[0-9]+(.[0-9]+)?", message.text):
bot.send_message(chat_id=user_id, text='Invalid format \n(e.g. Apple,US0378331005,53.2,120.4).\n Try again with /newtransaction.') bot.send_message(chat_id=user_id, text='Invalid format \n(e.g. Apple,US0378331005,53.2,120.4).\n Try again with /newtransaction.')
return return

View File

@ -68,8 +68,13 @@ def update_crontab(p_my_handler):
for element in all_users: for element in all_users:
if element["cron"] != '' and element["telegram_user_id"] != '': if element["cron"] != '' and element["telegram_user_id"] != '':
user_ids.append(int(element["telegram_user_id"])) try:
user_crontab.append(str(element["cron"])) user_ids.append(int(element["telegram_user_id"]))
try:
user_crontab.append(str(element["cron"]))
except: continue
except: continue
print(user_ids) print(user_ids)

View File

@ -1,9 +1,11 @@
pyTelegramBotAPI~=4.5.0 pyTelegramBotAPI~=4.5.0
Markdown~=3.3.6 Markdown~=3.3.6
yfinance~=0.1.70
newsapi-python~=0.2.6 newsapi-python~=0.2.6
python-dotenv~=0.20.0 python-dotenv~=0.20.0
requests~=2.27.1 requests~=2.27.1
APScheduler~=3.9.1 APScheduler~=3.9.1
croniter~=1.3.4 croniter~=1.3.4
tzlocal==2.1 tzlocal==2.1
investpy~=1.0.8
pandas~=1.4.1
currencyconverter~=0.16.12

View File

@ -3,24 +3,110 @@ script for share fetching (by symbols (e.g. AAPL, TSLA etc.))
""" """
__author__ = "Florian Kellermann, Linus Eickhoff" __author__ = "Florian Kellermann, Linus Eickhoff"
__date__ = "15.03.2022" __date__ = "15.03.2022"
__version__ = "0.0.2" __version__ = "1.0.0"
__license__ = "None" __license__ = "None"
import yfinance import investpy
import pandas
from currency_converter import CurrencyConverter
def get_share_price(str_symbol): def get_share_price(str_search_for):
"""get stock price per share for company name or isin or symbol
""" get current share price for a certain symbol Args:
:type str_symbol: string str_search_for (string): search for this string/isin
:param str_symbol: share symbol to get price for
:raises: Returns: none
:rtype:
""" """
try:
search_result = investpy.search_quotes(text=str_search_for, products=['stocks'], n_results=1, countries=['germany'])
my_share_info = yfinance.Ticker(str_symbol) currency = str(search_result.retrieve_currency())
my_share_data = my_share_info.info
#my_return_string = f'{my_share_data["regularMarketPrice"]} {my_share_data["currency"]}' recent_data = pandas.DataFrame(search_result.retrieve_recent_data())
my_return_string = f'{my_share_data["regularMarketPrice"]}'
return my_return_string stock_price = recent_data.iloc[-1]["Close"]
stock_price = round(float(stock_price), 2)
str_return =str(stock_price) + " " + str(currency)
return str_return
except RuntimeError:
try:
my_Converter = CurrencyConverter()
search_result = investpy.search_quotes(text=str_search_for, products=['stocks'], n_results=1)
currency = str(search_result.retrieve_currency())
recent_data = pandas.DataFrame(search_result.retrieve_recent_data())
stock_price = recent_data.iloc[-1]["Close"]
stock_price = my_Converter.convert(float(stock_price), str(currency), 'EUR')
stock_price = round(float(stock_price), 2)
str_return =str(stock_price) + " EUR"
return str_return
except RuntimeError:
return "None"
def get_share_price_no_currency(str_search_for):
"""get stock price per share for company name or isin or symbol no currency
Args:
str_search_for (string): search for this string/isin
Returns: none
"""
try:
search_result = investpy.search_quotes(text=str_search_for, products=['stocks'],
countries=['germany'], n_results=1)
recent_data = pandas.DataFrame(search_result.retrieve_recent_data())
stock_price = recent_data.iloc[-1]["Close"]
stock_price = round(float(stock_price), 2)
return stock_price
except RuntimeError:
my_Converter = CurrencyConverter()
search_result = investpy.search_quotes(text=str_search_for, products=['stocks'], n_results=1)
currency = str(search_result.retrieve_currency())
recent_data = pandas.DataFrame(search_result.retrieve_recent_data())
stock_price = recent_data.iloc[-1]["Close"]
stock_price = my_Converter.convert(float(stock_price), str(currency), 'EUR')
stock_price = round(float(stock_price), 2)
str_return =str(stock_price)
return str_return
def get_share_information(str_search_for):
search_result = investpy.search_quotes(text=str_search_for, products=['stocks'],
countries=['germany'], n_results=1)
str_return = "Company: " + search_result.name + "\nSymbol: " + search_result.symbol + "\nCurrent Price/Share: " + get_share_price(str_search_for)
return str_return
if __name__ == "__main__":
print(get_share_price("US2515661054"))
print(get_share_price("DE0005557508"))
print(get_share_price_no_currency("US2515661054"))
print(get_share_price_no_currency("DE0005557508"))