Django Models for Time Series Data Django Models for Time Series Data database database

Django Models for Time Series Data


You separate into 3 data models:

  • The model for the stock, having links to histories and current price and amount, as well as metadata
  • The model for the purchase history
  • The model for the price history

The three are linked with foreign keys from the stock model. Example code:

from django.db import modelsfrom django.util.translation import ugettext_lazy as _from datetime import dateclass StockAsset(models.Model):    symbol = models.CharField(max_length=5)    amount = models.PositiveIntegerField()    price = models.FloatField()class PurchaseHistory(models.Model):    BUY = 1    SELL = 2    ACTION_CHOICES = (        (BUY, _('buy')),        (SELL, _('sell')),    )    action = models.PositiveIntegerField(choices=ACTION_CHOICES)    action_date = models.DateTimeField(auto_now_add=True)    stock = models.ForeignKey(StockAsset,        on_delete=models.CASCADE, related_name='purchases'    )class PriceHistory(models.Model):    stock = models.ForeignKey(StockAsset, on_delete=models.CASCADE, related_name='price_history')    price_date = models.DateField(default=date.today)

This way you can access all from the StockAsset model. Start reading here.

For this, the type of database to pick is not really important. If you have no preference, go with PostgreSQL.


If you care only about date, and not timestamp of every tick of price changethen django-simple-history is a way to go.

You just update value (a price) and saving it in time series in a different table is up to that library, not even need to define a date field.

class StockAsset(models.Model):    history = HistoricalRecords()    symbol = models.CharField(...)    price = models.DecimalField(max_digit=8, decimal_places=2)