背景需求

【理财类-01-06】20260716 股票“差价”收益计算和excel统计(Python)https://mp.csdn.net/mp_blog/creation/editor/162911231

我发现有些股数少,会导致佣金总额小于5元,但是实际支付是5元,就会损失佣金

所以我要预先根据“买入价、卖出价”和“佣金比例”“预设100股-100000股(整数股)”来推算正好在大于等于5元的那个股数

在107行,写入股票代码和买入价或卖出价


'''
输入“买入价*预设股数(100-10000)*佣金比例(沪0.0001843深0.0001654)”,当佣金正好大于等于5“,就确定用这个股数”
豆包、阿夏
20260716
'''

def calc_min_shares(code: str, buy_price: float) -> dict:
    """
    根据股票代码、买入价,计算刚好佣金≥5元的最小股数(100~10000,100手递增)
    :param code: 股票代码字符串,如"600001"、"300001"
    :param buy_price: 买入单价
    :return: 结果字典
    """
    # 1. 校验股票代码长度,提取前两位
    if len(code) != 6 or not code.isdigit():
        raise ValueError("股票代码必须是6位纯数字")
    code_prefix = code[:2]

    # 2. 匹配市场与佣金费率
    if code_prefix in ("60", "68"):
        market = "沪市"
        commission_rate = 0.0001843  # 0.1843‰
    elif code_prefix in ("00", "30"):
        market = "深市"
        commission_rate = 0.0001654  # 0.1654‰
    else:
        raise ValueError("仅支持60/68开头沪市、00/30开头深市A股代码")

    min_target_shares = None
    target_commission = 0.0
    target_amount = 0.0

    # 3. 遍历100~10000股,步长100(A股1手=100股)
    for shares in range(100, 100001, 100):
        trade_amount = buy_price * shares
        real_commission = trade_amount * commission_rate

        # 找到第一个佣金≥5元的股数,直接跳出循环
        if real_commission >= 5:
            min_target_shares = shares
            target_amount = trade_amount
            target_commission = real_commission
            break

    # 4. 封装返回结果
    result = {
        "股票代码": code,
        "市场": market,
        "佣金费率": f"{commission_rate * 1000}‰",
        "买入单价": buy_price,
        "搜索区间": "100 ~ 10000股(100股递增)"
        '\n---------------'
    }

    if min_target_shares is not None:
        result["满足佣金≥5元最小股数"] = min_target_shares
        result["计算佣金(未保底)"] = round(target_commission, 4)
        result["实际收取佣金(保底5元)"] = max(5, round(target_commission, 2))
        result[""]='----------------------------------'
        result["对应成交总金额"] = round(target_amount, 2)
       
    else:
        result["提示"] = "区间100-10000股内,所有持仓计算佣金均不足5元,统一按5元收取"

    return result


# ---------------------- 测试调用示例 ----------------------
if __name__ == "__main__":
    # 示例1:沪市60开头,股价10元
    try:
        res1 = calc_min_shares("600000", 10.0)
        print("=== 测试1 沪市600000,股价10元 ===")
        for k, v in res1.items():
            print(f"{k}: {v}")
    except Exception as e:
        print("错误:", e)

    print("\n" + "-"*60 + "\n")

    # 示例2:深市30开头,股价5元
    try:
        res2 = calc_min_shares("300001", 5.0)
        print("=== 测试2 深市300001,股价5元 ===")
        for k, v in res2.items():
            print(f"{k}: {v}")
    except Exception as e:
        print("错误:", e)

    print("\n" + "-"*60 + "\n")

    # 示例3:低价股,10000股佣金仍不足5
    try:
        res3 = calc_min_shares("000001", 0.5)
        print("=== 测试3 深市000001,股价0.5元 ===")
        for k, v in res3.items():
            print(f"{k}: {v}")
    except Exception as e:
        print("错误:", e)

    # 交互式输入版本(运行后手动输入)
    print("\n===== 交互式输入 =====")
    # stock_code = input("请输入6位股票代码:")
    # price = float(input("请输入买入单价:"))

    stock_code = '002229'
    # price = 9.5       # 3200 5.03
    price = 9.7     # 3200 5.13

    output = calc_min_shares(stock_code, price)
    for key, val in output.items():
        print(f"{key}: {val}")

我再预设一笔9.8和10,股价越高,可以买的股数逐渐减少从3200到3100(因为佣金总额高了)

但是如果差价过大:9.5元(3200股)和10元(3100股),股价不一样,

两种情况

以买入9.5元为主、3200股,则卖出10元 3200

以卖出10元为主、3100股,则买入9.5元 3100

低买,3200,高卖3200,佣金都大于5

高买,3100,低买3200,低买的佣金小于5(但是只是微微小于5)

以上需要分别输入买入价和卖出价,现在我要同时计算买入和卖出价对应的最大股数


'''
同时计算“买入价和卖出价*预设股数(100-10000)*佣金比例(沪0.0001843深0.0001654)”,当佣金正好大于等于5“,就确定用这个股数”
推算买入价最大股数,卖出价最大股数
豆包、阿夏
20260716
'''

def calc_min_shares(code: str, price: float) -> dict:
    """
    根据股票代码、价格,计算刚好佣金≥5元的最小股数(100~10000,100递增)
    :param code: 6位股票代码字符串
    :param price: 买入/卖出单价
    :return: 单组价格对应的计算结果字典
    """
    # 1. 校验股票代码
    if len(code) != 6 or not code.isdigit():
        raise ValueError("股票代码必须是6位纯数字")
    code_prefix = code[:2]

    # 2. 匹配市场佣金费率
    if code_prefix in ("60", "68"):
        market = "沪市"
        commission_rate = 0.0001843  # 0.1843‰
    elif code_prefix in ("00", "30"):
        market = "深市"
        commission_rate = 0.0001654  # 0.1654‰
    else:
        raise ValueError("仅支持60/68开头沪市、00/30开头深市A股代码")

    min_target_shares = None
    target_commission = 0.0
    target_amount = 0.0

    # 3. 遍历100~10000股,步长100
    for shares in range(100, 10001, 100):
        trade_amount = price * shares
        real_commission = trade_amount * commission_rate
        if real_commission >= 5:
            min_target_shares = shares
            target_amount = trade_amount
            target_commission = real_commission
            break

    # 4. 组装结果
    result = {
        # "股票代码": code,
        # "市场": market,
        # "佣金费率": f"{commission_rate * 1000}‰",
        "成交单价": round(price, 2),
        # "搜索区间": "100 ~ 10000股(100股递增)"
    }

    if min_target_shares is not None:
        result["满足佣金≥5最小股数"] = min_target_shares
        # result["对应成交总金额"] = round(target_amount, 2)
        # result["理论计算佣金"] = round(target_commission, 4)
        # result["实际收取佣金(保底5元)"] = max(5, round(target_commission, 2))
    else:
        result["提示"] = "100-10000股内全部佣金不足5元,统一收5元保底佣金"

    return result


# ---------------------- 测试调用 ----------------------
if __name__ == "__main__":
    # 测试案例
    try:
        stock_code = '002229'
        buy_price = 9.5    # 买入单价
        sell_price = 10.0  # 卖出单价

        # 分别计算买入、卖出两套数据
        buy_result = calc_min_shares(stock_code, buy_price)
        sell_result = calc_min_shares(stock_code, sell_price)

        print("==================== 买入计算结果 ====================")
        for k, v in buy_result.items():
            print(f"{k}: {v}")

        print("-" * 60)

        print("==================== 卖出计算结果 ====================")
        for k, v in sell_result.items():
            print(f"{k}: {v}")

    except Exception as e:
        print("程序异常:", e)

    print("\n===== 交互式手动输入模式 =====")
    try:
        # input_code = input("请输入6位股票代码:")
        # input_buy = float(input("请输入买入单价:"))
        # input_sell = float(input("请输入卖出单价:"))
        input_code = '002229'
        input_buy = 9.3
        input_sell = 10

        res_buy = calc_min_shares(input_code, input_buy)
        res_sell = calc_min_shares(input_code, input_sell)

        print("\n===== 手动输入-买入结果 =====")
        for k, v in res_buy.items():
            print(f"{k}: {v}")
        print("-" * 60)
        print("===== 手动输入-卖出结果 =====")
        for k, v in res_sell.items():
            print(f"{k}: {v}")
    except Exception as err:
        print("输入错误:", err)

(做多)低买股数 与高卖股数不一样

(做空)高卖股数 与低买股数不一样(低买的相同股数的佣金会小于5)。所以高卖可以多加100股

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐