感谢楼主分享(已经给楼主加米)
抛砖引玉了,大致想法是,根据buy transaction构建一个queue, FIFO,
每次卖的时候,
- 如果队列的第一个buy_transaction够卖,就卖指定的数额,更新第一个buy_transaction
- 如果不够卖,出队列,然后去下一个buy_transaction,直到卖到指定的数额或者队列为空- from collections import deque
- class Transaction:
-
- def __init__(self, date: int, amount: int, price: float, type: str) -> None:
- self.date = date
- self.amount = amount
- self.unit_price = price / amount
- self.type = type
-
- def __str__(self) -> str:
- return "date=" + self.date + ", amount=" + self.amount + ", unit_price=" + self.unit_price
-
- def print_sell(buy_transaction, sell_transaction, amount_sold) -> str:
- proceeds = sell_transaction.unit_price * amount_sold
- gain = amount_sold * (sell_transaction.unit_price - buy_transaction.unit_price)
- info = "sell(date=" + str(sell_transaction.date) + ", date_acquire=" + str(buy_transaction.date) + ", amount=" + str(amount_sold) + ", proceeds=" + str(proceeds) + ", gain=" + str(gain)
- print(info)
-
- def handle_buy_transaction(positions: deque, transaction: Transaction) -> None:
- positions.append(transaction)
- def handle_sell_transaction(positions: deque, transaction: Transaction) -> None:
- if transaction.type != "sell":
- return
-
- sell_amount = transaction.amount
-
- while sell_amount > 0 and len(positions) > 0:
- first_trans = positions[0]
- if first_trans.amount > sell_amount:
- # this transaction has enough amount to sell
- print_sell(first_trans, transaction, sell_amount)
- first_trans.amount = first_trans.amount - sell_amount
- sell_amount = 0 # we don't need to sell anymore
- else:
- # this transaction doesn't have enough amount to sell
- print_sell(first_trans, transaction, first_trans.amount)
- first_trans = positions.popleft()
- sell_amount = sell_amount - first_trans.amount # we still need to sell
-
- def statement(inputs):
- # a queue of all 'buy' transactions
- positions = deque([])
-
- for input in inputs:
- # 1. build transaction
- transaction = Transaction(input["date"], input["amount"], input["price"], input["type"])
-
- # 2. handle transaction
- if input['type'] == "buy":
- handle_buy_transaction(positions, transaction)
- elif input["type"] == "sell":
- handle_sell_transaction(positions, transaction)
-
- ###################################
- ## Execution starts here
- ###################################
- inputs = [
- {"date": 1, "amount": 5, "price": 25.0, "type": "buy"},
- {"date": 2, "amount": 20, "price": 60.0, "type": "buy"},
- {"date": 3, "amount": 7, "price": 42.0, "type": "sell"},
- {"date": 4, "amount": 6, "price": 30.0, "type": "sell"},
- {"date": 5, "amount": 5, "price": 25.0, "type": "buy"},
- {"date": 6, "amount": 5, "price": 25.0, "type": "buy"},
- ]
- statement(inputs)
复制代码 |