Esempio n. 1
0
def test_get_ark_trades_by_ticker_json_normalize(mocker):
    mock_df = pd.DataFrame()
    mocker.patch(
        target="pandas.json_normalize",
        new=mocker.Mock(return_value=mock_df),
    )
    result_df = ark_model.get_ark_trades_by_ticker(ticker="TSLA")

    assert result_df.empty
Esempio n. 2
0
def test_get_ark_trades_by_ticker_invalid_status(mocker):
    mock_response = requests.Response()
    mock_response.status_code = 400
    mocker.patch(
        target="requests.get",
        new=mocker.Mock(return_value=mock_response),
    )
    result_df = ark_model.get_ark_trades_by_ticker(ticker="TSLA")

    assert result_df.empty
Esempio n. 3
0
def display_ark_trades(ticker: str,
                       num: int = 20,
                       export: str = "",
                       show_ticker: bool = False):
    """Display ARK trades for ticker

    Parameters
    ----------
    ticker : str
        Ticker to get trades for
    num: int
        Number of rows to show
    export : str, optional
        Format to export data
    show_ticker: bool
        Flag to show ticker in table
    """
    ark_holdings = ark_model.get_ark_trades_by_ticker(ticker)

    if ark_holdings.empty:
        print(
            "Issue getting data from cathiesark.com.  Likely no trades found.\n"
        )
        return

    # Since this is for a given ticker, no need to show it
    if not show_ticker:
        ark_holdings = ark_holdings.drop(columns=["ticker"])
    ark_holdings["Total"] = ark_holdings["Total"] / 1_000_000
    ark_holdings.rename(columns={
        "Close": "Close ($)",
        "Total": "Total ($1M)"
    },
                        inplace=True)

    ark_holdings.index = pd.Series(
        ark_holdings.index).apply(lambda x: x.strftime("%Y-%m-%d"))
    if gtff.USE_TABULATE_DF:
        print(
            tabulate(
                ark_holdings.head(num),
                headers=ark_holdings.columns,
                showindex=True,
                floatfmt=("", ".4f", ".4f", ".4f", "", ".2f", ".2f", ".3f"),
                tablefmt="fancy_grid",
            ))
    else:
        print(ark_holdings.head(num).to_string())
    print("")
    export_data(export, os.path.dirname(os.path.abspath(__file__)),
                "arktrades", ark_holdings)
Esempio n. 4
0
def test_get_ark_trades_by_ticker_invalid_json(mocker):
    mocker.patch(
        target="json.loads",
        new=mocker.Mock(
            return_value={
                "props": {
                    "pageProps": [],
                }
            }
        ),
    )
    result_df = ark_model.get_ark_trades_by_ticker(ticker="TSLA")

    assert result_df.empty
Esempio n. 5
0
def display_ark_trades(ticker: str,
                       num: int = 20,
                       export: str = "",
                       show_ticker: bool = False):
    """Display ARK trades for ticker

    Parameters
    ----------
    ticker : str
        Ticker to get trades for
    num: int
        Number of rows to show
    export : str, optional
        Format to export data
    show_ticker: bool
        Flag to show ticker in table
    """
    ark_holdings = ark_model.get_ark_trades_by_ticker(ticker)

    if ark_holdings.empty:
        console.print(
            "Issue getting data from cathiesark.com.  Likely no trades found.\n"
        )
        return

    # Since this is for a given ticker, no need to show it
    if not show_ticker:
        ark_holdings = ark_holdings.drop(columns=["ticker"])
    ark_holdings["Total"] = ark_holdings["Total"] / 1_000_000
    ark_holdings.rename(columns={
        "Close": "Close ($)",
        "Total": "Total ($1M)"
    },
                        inplace=True)

    ark_holdings.index = pd.Series(
        ark_holdings.index).apply(lambda x: x.strftime("%Y-%m-%d"))
    print_rich_table(
        ark_holdings.head(num),
        headers=list(ark_holdings.columns),
        show_index=True,
        title="ARK Trades",
    )

    console.print("")
    export_data(export, os.path.dirname(os.path.abspath(__file__)),
                "arktrades", ark_holdings)
Esempio n. 6
0
async def arktrades_command(ctx, ticker="", num=""):
    """Displays trades made by ark [cathiesark.com]"""

    try:
        # Debug user input
        if cfg.DEBUG:
            print(f"!stocks.dd.arktrades{ticker}")

        if num == "":
            pass
        else:
            if not num.lstrip("-").isnumeric():
                raise Exception("Number has to be an integer")
            num = int(num)

        if ticker == "":
            raise Exception("A ticker is required")

        ark_holdings = ark_model.get_ark_trades_by_ticker(ticker)

        if ark_holdings.empty:
            raise Exception(
                "Issue getting data from cathiesark.com. Likely no trades found.\n"
            )

        ark_holdings = ark_holdings.drop(columns=["ticker"])
        ark_holdings["Total"] = ark_holdings["Total"] / 1_000_000
        ark_holdings.rename(columns={
            "Close": "Close ($)",
            "Total": "Total ($1M)"
        },
                            inplace=True)

        ark_holdings.index = pd.Series(
            ark_holdings.index).apply(lambda x: x.strftime("%Y-%m-%d"))

        if num == "":
            ark_holdings_str = ark_holdings.to_string()
        else:
            ark_holdings_str = ark_holdings.head(num).to_string()

        if len(ark_holdings_str) <= 4000:
            embed = discord.Embed(
                title=f"Stocks: [cathiesark.com] {ticker} Trades by Ark",
                description="```" + ark_holdings_str + "```",
                colour=cfg.COLOR,
            )
            embed.set_author(
                name=cfg.AUTHOR_NAME,
                icon_url=cfg.AUTHOR_ICON_URL,
            )

            await ctx.send(embed=embed)

        else:
            i = 0
            str_start = 0
            str_end = 4000
            columns = []
            while i <= len(ark_holdings_str) / 4000:
                columns.append(
                    discord.Embed(
                        title=
                        f"Stocks: [cathiesark.com] {ticker} Trades by Ark",
                        description="```" +
                        ark_holdings_str[str_start:str_end] + "```",
                        colour=cfg.COLOR,
                    ).set_author(
                        name=cfg.AUTHOR_NAME,
                        icon_url=cfg.AUTHOR_ICON_URL,
                    ))
                str_end = str_start
                str_start += 4000
                i += 1

            await pagination(columns, ctx)

    except Exception as e:
        embed = discord.Embed(
            title=f"ERROR Stocks: [cathiesark.com] {ticker} Trades by Ark",
            colour=cfg.COLOR,
            description=e,
        )
        embed.set_author(
            name=cfg.AUTHOR_NAME,
            icon_url=cfg.AUTHOR_ICON_URL,
        )

        await ctx.send(embed=embed)
Esempio n. 7
0
async def arktrades_command(ctx, ticker: str = "", num: int = 10):
    """Displays trades made by ark [cathiesark.com]"""

    try:
        # Debug user input
        if cfg.DEBUG:
            logger.debug("!stocks.dd.arktrades %s", ticker)

        if ticker:
            ark_holdings = ark_model.get_ark_trades_by_ticker(ticker)
            ark_holdings = ark_holdings.drop(
                columns=["ticker", "everything.profile.companyName"])

        if ark_holdings.empty:
            raise Exception(
                "Issue getting data from cathiesark.com. Likely no trades found.\n"
            )

        ark_holdings["Total"] = ark_holdings["Total"] / 1_000_000
        ark_holdings.rename(columns={
            "direction": "B/S",
            "weight": "F %"
        },
                            inplace=True)

        ark_holdings.index = pd.Series(
            ark_holdings.index).apply(lambda x: x.strftime("%Y-%m-%d"))

        df = ark_holdings.head(num)
        dindex = len(df.head(num).index)
        formats = {"Close": "{:.2f}", "Total": "{:.2f}"}
        for col, f in formats.items():
            df[col] = df[col].map(lambda x: f.format(x))  # pylint: disable=W0640

        title = f"Stocks: [cathiesark.com] {ticker.upper()} Trades by Ark"

        embeds: list = []

        i, i2, end = 0, 0, 20
        df_pg = []
        embeds_img = []
        dindex = len(df.index)
        while i < dindex:
            df_pg = df.iloc[i:end]
            df_pg.append(df_pg)
            fig = df2img.plot_dataframe(
                df_pg,
                fig_size=(900, (40 + (40 * 20))),
                col_width=[5, 10, 4, 4, 3, 4, 5],
                tbl_cells=dict(height=35, ),
                font=dict(
                    family="Consolas",
                    size=20,
                ),
                template="plotly_dark",
                paper_bgcolor="rgba(0, 0, 0, 0)",
            )
            imagefile = f"disc-insider{i}.png"

            df2img.save_dataframe(fig=fig, filename=imagefile)
            image = Image.open(imagefile)
            image = autocrop_image(image, 0)
            image.save(imagefile, "PNG", quality=100)
            uploaded_image = gst_imgur.upload_image(imagefile,
                                                    title="something")
            image_link = uploaded_image.link
            embeds_img.append(f"{image_link}", )
            embeds.append(disnake.Embed(
                title=title,
                colour=cfg.COLOR,
            ), )
            i2 += 1
            i += 20
            end += 20
            os.remove(imagefile)

        # Author/Footer
        for i in range(0, i2):
            embeds[i].set_author(
                name=cfg.AUTHOR_NAME,
                url=cfg.AUTHOR_URL,
                icon_url=cfg.AUTHOR_ICON_URL,
            )
            embeds[i].set_footer(
                text=cfg.AUTHOR_NAME,
                icon_url=cfg.AUTHOR_ICON_URL,
            )

        i = 0
        for i in range(0, i2):
            embeds[i].set_image(url=embeds_img[i])

            i += 1
        embeds[0].set_footer(text=f"Page 1 of {len(embeds)}")
        options = [
            disnake.SelectOption(label="Home", value="0", emoji="🟢"),
        ]

        await ctx.send(embed=embeds[0], view=Menu(embeds, options))

    except Exception as e:
        embed = disnake.Embed(
            title=f"ERROR Stocks: [cathiesark.com] {ticker} Trades by Ark",
            colour=cfg.COLOR,
            description=e,
        )
        embed.set_author(
            name=cfg.AUTHOR_NAME,
            icon_url=cfg.AUTHOR_ICON_URL,
        )

        await ctx.send(embed=embed, delete_after=30.0)
Esempio n. 8
0
def test_get_ark_trades_by_ticker_invalid_ticker():
    result_df = ark_model.get_ark_trades_by_ticker(ticker="INVALID_TICKER")
    assert result_df.empty
Esempio n. 9
0
def test_get_ark_trades_by_ticker_not_recorded():
    with pytest.raises(vcr.errors.CannotOverwriteExistingCassetteException):
        ark_model.get_ark_trades_by_ticker(ticker="AAPL")
Esempio n. 10
0
def test_get_ark_trades_by_ticker(recorder):
    result_df = ark_model.get_ark_trades_by_ticker(ticker="TSLA")

    recorder.capture(result_df)
Esempio n. 11
0
def arktrades_command(ticker: str = "", num: int = 30):
    """Displays trades made by ark [cathiesark.com]"""

    # Debug user input
    if imps.DEBUG:
        logger.debug("dd arktrades %s", ticker)

    if ticker:
        ark_holdings = ark_model.get_ark_trades_by_ticker(ticker)

    if ark_holdings.empty:
        raise Exception(
            "Issue getting data from cathiesark.com. Likely no trades found.\n"
        )

    ark_holdings["Total"] = ark_holdings["Total"] / 1_000_000
    ark_holdings.rename(
        columns={
            "shares": "Shares",
            "direction": "B/S",
            "weight": "Weight",
            "fund": "Fund",
        },
        inplace=True,
    )
    ark_holdings = ark_holdings.drop(
        columns=["ticker", "everything.profile.companyName"])

    ark_holdings.index = pd.Series(
        ark_holdings.index).apply(lambda x: x.strftime("%Y-%m-%d"))

    df = ark_holdings.head(num)
    df = df.fillna(0)
    formats = {"Weight": "{:.2f}", "Close": "${:.2f}", "Total": "{:.2f}M"}
    for col, f in formats.items():
        df[col] = df[col].map(lambda x: f.format(x))  # pylint: disable=W0640

    title = f"Stocks: [cathiesark.com] {ticker.upper()} Trades by Ark"

    embeds: list = []

    i, i2, end = 0, 0, 15
    df_pg, embeds_img, images_list = [], [], []

    while i < len(df.index):
        df_pg = df.iloc[i:end]
        df_pg.append(df_pg)
        fig = imps.plot_df(
            df_pg,
            fig_size=(900, (40 + (40 * 20))),
            col_width=[5, 8, 4, 4, 3, 5, 5],
            tbl_header=imps.PLT_TBL_HEADER,
            tbl_cells=imps.PLT_TBL_CELLS,
            font=imps.PLT_TBL_FONT,
            row_fill_color=imps.PLT_TBL_ROW_COLORS,
            paper_bgcolor="rgba(0, 0, 0, 0)",
        )
        imagefile = imps.save_image("dd-arktrades.png", fig)

        if imps.IMAGES_URL or not imps.IMG_HOST_ACTIVE:
            image_link = imps.multi_image(imagefile)
            images_list.append(imagefile)
        else:
            image_link = imps.multi_image(imagefile)

        embeds_img.append(f"{image_link}", )
        embeds.append(disnake.Embed(
            title=title,
            colour=imps.COLOR,
        ), )
        i2 += 1
        i += 15
        end += 15

    # Author/Footer
    for i in range(0, i2):
        embeds[i].set_author(
            name=imps.AUTHOR_NAME,
            url=imps.AUTHOR_URL,
            icon_url=imps.AUTHOR_ICON_URL,
        )
        embeds[i].set_footer(
            text=imps.AUTHOR_NAME,
            icon_url=imps.AUTHOR_ICON_URL,
        )

    i = 0
    for i in range(0, i2):
        embeds[i].set_image(url=embeds_img[i])

        i += 1
    embeds[0].set_footer(text=f"Page 1 of {len(embeds)}")
    choices = [
        disnake.SelectOption(label="Home", value="0", emoji="🟢"),
    ]

    return {
        "view": imps.Menu,
        "title": title,
        "embed": embeds,
        "choices": choices,
        "embeds_img": embeds_img,
        "images_list": images_list,
    }