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) < 20 or int(age) >= 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) <= 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 <= 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、
<!DOCTYPE html> <html lang="en"> <head> {# <meta http-equiv="refresh" content="3;URL=data_entry/">#} <meta charset="UTF-8"> <title>front page</title> <style> a{ font-size:25px; color: white} li{ color: white; font-size: 30px} </style> </head> <body style="background:url('../static/images/') no-repeat fixed top; background-size: 100% 180%;overflow: hidden;"> <center> <br/> <div style="position:fixed;left:0;right:0;top:0;bottom:0;width: 500px; height: 400px; margin:auto;"> <img src="../static/images/" width="245" height="100"> <h2 style="color: white; size: 10px">Fund simulation system:</h2> <li><a href="{% url 'data_entry' %}" rel="external nofollow" >Data entry system</a></li> <li><a href="{% url 'check' %}" rel="external nofollow" aria-setsize="10px">Compliance Management System</a></li> <li><a href="{% url 'fund_pool' %}" rel="external nofollow" >Final liquidation system</a></li> </div> </center> </body> </html>
2、
<!DOCTYPE html> <html> <head> <title>Compliance query system</title> </head> <body style="background:url('../static/images/') no-repeat fixed top; background-size: 100% 180%;overflow: hidden;"> <center> <br/> <div style="position:fixed;left:0;right:0;top:0;bottom:0;width: 500px; height: 400px; margin:auto;"> <img src="../static/images/" width="245" height="100"> <h2 style="color: white; size: 10px">Compliance query system:</h2> <form action="/trading/" method="POST"> {% csrf_token %} <label style="color: white; size: 10px">surname&nbsp;&nbsp;&nbsp;name: </label> <input type="text" name="name"> <br> <label style="color: white; size: 10px">generation&nbsp;&nbsp;&nbsp;code: </label> <input type="text" name="code"> <br> <label style="color: white; size: 10px">number&nbsp;&nbsp;&nbsp;quantity: </label> <input type="text" name="number"> <br><br> <input type="submit" type="submit" style="width: 80px;height: 30px;border-radius: 7px;" value="submit"> </form> </div> </center> </body> </html>
3、data_entry.html
<!DOCTYPE html> <html> <head> <title>Data entry system</title> </head> <body style="background:url('../static/images/') no-repeat fixed top; background-size: 100% 180%;overflow: hidden;"> <center> <div style="position:fixed;left:0;right:0;top:0;bottom:0;width: 700px; height: 400px; margin:auto;"> <h1 style="color: white; size: 10px">Chongyang Investment</h1> <h4 style="color: white; size: 10px">Fund trading staff information entry system:</h4> <form action="/add_fund_manger/" method="post"> {% csrf_token %} <label style="color: white; size: 10px">surname&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;name: </label> <input type="text" name="name"> <br> <label style="color: white; size: 10px">Year&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;age: </label> <input type="text" name="age"> <br> <label style="color: white; size: 10px">Entry time: </label> <input type="text" name="Time"> <br><br> <input type="submit" style="width: 80px;height: 30px;border-radius: 7px;" value="submit"> </form> <h4 style="color: white; size: 10px">Fund pool information entry system:</h4> <form action="/add_stock/" method="post"> {% csrf_token %} <label style="color: white; size: 10px">Stock abbreviation: </label> <input type="text" name="stock_name"> <br> <label style="color: white; size: 10px">generation&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;code: </label> <input type="text" name="code"> <br><br> <input type="submit" style="width: 80px;height: 30px;border-radius: 7px;" value="submit"> </form> </div> </center> </body> </html>
4、trade_index.html
<!DOCTYPE html> <html> <head> <title>Trading system</title> </head> <body style="background:url('../static/images/') no-repeat fixed top; background-size: 100% 250%;overflow: hidden;"> <center> <div style="position:fixed;left:0;right:0;top:0;bottom:0;width: 500px; height: 400px; margin:auto;"> <h1 style="color: white; size: 10px">Chongyang Investment</h1> <h2 style="color: white; size: 10px">Trading system:</h2> <form action="/trading_success/" method="POST"> {% csrf_token %} <label style="color: white; size: 10px">surname&nbsp;&nbsp;&nbsp;name: </label> <input type="text" name="name" value={{ name }} readonly="readonly" /> <br> <label style="color: white; size: 10px">generation&nbsp;&nbsp;&nbsp;code: </label> <input type="text" name="code" value={{ code }} readonly="readonly" /> <br> <label style="color: white; size: 10px">number&nbsp;&nbsp;&nbsp;quantity: </label> <input type="text" name="number" value={{ number }} readonly="readonly" /> <br> <label style="color: white; size: 10px">price&nbsp;&nbsp;&nbsp;grid: </label> <input type="text" name="price"> <br> <label style="color: white; size: 10px">Hold&nbsp;&nbsp;&nbsp;do: </label> <input type="text" name="operate"> <br><br> <input type="submit" type="submit" style="width: 80px;height: 30px;border-radius: 7px;" value="submit"> </form> </div> </center> </body> </html>
5、fund_pool.html
<!DOCTYPE html> <html> <head> <title>Fund clearing system</title> </head> <body style="background:url('../static/images/') no-repeat fixed top; background-size: 100% 180%;overflow: hidden;"> <center> <br> <div style="position:fixed;left:0;right:0;top:0;bottom:0;width: 500px; height: 400px; margin:auto;"> <h1 style="color: white; size: 10px">Chongyang Investment</h1> <h4 style="color: white; size: 10px">Fund clearing system:</h4> <form action="/account/" method="post"> {% csrf_token %} <label style="color: white; size: 10px">surname&nbsp;&nbsp;name: </label> <input type="text" name="name"> <br><br> <input type="submit" style="width: 80px;height: 30px;border-radius: 7px;" value="Clean"> </form> </div> </center> </body> </html>
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.