Пример #1
0
 def test_load_clear(self):
     stocks_helper.load(["GME"], "GME", self.start, "1440min",
                        pd.DataFrame())
     values = stocks_helper.clear([], "GME", self.start, "1440min",
                                  pd.DataFrame())
     self.assertEqual(values[0], "")
     self.assertEqual(values[1], "")
     self.assertEqual(values[2], "")
def test_insider_activity(mocker, raw):
    mocker.patch.object(target=businessinsider_view.gtff,
                        attribute="USE_ION",
                        new=False)
    mocker.patch("matplotlib.pyplot.show")

    yf_download = stocks_helper.yf.download

    def mock_yf_download(*args, **kwargs):
        kwargs["threads"] = False
        return yf_download(*args, **kwargs)

    mocker.patch("yfinance.download", side_effect=mock_yf_download)

    ticker = "AAPL"
    stock = stocks_helper.load(ticker=ticker)
    businessinsider_view.insider_activity(
        stock=stock,
        ticker=ticker,
        start=None,
        interval="1440min",
        num=5,
        raw=raw,
        export="",
    )
Пример #3
0
def test_fails_to_deliver(mocker, raw):

    # MOCK VISUALIZE_OUTPUT
    mocker.patch(
        target="gamestonk_terminal.helper_classes.TerminalStyle.visualize_output"
    )

    mocker.patch(
        target="gamestonk_terminal.stocks.dark_pool_shorts.sec_model.get_fails_to_deliver",
        new=mocker.Mock(return_value=df_fails_to_deliver.copy()),
    )
    stock = stocks_helper.load(
        ticker="TSLA",
        start=datetime.strptime("2021-12-18", "%Y-%m-%d"),
    )

    sec_view.fails_to_deliver(
        ticker="PM",
        stock=stock,
        start=datetime.strptime("2021-12-18", "%Y-%m-%d"),
        end=datetime.strptime("2021-12-19", "%Y-%m-%d"),
        num=2,
        raw=raw,
        export="",
    )
def test_display_candle(mocker, use_matplotlib):
    mocker.patch.object(target=stocks_helper.gtff,
                        attribute="USE_ION",
                        new=False)
    mocker.patch("matplotlib.pyplot.show")
    mocker.patch("plotly.basedatatypes.BaseFigure.show")

    # LOAD DATA
    ticker = "GME"
    start = datetime.strptime("2020-12-01", "%Y-%m-%d")
    interval = 1440
    end = datetime.strptime("2020-12-08", "%Y-%m-%d")
    prepost = False
    source = "yf"
    df_stock = stocks_helper.load(
        ticker=ticker,
        start=start,
        interval=interval,
        end=end,
        prepost=prepost,
        source=source,
    )

    # PROCESS DATA
    df_stock = stocks_helper.process_candle(df_data=df_stock)

    # DISPLAY CANDLE
    s_ticker = "GME"
    intraday = False
    stocks_helper.display_candle(
        s_ticker=s_ticker,
        df_stock=df_stock,
        use_matplotlib=use_matplotlib,
        intraday=intraday,
    )
Пример #5
0
    def call_load(self, other_args: List[str]):
        """Process load command"""
        parser = argparse.ArgumentParser(
            add_help=False,
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
            prog="load",
            description=
            "Load stock ticker to perform analysis on. When the data source is 'yf', an Indian ticker can be"
            " loaded by using '.NS' at the end, e.g. 'SBIN.NS'. See available market in"
            " https://help.yahoo.com/kb/exchanges-data-providers-yahoo-finance-sln2310.html.",
        )
        parser.add_argument(
            "-t",
            "--ticker",
            action="store",
            dest="ticker",
            required="-h" not in other_args,
            help="Stock ticker",
        )
        if other_args and "-" not in other_args[0][0]:
            other_args.insert(0, "-t")
        ns_parser = parse_known_args_and_warn(parser, other_args)
        if ns_parser:
            df_stock_candidate = stocks_helper.load(ns_parser.ticker, )
            if not df_stock_candidate.empty:
                if "." in ns_parser.ticker:
                    self.ticker = ns_parser.ticker.upper().split(".")[0]
                else:
                    self.ticker = ns_parser.ticker.upper()

                self.stock = df_stock_candidate
                self.start = self.stock.index[0].strftime("%Y-%m-%d")
                self.interval = "1440min"
def test_insider_activity(mocker, raw):
    # MOCK VISUALIZE_OUTPUT
    mocker.patch(
        target="gamestonk_terminal.helper_classes.TerminalStyle.visualize_output"
    )

    yf_download = stocks_helper.yf.download

    def mock_yf_download(*args, **kwargs):
        kwargs["threads"] = False
        return yf_download(*args, **kwargs)

    mocker.patch("yfinance.download", side_effect=mock_yf_download)

    ticker = "AAPL"
    stock = stocks_helper.load(ticker=ticker)
    businessinsider_view.insider_activity(
        stock=stock,
        ticker=ticker,
        start=None,
        interval="1440min",
        num=5,
        raw=raw,
        export="",
    )
 def call_load(self, other_args: List[str]):
     """Process load command"""
     self.ticker, self.start, self.interval, self.stock = load(
         other_args, self.ticker, self.start, self.interval, self.stock)
     if "." in self.ticker:
         self.ticker, self.suffix = self.ticker.split(".")
     else:
         self.suffix = ""
def test_load(interval, recorder, source):
    ticker = "GME"
    start = datetime.strptime("2021-12-01", "%Y-%m-%d")
    end = datetime.strptime("2021-12-02", "%Y-%m-%d")
    prepost = False
    result_df = stocks_helper.load(
        ticker=ticker,
        start=start,
        interval=interval,
        end=end,
        prepost=prepost,
        source=source,
    )
    recorder.capture(result_df)
Пример #9
0
    def call_load(self, other_args: List[str]):
        """Process load command"""
        self.ticker, self.start, self.interval, stock = load(
            other_args, self.ticker, self.start, self.interval, self.stock)
        if "." in self.ticker:
            self.ticker = self.ticker.split(".")[0]

        if "-h" not in other_args:
            stock["Returns"] = stock["Adj Close"].pct_change()
            stock["LogRet"] = np.log(stock["Adj Close"]) - np.log(
                stock["Adj Close"].shift(1))
            stock = stock.rename(columns={"Adj Close": "AdjClose"})
            stock = stock.dropna()
            self.stock = stock
Пример #10
0
def test_load_week_or_month(recorder, weekly, monthly):
    ticker = "AAPL"
    start = datetime.strptime("2019-12-01", "%Y-%m-%d")
    end = datetime.strptime("2021-12-02", "%Y-%m-%d")
    prepost = False
    result_df = stocks_helper.load(
        ticker=ticker,
        start=start,
        interval=1440,
        end=end,
        prepost=prepost,
        source="yf",
        weekly=weekly,
        monthly=monthly,
    )
    recorder.capture(result_df)
Пример #11
0
 def call_load(self, other_args: List[str]):
     """Process load command"""
     parser = argparse.ArgumentParser(
         add_help=False,
         formatter_class=argparse.ArgumentDefaultsHelpFormatter,
         prog="load",
         description=
         "Load stock ticker to perform analysis on. When the data " +
         "source is 'yf', an Indian ticker can be loaded by using '.NS' at the end,"
         + " e.g. 'SBIN.NS'. See available market in" +
         " https://help.yahoo.com/kb/exchanges-data-providers-yahoo-finance-sln2310.html.",
     )
     parser.add_argument(
         "-t",
         "--ticker",
         action="store",
         dest="ticker",
         required="-h" not in other_args,
         help="Stock ticker",
     )
     parser.add_argument(
         "-s",
         "--start",
         type=valid_date,
         default=(datetime.now() -
                  timedelta(days=366)).strftime("%Y-%m-%d"),
         dest="start",
         help="The starting date (format YYYY-MM-DD) of the stock",
     )
     if other_args and "-" not in other_args[0][0]:
         other_args.insert(0, "-t")
     ns_parser = parse_known_args_and_warn(parser, other_args)
     if ns_parser:
         df_stock_candidate = stocks_helper.load(
             ns_parser.ticker,
             ns_parser.start,
         )
         if not df_stock_candidate.empty:
             self.start = ns_parser.start
             if "." in ns_parser.ticker:
                 self.ticker = ns_parser.ticker.upper().split(".")[0]
             else:
                 self.ticker = ns_parser.ticker.upper()
         else:
             console.print("Provide a valid ticker")
Пример #12
0
def test_price_target_from_analysts_plt(capsys, interval, mocker, start):
    # MOCK VISUALIZE_OUTPUT
    mocker.patch(
        target="gamestonk_terminal.helper_classes.TerminalStyle.visualize_output"
    )

    ticker = "TSLA"
    stock = load(ticker=ticker, start=start, interval=interval)

    business_insider_view.price_target_from_analysts(
        ticker=ticker,
        start=start,
        interval=interval,
        stock=stock,
        num=None,
        raw=False,
        export=None,
    )
    capsys.readouterr()
Пример #13
0
def test_price_target_from_analysts_plt(capsys, interval, mocker, start,
                                        monkeypatch):
    mock_show = mocker.Mock()
    mocker.patch(target="matplotlib.pyplot.show", new=mock_show)
    monkeypatch.setattr(business_insider_view.gtff, "USE_ION", False)

    ticker = "TSLA"
    stock = load(ticker=ticker, start=start, interval=interval)

    business_insider_view.price_target_from_analysts(
        ticker=ticker,
        start=start,
        interval=interval,
        stock=stock,
        num=None,
        raw=False,
        export=None,
    )
    capsys.readouterr()

    mock_show.assert_called_once()
Пример #14
0
def test_fails_to_deliver(mocker, raw):
    mocker.patch.object(target=sec_view.gtff, attribute="USE_ION", new=False)
    mocker.patch("matplotlib.pyplot.show")
    mocker.patch(
        target="gamestonk_terminal.stocks.dark_pool_shorts.sec_model.get_fails_to_deliver",
        new=mocker.Mock(return_value=df_fails_to_deliver.copy()),
    )
    stock = stocks_helper.load(
        ticker="TSLA",
        start=datetime.strptime("2021-12-18", "%Y-%m-%d"),
    )

    sec_view.fails_to_deliver(
        ticker="PM",
        stock=stock,
        start=datetime.strptime("2021-12-18", "%Y-%m-%d"),
        end=datetime.strptime("2021-12-19", "%Y-%m-%d"),
        num=2,
        raw=raw,
        export="",
    )
Пример #15
0
def test_display_candle(mocker, use_matplotlib):
    # MOCK VISUALIZE_OUTPUT
    mocker.patch(
        target="gamestonk_terminal.helper_classes.TerminalStyle.visualize_output"
    )

    mocker.patch("plotly.basedatatypes.BaseFigure.show")

    # LOAD DATA
    ticker = "GME"
    start = datetime.strptime("2020-12-01", "%Y-%m-%d")
    interval = 1440
    end = datetime.strptime("2020-12-08", "%Y-%m-%d")
    prepost = False
    source = "yf"
    df_stock = stocks_helper.load(
        ticker=ticker,
        start=start,
        interval=interval,
        end=end,
        prepost=prepost,
        source=source,
    )

    # PROCESS DATA
    df_stock = stocks_helper.process_candle(df=df_stock)

    # DISPLAY CANDLE
    s_ticker = "GME"
    intraday = False
    stocks_helper.display_candle(
        s_ticker=s_ticker,
        df_stock=df_stock,
        use_matplotlib=use_matplotlib,
        intraday=intraday,
    )
Пример #16
0
    def call_load(self, other_args: List[str]):
        """Process load command"""
        parser = argparse.ArgumentParser(
            add_help=False,
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
            prog="load",
            description=
            "Load stock ticker and alter the industry, sector, country and market cap "
            "accordingly for this ticker.",
        )
        parser.add_argument(
            "-t",
            "--ticker",
            action="store",
            dest="ticker",
            required="-h" not in other_args,
            help="Stock ticker",
        )
        if other_args and "-" not in other_args[0][0]:
            other_args.insert(0, "-t")
        ns_parser = parse_known_args_and_warn(parser, other_args)
        if ns_parser:
            df_stock_candidate = stocks_helper.load(ns_parser.ticker, )
            if not df_stock_candidate.empty:
                if "." in ns_parser.ticker:
                    self.ticker = ns_parser.ticker.upper().split(".")[0]
                else:
                    self.ticker = ns_parser.ticker.upper()

                data = yf.utils.get_json(
                    f"https://finance.yahoo.com/quote/{self.ticker}")

                if "summaryProfile" in data:
                    self.country = data["summaryProfile"]["country"]
                    if self.country not in financedatabase_model.get_countries(
                    ):
                        similar_cmd = difflib.get_close_matches(
                            self.country,
                            financedatabase_model.get_countries(),
                            n=1,
                            cutoff=0.7,
                        )
                        if similar_cmd:
                            self.country = similar_cmd[0]

                    self.sector = data["summaryProfile"]["sector"]
                    if self.sector not in financedatabase_model.get_sectors():
                        similar_cmd = difflib.get_close_matches(
                            self.sector,
                            financedatabase_model.get_sectors(),
                            n=1,
                            cutoff=0.7,
                        )
                        if similar_cmd:
                            self.sector = similar_cmd[0]

                    self.industry = data["summaryProfile"]["industry"]
                    if self.industry not in financedatabase_model.get_industries(
                    ):
                        similar_cmd = difflib.get_close_matches(
                            self.industry,
                            financedatabase_model.get_industries(),
                            n=1,
                            cutoff=0.7,
                        )
                        if similar_cmd:
                            self.industry = similar_cmd[0]

                if "price" in data:
                    mktcap = data["price"]["marketCap"]

                    if mktcap < 2_000_000_000:
                        self.mktcap = "Small"
                    elif mktcap > 10_000_000_000:
                        self.mktcap = "Large"
                    else:
                        self.mktcap = "Mid"

                self.stocks_data = {}
                self.update_runtime_choices()
Пример #17
0
    def call_load(self, other_args: List[str]):
        """Process load command."""
        parser = argparse.ArgumentParser(
            add_help=False,
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
            prog="load",
            description=
            "Load stock ticker to perform analysis on. When the data source " +
            "is 'yf', an Indian ticker can be loaded by using '.NS' at the end, e.g. "
            + "'SBIN.NS'. See available market in" +
            " https://help.yahoo.com/kb/exchanges-data-providers-yahoo-finance-sln2310.html.",
        )
        parser.add_argument(
            "-t",
            "--ticker",
            action="store",
            dest="ticker",
            required="-h" not in other_args,
            help="Stock ticker",
        )
        parser.add_argument(
            "-s",
            "--start",
            type=valid_date,
            default=(datetime.now() -
                     timedelta(days=366)).strftime("%Y-%m-%d"),
            dest="start",
            help="The starting date (format YYYY-MM-DD) of the stock",
        )
        parser.add_argument(
            "-i",
            "--interval",
            action="store",
            dest="interval",
            type=int,
            default=1440,
            choices=stocks_helper.INTERVALS,
            help="Intraday stock minutes",
        )
        parser.add_argument(
            "--source",
            action="store",
            dest="source",
            choices=stocks_helper.SOURCES,
            default="yf",
            help="Source of historical data.",
        )
        # For the case where a user uses: 'load BB'
        if other_args and "-t" not in other_args and "-h" not in other_args:
            other_args.insert(0, "-t")

        ns_parser = parse_known_args_and_warn(parser, other_args,
                                              EXPORT_ONLY_RAW_DATA_ALLOWED)
        if ns_parser:
            df_stock_candidate = stocks_helper.load(
                ticker=ns_parser.ticker,
                start=ns_parser.start,
                interval=ns_parser.interval,
                source=ns_parser.source,
            )

            if not df_stock_candidate.empty:
                self.start = ns_parser.start
                self.interval = str(ns_parser.interval) + "min"
                if "." in ns_parser.ticker:
                    self.ticker = ns_parser.ticker.upper().split(".")[0]
                else:
                    self.ticker = ns_parser.ticker.upper()
Пример #18
0
    def call_load(self, other_args: List[str]):
        """Process load command"""
        parser = argparse.ArgumentParser(
            add_help=False,
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
            prog="load",
            description="Load stock ticker to perform analysis on. When the data source is syf', an Indian ticker can be"
            " loaded by using '.NS' at the end, e.g. 'SBIN.NS'. See available market in"
            " https://help.yahoo.com/kb/exchanges-data-providers-yahoo-finance-sln2310.html.",
        )
        parser.add_argument(
            "-t",
            "--ticker",
            action="store",
            dest="ticker",
            required="-h" not in other_args,
            help="Stock ticker",
        )
        parser.add_argument(
            "-s",
            "--start",
            type=valid_date,
            default=(datetime.now() - timedelta(days=366)).strftime("%Y-%m-%d"),
            dest="start",
            help="The starting date (format YYYY-MM-DD) of the stock",
        )
        parser.add_argument(
            "-e",
            "--end",
            type=valid_date,
            default=datetime.now().strftime("%Y-%m-%d"),
            dest="end",
            help="The ending date (format YYYY-MM-DD) of the stock",
        )
        parser.add_argument(
            "-i",
            "--interval",
            action="store",
            dest="interval",
            type=int,
            default=1440,
            choices=[1, 5, 15, 30, 60],
            help="Intraday stock minutes",
        )
        parser.add_argument(
            "--source",
            action="store",
            dest="source",
            choices=["yf", "av", "iex"] if "-i" not in other_args else ["yf"],
            default="yf",
            help="Source of historical data.",
        )
        parser.add_argument(
            "-p",
            "--prepost",
            action="store_true",
            default=False,
            dest="prepost",
            help="Pre/After market hours. Only works for 'yf' source, and intraday data",
        )
        parser.add_argument(
            "-r",
            "--iexrange",
            dest="iexrange",
            help="Range for using the iexcloud api.  Note that longer range requires more tokens in account",
            choices=["ytd", "1y", "2y", "5y", "6m"],
            type=str,
            default="ytd",
        )
        if other_args and "-" not in other_args[0][0]:
            other_args.insert(0, "-t")

        ns_parser = parse_known_args_and_warn(parser, other_args)
        if ns_parser:
            df_stock_candidate = stocks_helper.load(
                ns_parser.ticker,
                ns_parser.start,
                ns_parser.interval,
                ns_parser.end,
                ns_parser.prepost,
                ns_parser.source,
            )
            if not df_stock_candidate.empty:
                self.stock = df_stock_candidate
                if "." in ns_parser.ticker:
                    self.ticker, self.suffix = ns_parser.ticker.upper().split(".")
                else:
                    self.ticker = ns_parser.ticker.upper()
                    self.suffix = ""

                if ns_parser.source == "iex":
                    self.start = self.stock.index[0].strftime("%Y-%m-%d")
                else:
                    self.start = ns_parser.start
                self.interval = f"{ns_parser.interval}min"
Пример #19
0
    def call_load(self, other_args: List[str]):
        """Process load command"""
        parser = argparse.ArgumentParser(
            add_help=False,
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
            prog="load",
            description=
            "Load stock ticker to perform analysis on. When the data source" +
            " is syf', an Indian ticker can be" +
            " loaded by using '.NS' at the end, e.g. 'SBIN.NS'. See available market in"
            +
            " https://help.yahoo.com/kb/exchanges-data-providers-yahoo-finance-sln2310.html.",
        )
        parser.add_argument(
            "-t",
            "--ticker",
            action="store",
            dest="ticker",
            required="-h" not in other_args,
            help="Stock ticker",
        )
        parser.add_argument(
            "-s",
            "--start",
            type=valid_date,
            default=(datetime.now() -
                     timedelta(days=1100)).strftime("%Y-%m-%d"),
            dest="start",
            help="The starting date (format YYYY-MM-DD) of the stock",
        )
        parser.add_argument(
            "-e",
            "--end",
            type=valid_date,
            default=datetime.now().strftime("%Y-%m-%d"),
            dest="end",
            help="The ending date (format YYYY-MM-DD) of the stock",
        )
        parser.add_argument(
            "-i",
            "--interval",
            action="store",
            dest="interval",
            type=int,
            default=1440,
            choices=[1, 5, 15, 30, 60],
            help="Intraday stock minutes",
        )
        parser.add_argument(
            "--source",
            action="store",
            dest="source",
            choices=["yf", "av", "iex"] if "-i" not in other_args else ["yf"],
            default="yf",
            help="Source of historical data.",
        )
        parser.add_argument(
            "-p",
            "--prepost",
            action="store_true",
            default=False,
            dest="prepost",
            help=
            "Pre/After market hours. Only works for 'yf' source, and intraday data",
        )
        parser.add_argument(
            "-f",
            "--file",
            default=None,
            help="Path to load custom file.",
            dest="filepath",
            type=str,
        )
        parser.add_argument(
            "-m",
            "--monthly",
            action="store_true",
            default=False,
            help="Load monthly data",
            dest="monthly",
        )
        parser.add_argument(
            "-w",
            "--weekly",
            action="store_true",
            default=False,
            help="Load weekly data",
            dest="weekly",
        )
        parser.add_argument(
            "-r",
            "--iexrange",
            dest="iexrange",
            help=
            "Range for using the iexcloud api.  Note that longer range requires more tokens in account",
            choices=["ytd", "1y", "2y", "5y", "6m"],
            type=str,
            default="ytd",
        )
        if other_args and "-" not in other_args[0][0]:
            other_args.insert(0, "-t")

        ns_parser = parse_known_args_and_warn(parser, other_args)

        if ns_parser:
            if ns_parser.weekly and ns_parser.monthly:
                console.print(
                    "[red]Only one of monthly or weekly can be selected.[/red]\n."
                )
                return
            if ns_parser.filepath is None:
                df_stock_candidate = stocks_helper.load(
                    ns_parser.ticker,
                    ns_parser.start,
                    ns_parser.interval,
                    ns_parser.end,
                    ns_parser.prepost,
                    ns_parser.source,
                    weekly=ns_parser.weekly,
                    monthly=ns_parser.monthly,
                )
            else:
                # This seems to block the .exe since the folder needs to be manually created
                # This block basically makes sure that we only look for the file if the -f flag is used
                # If we add files in the argparse choices, it will fail for the .exe even if no -f is used
                try:
                    if ns_parser.filepath not in os.listdir(
                            os.path.join("custom_imports", "stocks")):
                        console.print(
                            f"[red]{ns_parser.filepath} not found in custom_imports/stocks/ folder[/red].\n"
                        )
                        return
                except Exception as e:
                    console.print(e)
                    return

                df_stock_candidate = stocks_helper.load_custom(
                    os.path.join(os.path.join("custom_imports", "stocks"),
                                 ns_parser.filepath))
                if df_stock_candidate.empty:
                    return
            if not df_stock_candidate.empty:
                self.stock = df_stock_candidate
                self.add_info = stocks_helper.additional_info_about_ticker(
                    ns_parser.ticker)
                console.print(self.add_info)
                if "." in ns_parser.ticker:
                    self.ticker, self.suffix = ns_parser.ticker.upper().split(
                        ".")
                else:
                    self.ticker = ns_parser.ticker.upper()
                    self.suffix = ""

                if ns_parser.source == "iex":
                    self.start = self.stock.index[0].strftime("%Y-%m-%d")
                else:
                    self.start = ns_parser.start
                self.interval = f"{ns_parser.interval}min"

                if self.PATH in ["/stocks/qa/", "/stocks/pred/"]:
                    self.stock["Returns"] = self.stock["Adj Close"].pct_change(
                    )
                    self.stock["LogRet"] = np.log(
                        self.stock["Adj Close"]) - np.log(
                            self.stock["Adj Close"].shift(1))
                    self.stock["LogPrice"] = np.log(self.stock["Adj Close"])
                    self.stock = self.stock.rename(
                        columns={"Adj Close": "AdjClose"})
                    self.stock = self.stock.dropna()
                    self.stock.columns = [
                        x.lower() for x in self.stock.columns
                    ]
                    console.print("")
Пример #20
0
 def call_load(self, other_args: List[str]):
     """Process load command"""
     self.ticker, self.start, _, self.stock = load(other_args, self.ticker,
                                                   self.start, "1440min",
                                                   self.stock)
Пример #21
0
 def test_load(self):
     values = stocks_helper.load(["GME"], "GME", self.start, "1440min",
                                 pd.DataFrame())
     self.assertEqual(values[0], "GME")
     self.assertNotEqual(values[1], None)
     self.assertEqual(values[2], "1440min")
Пример #22
0
    def call_load(self, other_args: List[str]):
        """Process load command"""
        parser = argparse.ArgumentParser(
            add_help=False,
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
            prog="load",
            description=
            "Load stock ticker to perform analysis on. When the data source" +
            " is 'yf', an Indian ticker can be loaded by using '.NS' at the end,"
            + " e.g. 'SBIN.NS'. See available market in" +
            " https://help.yahoo.com/kb/exchanges-data-providers-yahoo-finance-sln2310.html.",
        )
        parser.add_argument(
            "-t",
            "--ticker",
            action="store",
            dest="ticker",
            required="-h" not in other_args,
            help="Stock ticker",
        )
        if other_args and "-" not in other_args[0][0]:
            other_args.insert(0, "-t")
        ns_parser = parse_known_args_and_warn(parser, other_args)
        if ns_parser:
            df_stock_candidate = stocks_helper.load(ns_parser.ticker, )
            if not df_stock_candidate.empty:
                if "." in ns_parser.ticker:
                    self.ticker = ns_parser.ticker.upper().split(".")[0]
                else:
                    self.ticker = ns_parser.ticker.upper()

                data = yf.utils.get_json(
                    f"https://finance.yahoo.com/quote/{self.ticker}")

                if "summaryProfile" in data:
                    self.country = data["summaryProfile"]["country"]
                    if self.country not in financedatabase_model.get_countries(
                    ):
                        similar_cmd = difflib.get_close_matches(
                            self.country,
                            financedatabase_model.get_countries(),
                            n=1,
                            cutoff=0.7,
                        )
                        if similar_cmd:
                            self.country = similar_cmd[0]

                    self.sector = data["summaryProfile"]["sector"]
                    if self.sector not in financedatabase_model.get_sectors():
                        similar_cmd = difflib.get_close_matches(
                            self.sector,
                            financedatabase_model.get_sectors(),
                            n=1,
                            cutoff=0.7,
                        )
                        if similar_cmd:
                            self.sector = similar_cmd[0]

                    self.industry = data["summaryProfile"]["industry"]
                    if self.industry not in financedatabase_model.get_industries(
                    ):
                        similar_cmd = difflib.get_close_matches(
                            self.industry,
                            financedatabase_model.get_industries(),
                            n=1,
                            cutoff=0.7,
                        )
                        if similar_cmd:
                            self.industry = similar_cmd[0]

                if "price" in data:
                    mktcap = data["price"]["marketCap"]

                    if mktcap < 2_000_000_000:
                        self.mktcap = "Small"
                    elif mktcap > 10_000_000_000:
                        self.mktcap = "Large"
                    else:
                        self.mktcap = "Mid"

                self.stocks_data = {}
                self.update_runtime_choices()
Пример #23
0
 def call_load(self, other_args: List[str]):
     """Process load command"""
     self.ticker, _, _, _ = load(other_args, self.ticker, "", "1440min",
                                 pd.DataFrame())
     if "." in self.ticker:
         self.ticker = self.ticker.split(".")[0]
Пример #24
0
    def call_load(self, other_args: List[str]):
        """Process load command"""
        parser = argparse.ArgumentParser(
            add_help=False,
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
            prog="load",
            description=
            "Load stock ticker to perform analysis on. When the data source" +
            " is 'yf', an Indian ticker can be loaded by using '.NS' at the end,"
            + " e.g. 'SBIN.NS'. See available market in" +
            " https://help.yahoo.com/kb/exchanges-data-providers-yahoo-finance-sln2310.html.",
        )
        parser.add_argument(
            "-t",
            "--ticker",
            action="store",
            dest="ticker",
            required="-h" not in other_args,
            help="Stock ticker",
        )
        parser.add_argument(
            "-s",
            "--start",
            type=valid_date,
            default=(datetime.now() -
                     timedelta(days=1100)).strftime("%Y-%m-%d"),
            dest="start",
            help="The starting date (format YYYY-MM-DD) of the stock",
        )
        parser.add_argument(
            "-e",
            "--end",
            type=valid_date,
            default=datetime.now().strftime("%Y-%m-%d"),
            dest="end",
            help="The ending date (format YYYY-MM-DD) of the stock",
        )
        parser.add_argument(
            "-i",
            "--interval",
            action="store",
            dest="interval",
            type=int,
            default=1440,
            choices=self.stock_interval,
            help="Intraday stock minutes",
        )
        parser.add_argument(
            "--source",
            action="store",
            dest="source",
            choices=self.stock_sources,
            default="yf",
            help="Source of historical data.",
        )
        parser.add_argument(
            "-p",
            "--prepost",
            action="store_true",
            default=False,
            dest="prepost",
            help=
            "Pre/After market hours. Only works for 'yf' source, and intraday data",
        )

        # For the case where a user uses: 'load BB'
        if other_args and "-t" not in other_args and "-h" not in other_args:
            other_args.insert(0, "-t")

        ns_parser = parse_known_args_and_warn(parser, other_args)
        if ns_parser:

            df_stock_candidate = stocks_helper.load(
                ns_parser.ticker,
                ns_parser.start,
                ns_parser.interval,
                ns_parser.end,
                ns_parser.prepost,
                ns_parser.source,
            )

            if not df_stock_candidate.empty:
                self.stock = df_stock_candidate
                if "." in ns_parser.ticker:
                    self.ticker = ns_parser.ticker.upper().split(".")[0]
                else:
                    self.ticker = ns_parser.ticker.upper()

                self.start = ns_parser.start
                self.interval = str(ns_parser.interval) + "min"

                self.stock["Returns"] = self.stock["Adj Close"].pct_change()
                self.stock["LogRet"] = np.log(
                    self.stock["Adj Close"]) - np.log(
                        self.stock["Adj Close"].shift(1))
                self.stock["LogPrice"] = np.log(self.stock["Adj Close"])
                self.stock = self.stock.rename(
                    columns={"Adj Close": "AdjClose"})
                self.stock = self.stock.dropna()
                self.stock.columns = [x.lower() for x in self.stock.columns]
                console.print("")