Вам нужно 2 типа объектов: Portfolio
и Stock
.
A User
может иметь несколько Portfolio
, и в примере представлено только его именем.
Для более сложной модели вы также можете смоделировать Transactions
как объекты; Вам также нужно будет обрабатывать колебания цен акций, комиссий и других расходов.
Вот упрощенный пример, который демонстрирует, как объекты взаимодействуют друг с другом:
class Stock:
def __init__(self, ticker, price):
assert price > 0
self.ticker = ticker
self.price = price
def __hash__(self):
return hash(self.ticker)
def __str__(self):
return self.ticker + ', $' + str(self.price) + ':'
class Portfolio:
def __init__(self, owner):
self.owner = owner
self.cash = 0
self.stocks = {} # a mapping of Stock --> quantity
def buy(self, stock, quantity):
if self.cash < stock.price * quantity:
print('Not enough cash to purchase ', quantity, stock)
else:
self.cash -= stock.price * quantity
try:
self.stocks[stock] += quantity
except KeyError:
self.stocks[stock] = quantity
def sell(self, stock, quantity):
assert quantity > 0
try:
if self.stocks[stock] < quantity:
print('Not enough', stock.ticker, 'inventory to sell', str(quantity), stock)
return
self.stocks[stock] -= quantity * stock.price
self.cash += quantity * stock.price
except KeyError:
print('No', stock.ticker, 'inventory to sell')
def __str__(self):
res = [self.owner, "'s Portfolio:\n"]
for stock, quantity in self.stocks.items():
res += [str(stock), ' ', str(quantity), ' -> ', '$', str(quantity*stock.price), '\n']
res += ['cash: ', '$', str(self.cash), '\n']
return ''.join(res)
goog = Stock('GOOG', 325)
alibaba = Stock('ALI', 12)
apple = Stock('AAPL', 42)
pfl = Portfolio('Karin')
pfl.cash = 10000
pfl.buy(goog, 10)
pfl.buy(alibaba, 100)
pfl.sell(apple, 100)
pfl.buy(apple, 10000)
pfl.sell(goog, 10000)
print()
print(pfl)
выход:
No AAPL inventory to sell
Not enough cash to purchase 10000 AAPL, $42:
Not enough GOOG inventory to sell 10000 GOOG, $325:
Karin's Portfolio:
GOOG, $325: 10 -> $3250
ALI, $12: 100 -> $1200
cash: $5550