SoFunction
Updated on 2025-03-02

Tutorial on using Django to build a fund simulation trading system

Teach you how to build a fund simulation system (based on Django framework)

first step:Create projects, apps, and static file storage folders

django-admin startproject Chongyang
django-admin startapp Stock # ChongyangOperations in folders

Create statics and templates folders in chongyang project

Step 2:Configuration File

INSTALLED_APPS = [
 '',
 '',
 '',
 '',
 '',
 '',
 'Stock' # Add your own APP name] 

TEMPLATES = [
 {
 'BACKEND': '',
 'DIRS': [(BASE_DIR, 'templates')], # Static folder address (must be configured) 'APP_DIRS': True,
 'OPTIONS': {
  'context_processors': [
  '.context_processors.debug',
  '.context_processors.request',
  '.context_processors.auth',
  '.context_processors.messages',
  ],
 },
 },
]

# Database configuration (using default sqlite)DATABASES = {
 'default': {
 'ENGINE': '.sqlite3',
 # 'NAME': (BASE_DIR, 'db.sqlite3'),
 'NAME': (BASE_DIR, ''),
 }
 }

LANGUAGE_CODE = 'zh-hans' # ChineseTIME_ZONE = 'Asia/Shanghai' # Time zone
STATIC_URL = '/static/'  # Static file configurationSTATICFILES_DIRS = [
 (BASE_DIR, 'statics'), # Specific path (BASE_DIR, 'templates'),
]

Step 3:Run the project

python  runserver 0.0.0.0:8000

So far, you have created a web site with extremely large functions, and you only need to activate the corresponding service in the future.

 #Routing configuration file # Function implementation file # Backend management files # Database creation file

Step 4:Specific project configuration

After configuring the previous settings, just copy the following code in the corresponding file to run the project

1、

from  import models
import uuid

# Fund Manager Data Sheetclass Fund_Manger():
 name = (max_length=20)
 age = ()
 entry_time = (max_length=20)
 def __str__(self):
 return 

# Stock information data tableclass Stock():
 stock_name = (max_length=20)
 code = (max_length=10)
 def __str__(self):
 return 

# Trading System Tableclass Trading():
 name = (max_length=20)
 time = ()
 code = (max_length=10)
 number = ()
 price = (max_length=10)
 operate = (max_length=10)
 total_price = (max_length=20)

# Clearing data tableclass Fund_pool():
 time = ()
 total_pool = (max_length=30)
 oprate_people = (max_length=10)
 people_num = ()
 def __str__(self):
 return self.total_pool

2、

from  import admin
from  import path
from  import url
from Stock import views

urlpatterns = [
 path('admin/', ),
 url(r'^$', ),
 url(r'^data_entry/$', views.data_entry, name='data_entry'),
 url(r'^add_fund_manger/$', views.add_fund_manger),
 url(r'^add_stock/$', views.add_stock),
 url(r'^check$', views.check_index, name='check'),
 url(r'^trading/$', ),
 url(r'^trading_success/$', ),
 url(r'^fund_pool/$', views.Fund_pool_, name='fund_pool'),
 url(r'^account/$', )
]

3、

from  import render
from  import HttpResponse
from  import timezone
from  import Fund_Manger, Stock, Trading, Fund_pool
import re


def index(request):
 return render(request, '')

def data_entry(request):
 return render(request, 'data_entry.html')

def check_index(request):
 return render(request, '')

def add_fund_manger(request):
 '''
  When adding, you need to determine whether the original table already has this user information.
  Age limit is also added (20~40)
  '''
 if  == "POST":
 name = ['name']
 age = ['age']
 entry_time = ['Time']
 check_name = Fund_Manger.(name=name)
 if check_name:
  return HttpResponse("<center><h1>This user is already in!</h1></center>")
 else:
  if int(age) &lt; 20 or int(age) &gt;= 40:
  return HttpResponse("<center><h1>This user does not meet the requirements!</h1></center>")
  else:
  Mas = Fund_Manger(name=name, age=age, entry_time=entry_time)
  ()
  return HttpResponse("<center><h1>User registration successfully!</h1></center>")

def add_stock(request):
 '''
  When adding fund pool data, you need to limit the stock code.
  Only for the A-share market, exception capture processing is performed at the same time
  '''
 if  == "POST":
 stock_name = ['stock_name']
 post_code = ['code']
 # Filter transaction codes (digits with length 6 starting with 0, 3, 6) pattern = (r'000[\d+]{3}$|^002[\d+]{3}$|^300[\d+]{3}$|^600[\d+]{3}$|^601[\d+]{3}$|^603[\d+]{3}$')
 code = (post_code)
 #Exception handling try:
  num = code[0].__len__()
  if num == 6:
  Mas = Stock(stock_name=stock_name, code=code[0])
  ()
  return HttpResponse("<center><h1>Fund pool data was added successfully!</h1></center>")
  else:
  return HttpResponse("<center><h1>Error code!</h1></center>")

 except Exception as e:
  return HttpResponse("<center><h1>Error code!</h1></center>")

def check(request):
 '''
  Information compliance query (A-share data only)
  A fund manager, stock code, and transaction quantity need to be judged simultaneously
  '''
 if  == "POST":
 name = ['name']
 code = ['code']
 number = ['number']
 # Fund manager information filtering try:
  check_name = Fund_Manger.(name=name)
  if check_name:
  # Fund pool data filtering  try:
   check_code = (code=code)
   # Transaction quantity filtering   if check_code:
   if int(number) % 100 == 0:
    return render(request, 'trade_index.html', {"name": name, "code": code, "number": number})
   else:
    return HttpResponse('<center><h1>The transaction quantity is filled in incorrectly!  </h1></center>')
   else:
   return HttpResponse('<center><h1>The fund pool does not have this stock information!  </h1></center>')

  except Exception as e:
   print('Exception information is: %s' % str(e))
   pass
  else:
  return HttpResponse('<center><h1>No such fund manager!  </h1></center>')

 except Exception as e:
  print('Exception information is: %s' % str(e))
  pass

def trading(request):
 '''
  Divided by operation (buy and sell)
  If you buy, you only need to judge the transaction amount and the remaining cash assets.
  If sold, you need to judge the number of shares you hold
  '''
 if  == "POST":
 name = ['name']
 code = ['code']
 number = ['number']
 price = ['price']
 operate = ['operate']
 # Obtain remaining available funds try:
  total_price = float(().order_by('-time')[0].total_price)
 except Exception as e:
  total_price = 1000000

 if operate == 'Sell':
  # Obtain the number of holdings of this stock  stock_nums = (code=code)
  stock_num = sum([ for i in stock_nums])
  number = -int(number)
  if abs(number) &lt;= stock_num:
  # Calculate the amount required for transactions  trade_price = float(price) * int(number)
  balance = total_price - trade_price
  Time_ = (()).strftime("%Y-%m-%d %H:%M:%S")
  Mas = Trading(name=name, time=Time_, code=code, number=number, price=price, operate=operate,
    total_price=balance)
  ()
  return HttpResponse("<center><h1>Transaction completed!</h1></center>")
  else:
  return HttpResponse("<center><h1>The number of positions is less than the number of sells, and it is impossible to trade!</h1></center>")

 elif operate == 'Buy':
  trade_price = float(price) * int(number)
  balance = total_price - trade_price
  Time_ = (()).strftime("%Y-%m-%d %H:%M:%S")
  if trade_price &lt;= total_price:
  Mas = Trading(name=name, time=Time_, code=code, number=number, price=price, operate=operate, total_price=balance)
  ()
  print(total_price)
  return HttpResponse("<center><h1>Transaction completed!</h1></center>")
  else:
  print(total_price)
  return HttpResponse("<center><h1>The total amount of funds is insufficient!</h1></center>")
 else:
  return HttpResponse("<center><h1>Invalid command!</h1></center>")

def Fund_pool_(request):
 return render(request, 'fund_pool.html')

def Account(request):
 '''
  Just check whether the operator is a fund manager.
  '''
 if  == "POST":
 name = ['name']
 # Fund Manager Information check_name = Fund_Manger.(name=name)
 # Statistics of fund operations oprate_people = ()
 if check_name:
  total_price = float(().order_by('-time')[0].total_price)
  total_pool = '¥ ' + str(total_price)
  oprate_people_num = set([stock_name.name for stock_name in oprate_people]).__len__()
  Time_ = (()).strftime("%Y-%m-%d %H:%M:%S")
  Mas = Fund_pool(time=Time_, total_pool=total_pool, oprate_people=name, people_num=oprate_people_num)
  ()
  return HttpResponse("<center><h1>Data clearing succeeded!</h1></center>")
 else:
  return HttpResponse('<center><h1>Illegal operation!  </h1></center>')

4、

from  import admin
from  import Fund_Manger, Stock, Trading, Fund_pool

# Register your models here.
class Fund_MangerAdmin():
 list_display = ('name', 'age', 'entry_time')

class StockAdmin():
 list_display = ('stock_name', 'code')

class TradingAdmin():
 list_display = ('name', 'time', 'code', 'number', 'price', 'operate', 'total_price')

class Fund_PoolAdmin():
 list_display = ('time', 'total_pool', 'oprate_people', 'people_num')

(Fund_Manger, Fund_MangerAdmin)
(Stock, StockAdmin)
(Trading, TradingAdmin)
(Fund_pool, Fund_PoolAdmin)

Step 5:Create a business page under the templates folder

1、

&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
{# &lt;meta http-equiv="refresh" content="3;URL=data_entry/"&gt;#}
 &lt;meta charset="UTF-8"&gt;
 &lt;title&gt;front page&lt;/title&gt;
&lt;style&gt;
 a{ font-size:25px; color: white}
 li{ color: white; font-size: 30px}
&lt;/style&gt;

&lt;/head&gt;
&lt;body style="background:url('../static/images/') no-repeat fixed top; background-size: 100% 180%;overflow: hidden;"&gt;

&lt;center&gt;
 &lt;br/&gt;
 &lt;div style="position:fixed;left:0;right:0;top:0;bottom:0;width: 500px; height: 400px; margin:auto;"&gt;
 &lt;img src="../static/images/" width="245" height="100"&gt;
 &lt;h2 style="color: white; size: 10px"&gt;Fund simulation system:&lt;/h2&gt;

 &lt;li&gt;&lt;a href="{% url 'data_entry' %}" rel="external nofollow" &gt;Data entry system&lt;/a&gt;&lt;/li&gt;
 &lt;li&gt;&lt;a href="{% url 'check' %}" rel="external nofollow" aria-setsize="10px"&gt;Compliance Management System&lt;/a&gt;&lt;/li&gt;
 &lt;li&gt;&lt;a href="{% url 'fund_pool' %}" rel="external nofollow" &gt;Final liquidation system&lt;/a&gt;&lt;/li&gt;

 &lt;/div&gt;
&lt;/center&gt;

&lt;/body&gt;
&lt;/html&gt;

2、

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Compliance query system&lt;/title&gt;
&lt;/head&gt;
&lt;body style="background:url('../static/images/') no-repeat fixed top; background-size: 100% 180%;overflow: hidden;"&gt;
&lt;center&gt;
 &lt;br/&gt;
 &lt;div style="position:fixed;left:0;right:0;top:0;bottom:0;width: 500px; height: 400px; margin:auto;"&gt;
 &lt;img src="../static/images/" width="245" height="100"&gt;
 &lt;h2 style="color: white; size: 10px"&gt;Compliance query system:&lt;/h2&gt;
  &lt;form action="/trading/" method="POST"&gt;
  {% csrf_token %}
  &lt;label style="color: white; size: 10px"&gt;surname&amp;nbsp;&amp;nbsp;&amp;nbsp;name: &lt;/label&gt;
  &lt;input type="text" name="name"&gt; &lt;br&gt;
  &lt;label style="color: white; size: 10px"&gt;generation&amp;nbsp;&amp;nbsp;&amp;nbsp;code: &lt;/label&gt;
  &lt;input type="text" name="code"&gt; &lt;br&gt;
  &lt;label style="color: white; size: 10px"&gt;number&amp;nbsp;&amp;nbsp;&amp;nbsp;quantity: &lt;/label&gt;
  &lt;input type="text" name="number"&gt; &lt;br&gt;&lt;br&gt;
  &lt;input type="submit" type="submit" style="width: 80px;height: 30px;border-radius: 7px;" value="submit"&gt;
  &lt;/form&gt;
 &lt;/div&gt;
&lt;/center&gt;
&lt;/body&gt;
&lt;/html&gt;

3、data_entry.html

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Data entry system&lt;/title&gt;
&lt;/head&gt;
&lt;body style="background:url('../static/images/') no-repeat fixed top; background-size: 100% 180%;overflow: hidden;"&gt;

&lt;center&gt;
 &lt;div style="position:fixed;left:0;right:0;top:0;bottom:0;width: 700px; height: 400px; margin:auto;"&gt;

 &lt;h1 style="color: white; size: 10px"&gt;Chongyang Investment&lt;/h1&gt;

 &lt;h4 style="color: white; size: 10px"&gt;Fund trading staff information entry system:&lt;/h4&gt;
  &lt;form action="/add_fund_manger/" method="post"&gt;
  {% csrf_token %}
  &lt;label style="color: white; size: 10px"&gt;surname&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;name: &lt;/label&gt;
  &lt;input type="text" name="name"&gt; &lt;br&gt;
  &lt;label style="color: white; size: 10px"&gt;Year&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;age: &lt;/label&gt;
  &lt;input type="text" name="age"&gt; &lt;br&gt;
  &lt;label style="color: white; size: 10px"&gt;Entry time: &lt;/label&gt;
  &lt;input type="text" name="Time"&gt; &lt;br&gt;&lt;br&gt;
  &lt;input type="submit" style="width: 80px;height: 30px;border-radius: 7px;" value="submit"&gt;
  &lt;/form&gt;

  &lt;h4 style="color: white; size: 10px"&gt;Fund pool information entry system:&lt;/h4&gt;
  &lt;form action="/add_stock/" method="post"&gt;
  {% csrf_token %}
  &lt;label style="color: white; size: 10px"&gt;Stock abbreviation: &lt;/label&gt;
  &lt;input type="text" name="stock_name"&gt; &lt;br&gt;
  &lt;label style="color: white; size: 10px"&gt;generation&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;code: &lt;/label&gt;
  &lt;input type="text" name="code"&gt; &lt;br&gt;&lt;br&gt;
  &lt;input type="submit" style="width: 80px;height: 30px;border-radius: 7px;" value="submit"&gt;
  &lt;/form&gt;
 &lt;/div&gt;
&lt;/center&gt;
&lt;/body&gt;
&lt;/html&gt;

4、trade_index.html

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Trading system&lt;/title&gt;
&lt;/head&gt;
&lt;body style="background:url('../static/images/') no-repeat fixed top; background-size: 100% 250%;overflow: hidden;"&gt;
&lt;center&gt;
 &lt;div style="position:fixed;left:0;right:0;top:0;bottom:0;width: 500px; height: 400px; margin:auto;"&gt;
 &lt;h1 style="color: white; size: 10px"&gt;Chongyang Investment&lt;/h1&gt;
 &lt;h2 style="color: white; size: 10px"&gt;Trading system:&lt;/h2&gt;
  &lt;form action="/trading_success/" method="POST"&gt;
  {% csrf_token %}
  &lt;label style="color: white; size: 10px"&gt;surname&amp;nbsp;&amp;nbsp;&amp;nbsp;name: &lt;/label&gt;
  &lt;input type="text" name="name" value={{ name }} readonly="readonly" /&gt; &lt;br&gt;
  &lt;label style="color: white; size: 10px"&gt;generation&amp;nbsp;&amp;nbsp;&amp;nbsp;code: &lt;/label&gt;
  &lt;input type="text" name="code" value={{ code }} readonly="readonly" /&gt; &lt;br&gt;
  &lt;label style="color: white; size: 10px"&gt;number&amp;nbsp;&amp;nbsp;&amp;nbsp;quantity: &lt;/label&gt;
  &lt;input type="text" name="number" value={{ number }} readonly="readonly" /&gt; &lt;br&gt;
  &lt;label style="color: white; size: 10px"&gt;price&amp;nbsp;&amp;nbsp;&amp;nbsp;grid: &lt;/label&gt;
  &lt;input type="text" name="price"&gt; &lt;br&gt;
  &lt;label style="color: white; size: 10px"&gt;Hold&amp;nbsp;&amp;nbsp;&amp;nbsp;do: &lt;/label&gt;
  &lt;input type="text" name="operate"&gt; &lt;br&gt;&lt;br&gt;
  &lt;input type="submit" type="submit" style="width: 80px;height: 30px;border-radius: 7px;" value="submit"&gt;
  &lt;/form&gt;
 &lt;/div&gt;
&lt;/center&gt;
&lt;/body&gt;
&lt;/html&gt;

5、fund_pool.html

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Fund clearing system&lt;/title&gt;
&lt;/head&gt;
&lt;body style="background:url('../static/images/') no-repeat fixed top; background-size: 100% 180%;overflow: hidden;"&gt;
&lt;center&gt;
 &lt;br&gt;
 &lt;div style="position:fixed;left:0;right:0;top:0;bottom:0;width: 500px; height: 400px; margin:auto;"&gt;
 &lt;h1 style="color: white; size: 10px"&gt;Chongyang Investment&lt;/h1&gt;
 &lt;h4 style="color: white; size: 10px"&gt;Fund clearing system:&lt;/h4&gt;
  &lt;form action="/account/" method="post"&gt;
  {% csrf_token %}
  &lt;label style="color: white; size: 10px"&gt;surname&amp;nbsp;&amp;nbsp;name: &lt;/label&gt;
  &lt;input type="text" name="name"&gt; &lt;br&gt;&lt;br&gt;
  &lt;input type="submit" style="width: 80px;height: 30px;border-radius: 7px;" value="Clean"&gt;
  &lt;/form&gt;
 &lt;/div&gt;
&lt;/center&gt;
&lt;/body&gt;
&lt;/html&gt;

Step 6:Create a table structure, create a super administrator, and run the project

python  makemigrations
python  migrate
python  createsuperuser
python  runserver 0.0.0.0:8000

The following content is just a summary and sharing of Django by yourself. If there are any shortcomings, everyone is welcome to guide their studies and make progress together.

This tutorial on using Django to build a fund simulation trading system is all the content I share with you. I hope you can give you a reference and I hope you can support me more.