-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_rules.py
More file actions
78 lines (61 loc) · 2.34 KB
/
test_rules.py
File metadata and controls
78 lines (61 loc) · 2.34 KB
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
import unittest
from typing import Mapping, Tuple
import pandas as pd
from portfolio import Portfolio
from rules import (
Balance,
Buy,
CashInterest,
ClosePosition,
Deposit,
Dividends,
Withdraw,
)
from utils import as_timestamp
from yfcache import Quote
def synthetic(cash: float, data: Mapping[str, float]) -> Tuple[Portfolio, Quote]:
p = Portfolio(cash)
q = Quote(pd.Timestamp.now(tz='UTC'), {
(ticker, 'Close'): value for ticker, value in data.items()
})
p.set_quote(q)
return (p, q)
def dividends(q: Quote, symbol: str, amount: float) -> Quote:
q.values[(symbol, 'Dividends')] = amount # type: ignore
return q
class TestRules(unittest.TestCase):
start = as_timestamp('2024-01-01')
def test_Buy(self):
p, q = synthetic(100.0, {'FOO': 10.0})
Buy(TestRules.start, 'D', 1, 'FOO', 1).execute(p, q)
self.assertEqual(p.position('FOO'), 1)
self.assertAlmostEqual(p.cash, 90.0)
def test_ClosePosition(self):
p, q = synthetic(100.0, {'FOO': 10.0})
p.set_position('FOO', 2)
ClosePosition(TestRules.start, 'D', 1, 'FOO').execute(p, q)
self.assertEqual(p.position('FOO'), 0)
self.assertAlmostEqual(p.cash, 120.0)
def test_Balance(self):
p, q = synthetic(100.0, {'FOO': 10.0, 'BAR': 5.0})
p.set_positions({'FOO': 0, 'BAR': 0})
Balance(TestRules.start, 'D', { 'FOO': 0.5, 'BAR': 0.5}).execute(p, q)
self.assertEqual(p.position('FOO'), 5)
self.assertEqual(p.position('BAR'), 10)
def test_Dividends(self):
p, q = synthetic(100.0, {'FOO': 2})
p.set_position('FOO', 1)
Dividends().execute(p, dividends(q, 'FOO', 10.0))
self.assertAlmostEqual(p.cash, 110.0)
def test_Deposit(self):
p, q = synthetic(100.0, { 'FOO': 1})
Deposit(TestRules.start, 'D', 1, 10.0).execute(p, q)
self.assertAlmostEqual(p.cash, 110.0)
def test_Withdraw(self):
p, q = synthetic(100.0, { 'FOO': 1})
Withdraw(TestRules.start, 'D', 1, 10.0).execute(p, q)
self.assertAlmostEqual(p.cash, 90.0)
def test_cashInterest(self):
p, q = synthetic(100.0, { 'FOO': 1})
CashInterest(0.12).execute(p, q)
self.assertAlmostEqual(p.cash, 101.0)