Пример #1
0
def liquidate_shares(s3_client: S3Client, s3_bucket: str, trading_day: Arrow,
                     transactions: pd.DataFrame) -> pd.DataFrame:
    """Sells all current positions in portfolio, based on current positions."""
    if transactions.empty:
        return
    # use ONLY the transactions dataframe to identify what stocks to liquidate
    # all_positions = transactions.groupby('symbol').amount.sum()
    # df = all_positions[all_positions >= 0].to_frame()
    stock_positions = transactions.groupby("symbol").amount.sum()
    # filter out the rows with amount = 0
    df = stock_positions[stock_positions > 0].to_frame()
    df["symbol"] = df.index
    df["amount"] = df["amount"] * -1
    df["price"] = df.apply(lambda x: qm.equities.historical.get_price(
        s3_client, s3_bucket, x["symbol"], trading_day),
                           axis=1)
    df["txn_dollars"] = df["price"] * df["amount"] * -1
    df["date"] = pd.to_datetime(arrow.get(trading_day.date()).datetime)
    df.set_index("date", inplace=True)

    return df
Пример #2
0
def purchase_new_shares(
    s3_client: S3Client,
    s3_bucket: str,
    trading_day: Arrow,
    available_cash: float,
    num_holdings: int,
    weight_type: WeightType,
    market_cap_percentile: int,
) -> pd.DataFrame:
    """
    Purchases shares of quality momentum stocks.

    Index: DatetimeIndex
    Columns: Index(['amount', 'price', 'symbol', 'txn_dollars'], dtype='object')
    """
    tickers = qm.algorithms.calculate_momentum.get_quality_momentum_stocks(
        s3_client, s3_bucket, trading_day, num_holdings, market_cap_percentile)
    if weight_type == WeightType.value_weighted:
        raise NotImplementedError(
            "Need to grab trading_day market cap to determine size of position"
        )

    data = [(x, float(math.floor(available_cash / len(tickers))))
            for x in tickers]
    df = pd.DataFrame(data, columns=["symbol", "position_size"])
    df["price"] = df.apply(lambda x: qm.equities.historical.get_price(
        s3_client, s3_bucket, x["symbol"], trading_day),
                           axis=1)
    df["amount"] = (df["position_size"] / df["price"]).apply(
        np.floor).astype(int)
    df["txn_dollars"] = df["price"] * df["amount"] * -1
    df["date"] = pd.to_datetime(arrow.get(trading_day.date()).datetime)
    df.set_index("date", inplace=True)
    del df["position_size"]

    return df