1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
| class TradingAccount:
"""基本交易帳戶"""
def __init__(self, owner, cash):
self.owner = owner
self._cash = cash
self._holdings = {} # {股票代號: 持有股數}
self._trades = [] # 交易紀錄
@property
def cash(self):
return self._cash
@property
def holdings(self):
return dict(self._holdings) # 回傳副本,防止外部直接修改
def buy(self, symbol, shares, price):
cost = shares * price
if cost > self._cash:
raise ValueError(f"現金不足:需要 {cost:,},現有 {self._cash:,}")
self._cash -= cost
self._holdings[symbol] = self._holdings.get(symbol, 0) + shares
self._trades.append(("買入", symbol, shares, price))
print(f"買入 {symbol} {shares} 股 @ {price},現金剩餘:{self._cash:,.0f}")
def sell(self, symbol, shares, price):
if self._holdings.get(symbol, 0) < shares:
raise ValueError(f"{symbol} 持股不足")
self._cash += shares * price
self._holdings[symbol] -= shares
if self._holdings[symbol] == 0:
del self._holdings[symbol]
self._trades.append(("賣出", symbol, shares, price))
print(f"賣出 {symbol} {shares} 股 @ {price},現金剩餘:{self._cash:,.0f}")
def portfolio(self, current_prices):
total = self._cash
print(f"\n===== {self.owner} 的投資組合 =====")
print(f"現金:{self._cash:>12,.0f}")
for symbol, shares in self._holdings.items():
price = current_prices.get(symbol, 0)
value = shares * price
total += value
print(f"{symbol}:{shares} 股 × {price:,} = {value:>10,.0f}")
print(f"{'─' * 30}")
print(f"總資產:{total:>10,.0f}")
def __str__(self):
return f"TradingAccount({self.owner}, 現金={self._cash:,.0f})"
class MarginAccount(TradingAccount):
"""融資帳戶(繼承自 TradingAccount,可用槓桿)"""
def __init__(self, owner, cash, leverage=2):
super().__init__(owner, cash)
self.leverage = leverage # 槓桿倍數
@property
def buying_power(self):
"""可用買力 = 現金 × 槓桿"""
return self._cash * self.leverage
def buy(self, symbol, shares, price):
cost = shares * price
if cost > self.buying_power:
raise ValueError(f"超過買力上限:{self.buying_power:,}")
# 直接操作父類別的私有屬性需透過方法
# 這裡簡化為:只扣實際持有的現金比例
actual_cost = cost / self.leverage
self._cash -= actual_cost
self._holdings[symbol] = self._holdings.get(symbol, 0) + shares
self._trades.append(("買入(融資)", symbol, shares, price))
print(f"融資買入 {symbol} {shares} 股 @ {price},買力剩餘:{self.buying_power:,.0f}")
# 一般帳戶
acc = TradingAccount("Alice", 100_000)
acc.buy("2330", 10, 950)
acc.buy("0050", 20, 150)
acc.sell("2330", 5, 1_000)
current_prices = {"2330": 1_000, "0050": 155}
acc.portfolio(current_prices)
print()
# 融資帳戶
margin = MarginAccount("Bob", 50_000, leverage=2)
print(f"買力:{margin.buying_power:,}") # 100,000
margin.buy("2330", 5, 950)
|