1 from django.db import models
4 class Person (models.Model):
5 name = models.CharField('name', max_length=200)
8 return unicode(self.name)
11 class Exchange (models.Model):
12 name = models.CharField(max_length=200)
13 symbol = models.CharField(max_length=10)
15 def __unicode__(self):
16 return unicode(self.name)
19 class Company (models.Model):
20 name = models.CharField(max_length=200)
22 def __unicode__(self):
23 return unicode(self.name)
26 class Ticker (models.Model):
27 symbol = models.CharField(max_length=10)
28 company = models.ForeignKey(Company)
29 exchange = models.ForeignKey(Exchange)
31 def __unicode__(self):
32 return u'{0.exchange.symbol}:{0.symbol}'.format(self)
35 class Transaction (models.Model):
36 person = models.ForeignKey(Person)
37 date = models.DateTimeField()
38 ticker = models.ForeignKey(Ticker)
39 shares = models.IntegerField('number of shares')
41 # If you want to track values in several currencies, check out the
42 # python-money package: http://code.google.com/p/python-money/
43 value = models.DecimalField(
44 'value in US dollars', max_digits=20, decimal_places=2)
46 source = models.CharField(max_length=200) # ideally a permalink
48 def __unicode__(self):
49 return (u'{0.person} traded {0.shares} shares (${0.value}) '
50 'of {0.ticker} on {0.date}').format(self)
53 def add_transaction(person, date, exchange, exchange_symbol, company,
54 company_symbol, shares, value, source):
55 if not value and not shares:
56 return # not a transaction (insider just declaring holdings?)
58 person = Person.objects.get(name__iexact=person)
59 except Person.DoesNotExist:
60 person = Person(name=person)
61 print('adding new person {}'.format(person))
64 exchange = Exchange.objects.get(symbol__iexact=exchange_symbol)
65 except Exchange.DoesNotExist:
66 exchange = Exchange(name=exchange, symbol=exchange_symbol)
67 print('adding new exchange {}'.format(exchange))
70 tickers = Ticker.objects.filter(symbol__iexact=company_symbol)
71 ticker = tickers.get(exchange__id=exchange.id)
72 except Ticker.DoesNotExist:
74 company = Company.objects.get(name__iexact=company)
75 except Company.DoesNotExist:
76 company = Company(name=company)
77 print('adding new company {}'.format(company))
79 ticker = Ticker(exchange=exchange, company=company,
80 symbol=company_symbol)
81 print('adding new ticker {}'.format(ticker))
83 company = ticker.company
85 transactions = Transaction.objects.filter(person__id=person.id)
86 transactions = transactions.filter(ticker__id=ticker.id)
87 transactions = transactions.filter(date=date)
88 transactions = transactions.filter(shares=shares)
89 transaction = transactions.get(value=value)
90 except Transaction.DoesNotExist:
91 transaction = Transaction(
98 print('adding new transaction {}'.format(transaction))