Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wiseplat
GitHub Repository: wiseplat/python-code
Path: blob/master/ invest-robot-contest_investRobot-master/robotlib/money.py
5929 views
1
from __future__ import annotations
2
3
import math
4
5
from dataclasses import dataclass
6
from tinkoff.invest import MoneyValue, Quotation
7
8
9
@dataclass(init=False, order=True)
10
class Money:
11
units: int
12
nano: int
13
MOD: int = 10 ** 9
14
15
def __init__(self, value: int | float | Quotation | MoneyValue, nano: int = None):
16
if nano:
17
assert isinstance(value, int), 'if nano is present, value must be int'
18
assert isinstance(nano, int), 'nano must be int'
19
self.units = value
20
self.nano = nano
21
else:
22
match value:
23
case int() as value:
24
self.units = value
25
self.nano = 0
26
case float() as value:
27
self.units = int(math.floor(value))
28
self.nano = int((value - math.floor(value)) * self.MOD)
29
case Quotation() | MoneyValue() as value:
30
self.units = value.units
31
self.nano = value.nano
32
case _:
33
raise ValueError(f'{type(value)} is not supported as initial value for Money')
34
35
def __float__(self):
36
return self.units + self.nano / self.MOD
37
38
def to_float(self):
39
return float(self)
40
41
def to_quotation(self):
42
return Quotation(self.units, self.nano)
43
44
def to_money_value(self, currency: str):
45
return MoneyValue(currency, self.units, self.nano)
46
47
def __add__(self, other: Money) -> Money:
48
print(self.units + other.units + (self.nano + other.nano) // self.MOD)
49
print((self.nano + other.nano) % self.MOD)
50
return Money(
51
self.units + other.units + (self.nano + other.nano) // self.MOD,
52
(self.nano + other.nano) % self.MOD
53
)
54
55
def __neg__(self) -> Money:
56
return Money(-self.units, -self.nano)
57
58
def __sub__(self, other: Money) -> Money:
59
return self + -other
60
61
def __mul__(self, other: int) -> Money:
62
return Money(self.units * other + (self.nano * other) // self.MOD, (self.nano * other) % self.MOD)
63
64
def __str__(self) -> str:
65
return f'<Money units={self.units} nano={self.nano}>'
66
67