Skip to content

Commit e8433fa

Browse files
author
Siddharta Govindaraj
committed
PriceRule + tests
1 parent 0e99c63 commit e8433fa

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

stock_alerter/rule.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class PriceRule:
2+
"""PriceRule is a rule that triggers when a stock price satisfies a
3+
condition (usually greater, equal or lesser than a given value)"""
4+
5+
def __init__(self, symbol, condition):
6+
self.symbol = symbol
7+
self.condition = condition
8+
9+
def matches(self, exchange):
10+
try:
11+
stock = exchange[self.symbol]
12+
except KeyError:
13+
return False
14+
return self.condition(stock) if stock.price else False
15+
16+
def depends_on(self):
17+
return {self.symbol}

stock_alerter/tests/test_rule.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import unittest
2+
from datetime import datetime
3+
4+
from ..stock import Stock
5+
from ..rule import PriceRule
6+
7+
8+
class PriceRuleTest(unittest.TestCase):
9+
@classmethod
10+
def setUpClass(cls):
11+
goog = Stock("GOOG")
12+
goog.update(datetime(2014, 2, 10), 11)
13+
cls.exchange = {"GOOG": goog}
14+
15+
def test_a_PriceRule_matches_when_it_meets_the_condition(self):
16+
rule = PriceRule("GOOG", lambda stock: stock.price > 10)
17+
self.assertTrue(rule.matches(self.exchange))
18+
19+
def test_a_PriceRule_is_False_if_the_condition_is_not_met(self):
20+
rule = PriceRule("GOOG", lambda stock: stock.price < 10)
21+
self.assertFalse(rule.matches(self.exchange))
22+
23+
def test_a_PriceRule_is_False_if_the_stock_is_not_in_the_exchange(self):
24+
rule = PriceRule("MSFT", lambda stock: stock.price > 10)
25+
self.assertFalse(rule.matches(self.exchange))
26+
27+
def test_a_PriceRule_is_False_if_the_stock_hasnt_got_an_update_yet(self):
28+
self.exchange["AAPL"] = Stock("AAPL")
29+
rule = PriceRule("AAPL", lambda stock: stock.price > 10)
30+
self.assertFalse(rule.matches(self.exchange))
31+
32+
def test_a_PriceRule_only_depends_on_its_stock(self):
33+
rule = PriceRule("MSFT", lambda stock: stock.price > 10)
34+
self.assertEqual({"MSFT"}, rule.depends_on())

0 commit comments

Comments
 (0)