Esempio n. 1
0
def QuarterlyCheck(stock_datas=None):
    """ 15 minute check during trading hours to make sure stock price has not hit target """
    stockDB = StockDB()
    msgrecordDB = MsgRecordDB()
    stocklist = stockDB.stockList()
    stock_ids = [stock_id for stock_id, _, _ in stocklist]
    if not stock_datas:
        stock_datas = checkStocksThreaded(stock_ids)
    for stock_id, stock_trigger, trigger_type in stocklist:
        stock_data = stock_datas[stock_id]
        last_time = msgrecordDB.getMsgRecord(stock_id, trigger_type)
        if last_time: date = last_time[2]
        message = None
        if last_time:
            if trigger_type == 'sell' and stock_data[0] <= float(
                    stock_trigger):
                message = f"{stock_id} has gone below your trigger amount of ${stock_trigger} after going above at {date}.\nCurrent Price: ${stock_data[0]}\nPercentage = {'' if stock_data[1] < 0 else '+'}{stock_data[1]}%"
            if trigger_type == 'buy' and stock_data[0] >= float(stock_trigger):
                message = f"{stock_id} has gone above your trigger amount of ${stock_trigger} after going below at {date}.\nCurrent Price: ${stock_data[0]}\nPercentage = {'' if stock_data[1] < 0 else '+'}{stock_data[1]}%"
        else:
            if trigger_type == 'sell' and stock_data[0] >= float(
                    stock_trigger):
                message = f"{stock_id} has gone above your trigger amount of ${stock_trigger}.\nCurrent Price: ${stock_data[0]}\nPercentage = {'' if stock_data[1] < 0 else '+'}{stock_data[1]}%"
            if trigger_type == 'buy' and stock_data[0] <= float(stock_trigger):
                message = f"{stock_id} has gone below your trigger amount of ${stock_trigger}.\nCurrent Price: ${stock_data[0]}\nPercentage = {'' if stock_data[1] < 0 else '+'}{stock_data[1]}%"
        if message and last_time:
            sendMessage(message)
            msgrecordDB.removeMsgRecord(stock_id, trigger_type)
        if message and not last_time:
            sendMessage(message)
            msgrecordDB.addMsgRecord(stock_id, trigger_type)
    # stock_datas_n = {stock_id: details[0] for stock_id, details in stock_datas.items()}
    # pfdb = PortfolioDB()
    # pf = pfdb.getPortfolio(stock_datas_n)
    logging.info("Performed quarterly stock price check")
Esempio n. 2
0
def mbsetWebhook(url):
    """ Sets telegram webhook """
    s = mbot.setWebhook('{URL}/{HOOK}'.format(URL=url, HOOK=mbtoken))
    if s:
        logging.info("Movie Bot Webhook succesfully set up!")
    else:
        logging.error("Movie Bot Webhook setup failed.")
Esempio n. 3
0
def tradingMode():
    stockDB = StockDB()
    pfdb = PortfolioDB()
    stock_ids = list(set(pfdb.CurrentStocks() + [stock[0] for stock in stockDB.stockList()]))
    stock_data = checkStocksThreaded(stock_ids)
    QuarterlyCheck(stock_data)
    message = "Stocks Report:\n\nStock ID - Stock Price - Increase/Decrease %"
    for stock_id, stock_info in sorted(stock_data.items()):
        line = f"\n{stock_id} : ${stock_info[0]} , {'' if stock_info[1] < 0 else '+'}{stock_info[1]}%"
        message += line
    sendMessage(message)
    logging.info("Trading mode check performed succesfully")
Esempio n. 4
0
def stocknews():
    start = time.time()
    news = ''
    link = 'https://www.cnbc.com/id/100003114/device/rss/rss.html'  # Change
    req = requests.get(link)
    soup = BeautifulSoup(req.text, 'lxml')
    items = soup.find_all('item')
    for item in items:
        title = item.find('title').text
        news += f"{title} | "
    end = time.time()
    logging.info(f"Updated news in {round(end-start, 2)} seconds")
    return news
Esempio n. 5
0
def predictionsCheck():
    from actions import sendMessage
    stockDB = StockDB()
    pfdb = PortfolioDB()
    predictionrecordDB = PredictionRecordDB()
    predictions = getPredictions()
    stocks = list(
        set(pfdb.CurrentStocks() +
            [stock[0].upper() for stock in stockDB.stockList()]))
    for result in predictions.values:
        ticker = result[1]
        if ticker.upper() in stocks:
            prev_alert = predictionrecordDB.getPredictionRecord(*result)
            if not prev_alert:
                message = f"Prediction for {result[0]} ({result[1]}):\nFirm: {result[2]}\nRatings Change: {result[3]}\nPrice Target: {result[4]}"
                sendMessage(message)
                predictionrecordDB.addPredictionRecord(*result)
    logging.info("Predictions check ran succesfully")
Esempio n. 6
0
def moviebot_respond():
    """ Parses telegram update """
    os.chdir(os.path.expanduser("~"))
    try:
        request_json = request.get_json(force=True)
        logging.debug(request_json)
        update = telegram.Update.de_json(request_json, bot)
        chat_id = update.effective_chat.id
        if str(chat_id) not in ['855910557', '1207015683']:
            logging.warning(f"Unknown chat id: {chat_id}")
            return 'no'
        try:
            text = update.effective_message.text.encode('utf-8').decode()
            logging.info(f"MOVIEBOT: Recieved message {text}")
        except:
            logging.info("MOVIEBOT: Recieved message")
        apy.dispatcher.process_update(update)
    except Exception as e:
        exc_type, exc_value, exc_tb = sys.exc_info()
        handle_unhandled_exception(exc_type, exc_value, exc_tb)
    return 'ok'
Esempio n. 7
0
def respond():
    """ Parses telegram update """
    os.chdir(cwd)
    try:
        request_json = request.get_json(force=True)
        logging.debug(request_json)
        update = telegram.Update.de_json(request_json, bot)
        chat_id = update.effective_chat.id
        if str(chat_id) not in ['855910557', '1207015683', '-1001157094088']:
            logging.warning(f"Unknown chat id: {chat_id}")
            return 'no'
        try:
            text = update.effective_message.text.encode('utf-8').decode()
            logging.info(f"Recieved message {text}")
        except:
            pass
            logging.info(f"Recieved message")
        newMessage(text)
    except Exception as e:
        exc_type, exc_value, exc_tb = sys.exc_info()
        handle_unhandled_exception(exc_type, exc_value, exc_tb)
    return 'ok'
Esempio n. 8
0
def stockdata():
    start = time.time()
    indexes = ['^DJI', '^IXIC', '^GSPC']
    index_names = ['Dow Jones', 'Nasdaq', 'S&P 500']
    index_data = checkStocksThreaded(indexes).values()
    index_datas = {
        index_name: [int(index_data[0]), index_data[1]]
        for index_name, index_data in zip(index_names, index_data)
    }
    stockDB = StockDB()
    pfdb = PortfolioDB()
    stock_list = list(
        set(pfdb.CurrentStocks() + [stock[0]
                                    for stock in stockDB.stockList()]))
    stock_data = checkStocksThreaded(stock_list)
    updated_time = time.strftime("%H:%M:%S")
    end = time.time()
    logging.info(f"Updated dashboard data in {round(end-start, 2)} seconds")
    return render_template('stock_table.html',
                           stock_data=stock_data,
                           updated_time=updated_time,
                           index_datas=index_datas)
Esempio n. 9
0
            self.addNews(stock_id, news2)
        # news = self.getImportant(stock_id, stock_name, news + news2) # Comment out to send all news
        try:
            return news + news2
        except:
            if len(stock_id) <=2:
                return news2
            else:
                return news

    def getNewNews(self, stock_ids: list) -> dict:
        news_dict = dict()
        for stock_id in stock_ids:
            news = self.getNews(stock_id)
            news_dict[stock_id] = news
        return news_dict


newsDB = NewsDB()
newstriggerDB = NewsTriggerDB()

if __name__ == "__main__":
    stockDB = StockDB()
    pfdb = PortfolioDB()
    stock_list = list(set(pfdb.CurrentStocks() + [stock[0] for stock in stockDB.stockList()]))
    news_dict = newsDB.getNewNews(stock_list)
    for stock_id, news in news_dict.items():
        for news_one in news:
            news_bot.sendMessage(chat_id=chat_id, text=newsDB.formatNews(stock_id, news_one))
    logging.info("Performed news check successfully")
Esempio n. 10
0
def index():
    # Cronjob turns off the dashboard everyday at 1 AM
    logging.info("Stock Dashboard session started")
    return render_template('index.html')
Esempio n. 11
0
    try:
        req = requests.get('http://127.0.0.1:4040/api/tunnels')
        soup = BeautifulSoup(req.text, 'lxml')
        tunnelsjson = json.loads(soup.find('p').text)
        url = tunnelsjson['tunnels'][0]['public_url'].replace(
            'http://', 'https://')
    except:
        os.system('ngrok http 4000 > /dev/null &')
        time.sleep(10)
        try:
            req = requests.get('http://127.0.0.1:4040/api/tunnels')
            soup = BeautifulSoup(req.text, 'lxml')
            tunnelsjson = json.loads(soup.find('p').text)
            url = tunnelsjson['tunnels'][0]['public_url'].replace(
                'http://', 'https://')
        except:
            logging.critical("Failure in obtaining ngrok url")
            exit()
    return url


url = ngrok()
logging.info(f"Ngrok url obtained - {url}")
setWebhook(url)
mbsetWebhook(url)
logging.info("Web app starting")
sendMessage("Stock Bot has restarted")

if __name__ == '__main__':
    app.run(port=4000, threaded=True)