Exemplo n.º 1
0
def test_default_calendars():
    for name in get_calendar_names():
        if name == "XKRX":
            with pytest.warns(UserWarning):
                assert get_calendar(name) is not None
        else:
            assert get_calendar(name) is not None
Exemplo n.º 2
0
def test_default_calendars():
    for name in get_calendar_names():
        assert get_calendar(name) is not None
Exemplo n.º 3
0
def additional_info_about_ticker(ticker: str) -> str:
    """Additional information about trading the ticker such as exchange, currency, timezone and market status

    Parameters
    ----------
    ticker : str
        The stock ticker to extract if stock market is open or not

    Returns
    -------
    str
        Additional information about trading the ticker
    """
    extra_info = ""
    if ticker:
        # outside US exchange
        if "." in ticker:
            ticker_info = yf.Ticker(ticker).info

            extra_info += "\n[param]Datetime: [/param]"
            if (
                "exchangeTimezoneName" in ticker_info
                and ticker_info["exchangeTimezoneName"]
            ):
                dtime = datetime.now(
                    pytz.timezone(ticker_info["exchangeTimezoneName"])
                ).strftime("%Y %b %d %H:%M")
                extra_info += dtime
                extra_info += "\n[param]Timezone: [/param]"
                extra_info += ticker_info["exchangeTimezoneName"]
            else:
                extra_info += "\n[param]Datetime: [/param]"
                extra_info += "\n[param]Timezone: [/param]"

            extra_info += "\n[param]Exchange: [/param]"
            if "exchange" in ticker_info and ticker_info["exchange"]:
                exchange_name = ticker_info["exchange"]
                extra_info += exchange_name

            extra_info += "\n[param]Currency: [/param]"
            if "currency" in ticker_info and ticker_info["currency"]:
                extra_info += ticker_info["currency"]

            extra_info += "\n[param]Market:   [/param]"
            if "exchange" in ticker_info and ticker_info["exchange"]:
                if exchange_name in mcal.get_calendar_names():
                    calendar = mcal.get_calendar(exchange_name)
                    sch = calendar.schedule(
                        start_date=(datetime.now() - timedelta(days=3)).strftime(
                            "%Y-%m-%d"
                        ),
                        end_date=(datetime.now() + timedelta(days=3)).strftime(
                            "%Y-%m-%d"
                        ),
                    )
                    user_tz = get_user_timezone_or_invalid()
                    if user_tz != "INVALID":
                        is_market_open = calendar.open_at_time(
                            sch,
                            pd.Timestamp(
                                datetime.now().strftime("%Y-%m-%d %H:%M"), tz=user_tz
                            ),
                        )
                        if is_market_open:
                            extra_info += "OPEN"
                        else:
                            extra_info += "CLOSED"
        else:
            extra_info += "\n[param]Datetime: [/param]"
            dtime = datetime.now(pytz.timezone("America/New_York")).strftime(
                "%Y %b %d %H:%M"
            )
            extra_info += dtime
            extra_info += "\n[param]Timezone: [/param]America/New_York"
            extra_info += "\n[param]Currency: [/param]USD"
            extra_info += "\n[param]Market:   [/param]"
            calendar = mcal.get_calendar("NYSE")
            sch = calendar.schedule(
                start_date=(datetime.now() - timedelta(days=3)).strftime("%Y-%m-%d"),
                end_date=(datetime.now() + timedelta(days=3)).strftime("%Y-%m-%d"),
            )
            user_tz = get_user_timezone_or_invalid()
            if user_tz != "INVALID":
                is_market_open = calendar.open_at_time(
                    sch,
                    pd.Timestamp(datetime.now().strftime("%Y-%m-%d %H:%M"), tz=user_tz),
                )
                if is_market_open:
                    extra_info += "OPEN"
                else:
                    extra_info += "CLOSED"

    else:
        extra_info += "\n[param]Datetime: [/param]"
        extra_info += "\n[param]Timezone: [/param]"
        extra_info += "\n[param]Exchange: [/param]"
        extra_info += "\n[param]Market: [/param]"
        extra_info += "\n[param]Currency: [/param]"

    return extra_info + "\n"
def test_get_calendar_names():
    assert 'ASX' in mcal.get_calendar_names()
Exemplo n.º 5
0
    def fill_in_time_block(self):
        self.get_ticker_selection()
        self.initialize_worksheet(sheet_type="backend")

        today = datetime.today().date()
        self.ws.Range('last_update').Value = today.strftime("%x %X")

        # Gets the functioning dates in a a dataframe format of the stock exchange of the stock
        stock_exchange = self.ws.Range("exchange").Value
        exchange_calendar = None
        for exchange_name in mcal.get_calendar_names():
            if stock_exchange.upper() in exchange_name.upper(
            ) or exchange_name.upper() in stock_exchange.upper():
                exchange_calendar = mcal.get_calendar(exchange_name)
                break

        if exchange_calendar is None:
            pymsgbox.alert(
                f"Stock exchange for {self.ticker} couldn't be found in stock exchange calender"
            )
            return

        if stock_exchange is None:
            pymsgbox.alert(
                "No valid calendar could be found of the stock exchange linked to the selected ticker"
            )
            return

        self.ws.Range('last_market_close_date').Value = datetime.date(
            exchange_calendar.valid_days(start_date=today - timedelta(days=7),
                                         end_date=today)[-1]).strftime("%x %X")
        self.ws.Range('next_market_open_date').Value = datetime.date(
            exchange_calendar.valid_days(
                start_date=today,
                end_date=today + timedelta(days=7))[0]).strftime("%x %X")

        # Gets the next earning date for the specific stock (AKA Quarter Report release date)
        yec = YahooEarningsCalendar()
        self.ws.Range(
            'next_quarter_report_date').Value = datetime.utcfromtimestamp(
                yec.get_next_earnings_date(self.ticker)).strftime("%x %X")

        # Gets the last earning date of a specific stock
        earnings_df = pd.DataFrame(yec.get_earnings_of(self.ticker))
        earnings_df['report_date'] = earnings_df['startdatetime'].apply(
            lambda x: dateutil.parser.isoparse(x).date())
        last_earnings_df = earnings_df.loc[earnings_df['report_date'] < today]

        self.ws.Range('last_quarter_report_date').Value = last_earnings_df[
            'report_date'].iloc[0].strftime("%x %X")

        # Gets the date where you first start investing in this stock, and last buy and sell dates
        self.get_portfolio_dict()
        self.dict_to_df()
        stock_df = self.db_df.loc[self.db_df['Ticker'] == self.ticker]
        if stock_df.empty:
            inv_start_date = "-"
        else:
            inv_start_date = datetime.strptime(
                stock_df['Transaction Date'].iloc[0],
                '%Y-%m-%d').strftime("%x %X")

        buy_df = stock_df.loc[stock_df['Type'] == 'Buy']
        sell_df = stock_df.loc[stock_df['Type'] == 'Sell']

        # Check if the dataframes really contain dates to be used for time block
        if buy_df.empty:
            last_buy_date = "-"
        else:
            last_buy_date = datetime.strptime(
                buy_df['Transaction Date'].iloc[-1],
                '%Y-%m-%d').strftime("%x %X")

        if sell_df.empty:
            last_sell_date = "-"
        else:
            last_sell_date = datetime.strptime(
                sell_df['Transaction Date'].iloc[-1],
                '%Y-%m-%d').strftime("%x %X")

        self.ws.Range('investment_start_date').Value = inv_start_date
        self.ws.Range('last_buy_date').Value = last_buy_date
        self.ws.Range('last_sell_date').Value = last_sell_date