I’m trying to build a financial app in Django.
The goal of the app is: A user will have the ability to save a portfolio to the database, and the app will run different types of financial metrics on the data, as standard deviation, beta, alpha, ect…
The issue I’m facing is that the number of stocks a user has in their portfolio is different for each user. A user who is a risk-averse investor would maybe have ten stocks, while an investor who is trading in the short term might only have 2-3 stocks in the portfolio.
Each transaction consists of 5 elements: the direction the user has traded, either “long” or “short.” The ticker, volume of the trade, price paid, and the transaction date.
So, for example, a user has three stocks the transactions would look something like this: Transaction example
How can I give the user the ability to choose how many stocks they would like to record in the portfolio?
My code:
models.py
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
class Portfolio(models.Model):
direction_option = (
('Long','Long'),
('Short','Short')
)
portfolio_name = models.CharField(max_length=200)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
direction = models.CharField(max_length=200, null=True, choices=direction_option)
ticker = models.CharField(max_length=10, null=True)
volume = models.CharField(max_length=10, null=True)
price = models.FloatField(null=True)
transaction_date = models.DateField(null=True)
def __str__(self):
return self.portfolio_name
Forms.py
from django import forms
from django.forms import ModelForm
from .models import *
class DateInput(forms.DateInput):
input_type = 'date'
class PortfolioForm(ModelForm):
class Meta:
model = Portfolio
fields = ['portfolio_name','direction','ticker','volume','price','transaction_date']
widgets = {
'transaction_date':DateInput(),
}
Views.py
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from .forms import PortfolioForm
from .models import Portfolio
from django.contrib.auth.models import User
@login_required
def portfolio(request):
form = PortfolioForm()
if request.method == 'POST':
#print('Printing post', request.POST)
form = PortfolioForm(request.POST)
if form.is_valid():
instace = form.save(commit=False)
instace.user = request.user
instace.save()
#form.save()
return redirect('../')
context = {'form' : form}
return render(request, 'backapp/portfolio.html', context)
FYI: I’m a little new to Django.