整数与小数
Python 日常使用两种数字类型。int 是整数,例如 200 股;float 是小数,例如价格 184.25。用 type() 可以查看一个值的类型。可数的东西(股数、手数、天数)用 int;价格、收益率和比率用 float。
shares = 200
price = 184.25
print(type(shares), type(price)) # <class 'int'> <class 'float'>三种除法
+、-、* 的行为与你预期一致。除法有三种形式。/ 总是返回 float,即使是 10 / 2(结果为 5.0)。// 是整除:先相除再向下取整为整数。% 返回余数。** 表示乘方。
# Division, floor division, remainder and power
print(7 / 2) # 3.5
print(7 // 2) # 3
print(7 % 2) # 1
print(2 ** 10) # 1024// 向负无穷方向取整,所以 -7 // 2 等于 -4,而不是 -3。对正数来说像是去掉小数部分,对负数则不是。最多能买几股整股?
整除回答的是“能放进去几次”。现金 1,000、价格 184.25 时,cash // price 就是能买的整股数,cash - shares * price 是剩余现金。对 float 使用 // 返回的仍是 float(5.0),需要真正的个数时用 int() 包起来。
# Whole shares for a cash budget, and the cash left over
cash, price = 1000, 184.25
shares = int(cash // price)
left = cash - shares * price
print(shares, left) # 5 78.75float 只是近似值
float 以二进制保存数字,而 0.1 这样的大多数小数没有精确的二进制表示。Python 保存最接近的值,因此会出现极小的误差。每种语言都是如此,并不是 Python 的 bug。量化开发的规则是:永远不要用 == 比较 float,而要用允许微小误差的 math.isclose。
# Floats are approximate: compare with isclose, not ==
import math
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
print(math.isclose(0.1 + 0.2, 0.3)) # True按最小报价单位取整
round(x, n) 保留 n 位小数。交易所只接受落在最小报价单位(tick)上的价格(例如每 0.05 一档),所以先除以 tick,取整为整数个 tick,再乘回去。另外要注意,round 遇到恰好一半时会取最近的偶数:round(2.5) 是 2,round(3.5) 是 4。
# Snap a price to the nearest 5-cent tick
price, tick = 184.267, 0.05
ticks = round(price / tick)
print(ticks, ticks * tick) # 3685 184.25
print(round(2.5), round(3.5)) # 2 4用整数分来表示金额
由于 float 只是近似值,需要精确的系统会把金额存成整数分。转换方法是乘以 100 并四舍五入。int() 只会截掉小数部分,所以实际为 1998.9999999999998 的 19.99 * 100 会丢掉一分钱。
# Dollars to integer cents: round, do not truncate
amount = 19.99
print(amount * 100) # 1998.9999999999998
print(int(amount * 100)) # 1998 (a cent is lost)
print(round(amount * 100)) # 1999- 计数(股数、手数、天数):
int。 - 价格、收益率和比率:
float,用math.isclose比较。 - 精确的金额:整数分(或
decimal模块)。
下一节:字符串与 f-string,把这些数字变成 AAPL 184.25 x 184.50 这样易读的文本。
实验:评分内容
- 用
shares_for_cash计算预算能买的整股数25 分 - 用
leftover_cash求剩余现金25 分 - 用
round_to_tick把价格对齐到最近的 tick25 分 - 用
cents把美元换算成精确的整数分25 分