Test coverage report: forex.models

# forex.models: 129 total statements, 95.8% covered

Generated: Mon 2015-06-08 11:27 AST

Source file: /home/kevin/Development/custom apps/valuehorizon-forex/forex/models.py

Stats: 113 executed, 5 missed, 11 excluded, 98 ignored

1. `from django.db import models`
2. `from django.db.models import Manager`
3. `from django.core.validators import MinValueValidator, ValidationError`
4. ``
5. `# Import misc packages`
6. `import numpy as np`
7. `from datetime import date, timedelta`
8. `from decimal import Decimal`
9. `from pandas import DataFrame, date_range`
10. ``
11. `PRICE_PRECISION = 4`
12. `DATEFRAME_START_DATE = date(2005,1,1)`
13. ``
14. ``
15. `class Currency(models.Model):`
16. `"""`
17. `Represents a currency according to ISO 4217 standards.`
18. `"""`
19. ``
20. `name = models.CharField(max_length=255)`
21. `symbol = models.CharField(max_length=10, unique=True)`
22. `ascii_symbol = models.CharField(max_length=20, null=True, blank=True)`
23. `num_code = models.IntegerField(null=True, blank=True)`
24. `digits = models.IntegerField(null=True, blank=True) # Digits after decimal (minor unit)`
25. `description = models.TextField(blank=True)`
26. ``
27. `# Cached Data`
28. `date_modified = models.DateTimeField(null=True, blank=True, editable=False, auto_now=True)`
29. `date_created = models.DateTimeField(null=True, blank=True, editable=False, auto_now_add=True)`
30. ``
31. `class Meta:`
32. `verbose_name_plural = 'Currencies'`
33. `verbose_name = 'Currency'`
34. `ordering = ['name', 'symbol']`
35. ``
36. `def __unicode__(self):`
37. `return u'%s, %s' % (unicode(self.name), unicode(self.symbol))`
38. ``
39. `def generate_dataframe(self, start_date=None, end_date=None):`
40. `"""`
41. `"""`
42. `first_series_point = CurrencyPrice.objects.filter(currency=self)[0]`
43. `last_series_point = CurrencyPrice.objects.filter(currency=self).reverse()[0]`
44. `start_date = first_series_point.date if start_date == None else max(first_series_point.date, start_date)`
45. `temp_start_date = start_date - timedelta(days=3) # Add lag`
46. `end_date = last_series_point.date if end_date == None else min(last_series_point.date, end_date)`
47. ``
48. `currency_date = CurrencyPrice.objects.filter(currency=self, date__gte=temp_start_date, date__lte=end_date).values_list('date', 'ask_price', 'bid_price')`
49. `currency_data_array = np.core.records.fromrecords(currency_date, names=['DATE', "ASK", "BID"])`
50. `df = DataFrame.from_records(currency_data_array, index='DATE').astype(float)`
51. `df['MID'] = (df['ASK'] + df['BID']) / 2.0`
52. `df['CHANGE'] = df['MID'].pct_change()`
53. ``
54. `required_dates = date_range(start_date,end_date)`
55. `df = df.reindex(required_dates)`
56. `df = df.fillna(method='ffill')`
57. ``
58. `return df`
59. ``
60. ``
61. ``
62. `class CurrencyPriceManager(Manager):`
63. `""" Adds some added functionality """`
64. ``
65. `def generate_dataframe(self, symbols=None, date_index=None, price_type="mid"):`
66. `"""`
67. `Generate a dataframe consisting of the currency prices (specified by symbols)`
68. `from the start to end date`
69. `"""`
70. ``
71. `# Set defaults if necessary`
72. `if symbols == None:`
73. `symbols = list(Currency.objects.all().values_list('symbol', flat=True))`
74. `try:`
75. `start_date = date_index[0]`
76. `end_date = date_index[-1]`
77. `except:`
78. `start_date = DATEFRAME_START_DATE`
79. `end_date = date.today()`
80. `date_index = date_range(start_date, end_date)`
81. ``
82. `currency_price_data = CurrencyPrice.objects.filter(currency__symbol__in=symbols,`
83. `date__gte=date_index[0],`
84. `date__lte=date_index[-1]).values_list('date', 'currency__symbol', 'ask_price', 'bid_price')`
85. `try:`
86. `forex_data_array = np.core.records.fromrecords(currency_price_data, names=['date', 'symbol', 'ask_price', 'bid_price'])`
87. `except IndexError:`
88. `forex_data_array = np.core.records.fromrecords([(date(1900,1,1) , "", 0, 0)], names=['date', 'symbol', 'ask_price', 'bid_price'])`
89. `df = DataFrame.from_records(forex_data_array, index='date')`
90. ``
91. `df['date'] = df.index`
92. ``
93. `if price_type == "mid":`
94. `df['price'] = (df['ask_price'] + df['bid_price']) / 2`
95. `elif price_type == "ask_price":`
96. `df['price'] = df['ask_price']`
97. `elif price_type == "bid_price":`
98. `df['price'] = df['bid_price']`
99. `else:`
100. `raise ValueError("price_type must be on of 'ask', 'bid' or 'mid'")`
101. ``
102. `df = df.pivot(index='date', columns='symbol', values='price')`
103. `df = df.reindex(date_index)`
104. `df = df.fillna(method="ffill")`
105. `unlisted_symbols = list(set(symbols) - set(df.columns))`
106. `for unlisted_symbol in unlisted_symbols:`
107. `df[unlisted_symbol] = np.nan`
108. `df = df[symbols]`
109. ``
110. `return df`
111. ``
112. ``
113. `class CurrencyPrice(models.Model):`
114. `"""`
115. `Represents a currency price to US`
116. `"""`
117. ``
118. `currency = models.ForeignKey(Currency)`
119. `date = models.DateField()`
120. ``
121. `# Price Data per $1 of US`
122. `ask_price = models.DecimalField(max_digits=20, decimal_places=PRICE_PRECISION,`
123. `validators=[MinValueValidator(Decimal('0.00'))])`
124. `bid_price = models.DecimalField(max_digits=20, decimal_places=PRICE_PRECISION,`
125. `validators=[MinValueValidator(Decimal('0.00'))],`
126. `blank=True, null=True)`
127. ``
128. `# Cached Data`
129. `date_modified = models.DateTimeField(null=True, blank=True, editable=False, auto_now=True)`
130. `date_created = models.DateTimeField(null=True, blank=True, editable=False, auto_now_add=True)`
131. ``
132. `# Add custom managers`
133. `objects=CurrencyPriceManager()`
134. ``
135. `class Meta:`
136. `verbose_name_plural = 'Currency Prices'`
137. `verbose_name = 'Currency Price'`
138. `ordering = ['date', ]`
139. `unique_together=['date', 'currency']`
140. `get_latest_by = "date"`
141. ``
142. `def __unicode__(self):`
143. `return u'%s, %s' % (unicode(self.currency),`
144. `unicode(self.date),)`
145. ``
146. `def save(self, *args, **kwargs):`
147. `"""`
148. `Sanitation checks`
149. `"""`
150. `if self.ask_price < 0:`
151. `raise ValidationError("Ask price must be greater than zero")`
152. `if self.bid_price < 0:`
153. `raise ValidationError("Bid price must be greater than zero")`
154. `if self.ask_price < self.bid_price:`
155. `raise ValidationError("Ask price must be at least Bid price")`
156. ``
157. `super(CurrencyPrice, self).save(*args, **kwargs) # Call the "real" save() method.`
158. ``
159. `@property`
160. `def mid_price(self):`
161. `"""`
162. `Compute the mid point between the bid and ask prices`
163. `"""`
164. `return (self.ask_price + self.bid_price) / Decimal('2.0')`
165. ``
166. `@property`
167. `def spread(self):`
168. `"""`
169. `Compute the difference between bid and ask prices`
170. `"""`
171. `return (self.ask_price - self.bid_price)`
172. ``
173. `@property`
174. `def ask_price_us(self):`
175. `"""`
176. `Calculate the ask_price in USD. This is the inverse`
177. `of the ask price.`
178. `"""`
179. `if self.ask_price != 0:`
180. `return 1 / Decimal(str(self.ask_price))`
181. `else:`
182. `raise ZeroDivisionError('Ask price is zero')`
183. ``
184. `@property`
185. `def bid_price_us(self):`
186. `"""`
187. `Calculate the bid_price in USD. This is the inverse`
188. `of the bid price.`
189. `"""`
190. `if self.bid_price != 0:`
191. `return 1 / Decimal(str(self.bid_price))`
192. `else:`
193. `raise ZeroDivisionError('Bid price is zero')`
194. ``
195. ``
196. ``
197. ``
198. `def convert_currency(from_symbol, to_symbol, value, date):`
199. `"""`
200. `"""`
201. `if from_symbol == to_symbol:`
202. `return value`
203. ``
204. ``
205. `from_currency = Currency.objects.get(symbol=from_symbol)`
206. `try:`
207. `from_currency_price = CurrencyPrice.objects.get(currency=from_currency, date=date).mid_price`
208. `except CurrencyPrice.DoesNotExist:`
209. `print "Cannot fetch prices for %s on %s" % (str(from_currency), str(date))`
210. `return None`
211. ``
212. `to_currency = Currency.objects.get(symbol=to_symbol)`
213. `try:`
214. `to_currency_price = CurrencyPrice.objects.get(currency=to_currency, date=date).mid_price`
215. `except CurrencyPrice.DoesNotExist:`
216. `print "Cannot fetch prices for %s on %s" % (str(to_currency), str(date))`
217. `return None`
218. ``
219. `if type(value) == float:`
220. `output = (value / float(from_currency_price)) * float(to_currency_price)`
221. `elif type(value) == Decimal:`
222. `output = Decimal(format((value / from_currency_price) * to_currency_price, '.%sf' % str(PRICE_PRECISION)))`
223. `else:`
224. `output = None`
225. ``
226. `return output`
227. ``