假设买入和卖出记录都是以字符串形式给出,每条记录包括股票代码、交易类型(买入/卖出)、交易数量和交易价格。我们可以先将记录转化为一个列表,然后遍历这个列表,根据交易类型更新股票持仓。

以下是一个可能的实现:

records = [
    "AAPL,Buy,100,120.0",
    "AAPL,Sell,50,130.0",
    "GOOG,Buy,200,110.0",
    "AAPL,Buy,50,125.0",
    "GOOG,Sell,100,120.0"
]

holdings = {}  # 用字典来记录股票持仓

for record in records:
    code, action, quantity, price = record.split(',')
    quantity = int(quantity)
    price = float(price)
    
    if code not in holdings:
        holdings[code] = 0
        
    if action == 'Buy':
        holdings[code] += quantity
    elif action == 'Sell':
        holdings[code] -= quantity
        
print(holdings)

输出结果为:

{'AAPL': 100, 'GOOG': 100}

表示最终持有100股AAPL和100股GOOG。

有一长串买入买出记录写一个python程序处理上述记录根据买入卖出的记录计算出最终持仓

原文地址: https://www.cveoy.top/t/topic/CwC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录