Exemple #1
0
    def get_fund_mess(self,
                      financials,
                      curr_price,
                      earnings,
                      sentiment,
                      days_to_earnings,
                      day_stocks=None):
        mess = ""
        mess += ''.join("Detail | ")
        financials.sort_values(by=["date"], inplace=True, ascending=True)
        if len(financials) > 0:
            cols = [
                "date", "shortRatio", "sharesShortPriorMonth",
                "fiftyDayAverage", "beta", "dividendRate", "exDividendDate",
                "priceToSalesTrailing12Months", "enterpriseToRevenue",
                "profitMargins", "enterpriseToEbitda", "trailingEps",
                "forwardEps", "priceToBook", "bookValue", "pegRatio",
                "earningsQuarterlyGrowth", "bid", "volume", "trailingPE",
                "forwardPE", "heldPercentInstitutions", "heldPercentInsiders"
            ]

            mess += ''.join([
                "T_EPS->F_EPS: ",
                str(
                    Utils.calc_perc(financials.iloc[0].trailingEps,
                                    financials.iloc[0].forwardEps)), "%\n\r",
                "T_PE->F_PE: ",
                str(
                    Utils.calc_perc(financials.iloc[0].trailingPE,
                                    financials.iloc[0].forwardPE)) + "%\n\r"
            ])

            for item in cols:

                # financials[item].dropna(inplace=True)

                first = financials.iloc[0][item]
                last = financials.iloc[-1][item]

                mess += ''.join([
                    item + ": ",
                    str(Utils.human_format(first)),
                    " -> ",
                    str(Utils.human_format(last)),
                    " | ",
                    str(Utils.calc_perc(first, last)),
                    "%\n\r",
                ])

            mess += ''.join([
                str(financials.iloc[0].sector), ' | ',
                str(financials.iloc[0].industry), "\n\r",
                str("Current Price: "), ' | ',
                str(curr_price), "\n\r",
                str("Days to earn.: "), ' | ',
                str(days_to_earnings), " D", "\n\r"
            ])

        if earnings is not None and len(earnings) > 0:
            mess += str("Earn. est. | act. | surp.:  ") + str(earnings.iloc[-1].epsestimate) + \
                ' | ' + str(earnings.iloc[-1].epsactual) + \
                ' | ' + str(earnings.iloc[-1].epssurprisepct) + "\n\r"
        if sentiment is not None and len(sentiment) > 0:
            mess += str("Sentiment article/title: ") + str(sentiment.sentiment_summary_avg.to_list()) + \
                '/' + str(sentiment.sentiment_title_avg.to_list()) if sentiment is not None and len(sentiment)>0 else str("Sentiment: NaN ") + "\n\r"
        if financials is not None and len(financials) > 0:
            mess += str(financials.iloc[0].longBusinessSummary) + "\n\r"

        sector_mess, spy_mess, vol_mess = self.get_common_mess(self.stocks)
        mess += "\n\r" + sector_mess
        mess += "\n\r" + spy_mess
        mess += "\n\r" + vol_mess

        hl = FinI.get_fib_hl(self.stocks, curr_price)
        mess += "\n\r" + "Loss: " + str(Utils.calc_perc(curr_price, hl["l"])) + "% " + "  " + str(hl['l']) +" | "+\
            " Price: " + str(curr_price) + \
            " | " + "Profit: " + str(hl['h']) + \
            "  " + str(Utils.calc_perc(curr_price, hl["h"])) + "% \n\r"

        mess += self.get_fib_mess(self.stocks, curr_price) + "\n\r"
        print("get_fund_mess() - done")
        return mess
Exemple #2
0
    def buy_sell(self, stocks_day, stocks_15, spy, spy_row15, spy_row_day):
        """ By sell backtrading simaltion with specific strategy

        Args:
            stocks_day ([type]): [description]
            stocks_15 ([type]): [description]
            spy ([type]): [description]
            spy_row15 ([type]): [description]
            spy_row_day ([type]): [description]
        """

        # self.stocks = self.stocks.append(stocks_day.iloc[-1])
        self.db.last_date = stocks_15.iloc[-1].name
        logging.info(self.db.last_date)
        sym = stocks_day.iloc[-1].sym
        # send only one buy suggestion per day
        hash_warn = hash(sym + str(stocks_15.index[-1].strftime("%d/%m/%Y")))

        hl = FinI.get_fib_hl(stocks_day, stocks_day.iloc[-1].close)

        # logging.info(str(stocks_day))
        if len(stocks_day) > 1:
            # stocks_day = sdf.retype(stocks_day)
            # stocks_day = FinI.add_indicators(stocks_day)
            stocks_day.sort_index(ascending=True, inplace=True)
            stocks_day["flpd"] = Utils.calc_flpd(stocks_day)
            hl = FinI.get_fib_hl(stocks_day, stocks_15.iloc[-1].close)
            #OLD CHECK SELL moved to this Fce
            # self.check_sell(stocks_15.iloc[-1])

            earnings, sentiment, financials = self.db.get_fundamentals(
                stocks_day.iloc[-1]["sym"])
            self.set_mess_data(fin=financials,
                               sen=sentiment,
                               earn=earnings,
                               spy=spy,
                               stc=stocks_day)

            # st.write("BUYSELL OPEN trades amount:" + str(len(self.bs.buy_sell_open)))
            #-----------------------------SELL------------------------------------------
            if len(self.bs.buy_sell_open) > 0:

                logging.info("not selled stocks:" + str(self.bs.buy_sell_open[
                    self.bs.buy_sell_open.state == "open"]))
                logging.info("Current SYM: " + str(stocks_15.iloc[-1].sym))

                bs = self.bs.buy_sell_open[self.bs.buy_sell_open.sym ==
                                           stocks_15.iloc[-1].sym]

                if len(bs) > 0:
                    st.write(
                        "--------------------SELLING----------------------------"
                    )
                    for index, row in bs.iterrows():
                        if Utils.calc_perc(stocks_15.iloc[-1].close, hl["h"], 2) <= 1 or \
                                chi.check_sma9(stocks=stocks_day, live_stocks=stocks_15, buy=False):

                            # self.bs.buy_sell_open[(self.bs.buy_sell_open.sym == stocks_15.iloc[-1].sym) & (self.bs.buy_sell_open.state == "open")] = self.bs.sell_stock_t(stocks_15.iloc[-1],  sell_price=stocks_15.iloc[-1].close,
                            sold_stock = self.bs.sell_stock_t(
                                sym=stocks_15.iloc[-1].sym,
                                price=stocks_15.iloc[-1].close,
                                sell_date=stocks_15.iloc[-1].name)
                            st.write(sold_stock)
                            # st.write(sym + " | Selling Profit: " + str(stocks_15.iloc[-1].sym) + " | " + str(stocks_15.index[-1]) + " | " +
                            #                                      " | B.S.:" + str(row["buy"]) + "/" + str(stocks_15.iloc[-1].close) +
                            #                                      " | " + str(Utils.calc_perc(row["buy"], stocks_15.iloc[-1].close)) +
                            #                                      "% | " + str(stocks_15.iloc[-1].name) +
                            #                                      " | ", stocks_15.iloc[-1].name)

                            # asyncio.run(self.sm.a_mail_sym_stats(sym, "Selling Profit: " + str(stocks_15.iloc[-1].sym) + " | " + str(stocks_15.index[-1]) + " | " +
                            #                                      " | B.S.:" + str(row["buy"]) + "/" + str(stocks_15.iloc[-1].close) +
                            #                                      " | " + str(Utils.calc_perc(row["buy"], stocks_15.iloc[-1].close)) +
                            #                                      "% | " + str(stocks_15.iloc[-1].name) +
                            #                                      " | ", stocks_15.iloc[-1].name), debug=True)

            #------------------------------------------------------------BUY---------------------------------------------
            if hash_warn not in self.warning_check_list \
                    and stocks_day.iloc[-1]["flpd"] > 0 \
                    and chi.check_financials(financials) \
                    and (len(self.bs.buy_sell_open) == 0 or stocks_15.iloc[-1].sym not in self.bs.buy_sell_open[self.bs.buy_sell_open.state == "open"].sym)  \
                    and chi.check_pre_sma9(stocks_day, live_stocks=stocks_15):

                # and chi.check_sentiment(sentiment) \
                # and chi.check_financials(financials) \

                self.warning_check_list.append(hash_warn)
                self.bs.buy_stock_t(stocks_15.iloc[-1],
                                    stocks_15.iloc[-1].close,
                                    table_name="buy_sell_lt",
                                    profit_loss={
                                        "profit": hl["h"],
                                        "loss": hl["l"]
                                    })

                st.write(
                    "---------------------------BUYiNG-------------------------------"
                )
                # logging.info(self.bs.buy_sell)

                st.write(
                    sym + " | Buy: " + str(stocks_15.iloc[-1].sym) + " | " +
                    str(stocks_15.index[-1]) + " | " +
                    str(stocks_15.iloc[-1].close) + " | " + str(hl),
                    stocks_15.iloc[-1].name)