使用Django搭建一個基金模擬交易系統(tǒng)教程
親手教你如何搭建一個基金模擬系統(tǒng)(基于Django框架)
第一步:創(chuàng)建項(xiàng)目、APP以及靜態(tài)文件存儲文件夾
django-admin startproject Chongyang django-admin startapp Stock # Chongyang文件夾里面操作
在chongyang項(xiàng)目創(chuàng)建statics和templates兩個文件夾
第二步:配置Setting.py文件
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Stock' # 添加自己的APP名
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], # 靜態(tài)文件夾地址(必須配置)
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# 數(shù)據(jù)庫配置(使用默認(rèn)sqlite)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'NAME': os.path.join(BASE_DIR, 'StockDB.db'),
}
}
LANGUAGE_CODE = 'zh-hans' # 漢語
TIME_ZONE = 'Asia/Shanghai' # 時區(qū)
STATIC_URL = '/static/' # 靜態(tài)文件配置
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'statics'), # 具體的路徑
os.path.join(BASE_DIR, 'templates'),
]
第三步:運(yùn)行項(xiàng)目
python manage.py runserver 0.0.0.0:8000
到目前為止,你已經(jīng)創(chuàng)建了一個擁有極其龐大功能的web網(wǎng)站,后續(xù)只需激活相應(yīng)的服務(wù)即可
url.py # 路由配置文件 views.py # 功能實(shí)現(xiàn)文件 admin.py # 后臺管理文件 model.py # 數(shù)據(jù)庫創(chuàng)建文件
第四步:具體項(xiàng)目配置
在配置好前面設(shè)置后直接在相應(yīng)的文件里復(fù)制如下代碼運(yùn)行項(xiàng)目即可
1、models.py
from django.db import models import uuid # 基金經(jīng)理數(shù)據(jù)表 class Fund_Manger(models.Model): name = models.CharField(max_length=20) age = models.IntegerField() entry_time = models.CharField(max_length=20) def __str__(self): return self.name # 股票信息數(shù)據(jù)表 class Stock(models.Model): stock_name = models.CharField(max_length=20) code = models.CharField(max_length=10) def __str__(self): return self.code # 交易系統(tǒng)表 class Trading(models.Model): name = models.CharField(max_length=20) time = models.DateTimeField() code = models.CharField(max_length=10) number = models.IntegerField() price = models.CharField(max_length=10) operate = models.CharField(max_length=10) total_price = models.CharField(max_length=20) # 清算數(shù)據(jù)表 class Fund_pool(models.Model): time = models.DateTimeField() total_pool = models.CharField(max_length=30) oprate_people = models.CharField(max_length=10) people_num = models.IntegerField() def __str__(self): return self.total_pool
2、url.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from Stock import views
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$', views.index),
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/$', views.check),
url(r'^trading_success/$', views.trading),
url(r'^fund_pool/$', views.Fund_pool_, name='fund_pool'),
url(r'^account/$', views.Account)
]
3、views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.utils import timezone
from Stock.models import Fund_Manger, Stock, Trading, Fund_pool
import re
def index(request):
return render(request, 'index.html')
def data_entry(request):
return render(request, 'data_entry.html')
def check_index(request):
return render(request, 'check.html')
def add_fund_manger(request):
'''
添加時需判斷原始表是否已經(jīng)存在此用戶信息
同時添加年齡限制(20~40)
'''
if request.method == "POST":
name = request.POST['name']
age = request.POST['age']
entry_time = request.POST['Time']
check_name = Fund_Manger.objects.filter(name=name)
if check_name:
return HttpResponse("<center><h1>該用戶已處在!</h1></center>")
else:
if int(age) < 20 or int(age) >= 40:
return HttpResponse("<center><h1>該用戶年齡不符合要求!</h1></center>")
else:
Mas = Fund_Manger(name=name, age=age, entry_time=entry_time)
Mas.save()
return HttpResponse("<center><h1>用戶注冊成功!</h1></center>")
def add_stock(request):
'''
添加基金池數(shù)據(jù)時需對股票代碼做限定
僅限A股市場,同時做異常捕獲處理
'''
if request.method == "POST":
stock_name = request.POST['stock_name']
post_code = request.POST['code']
# 過濾交易代碼(以0、3、6開頭長度為6的數(shù)字)
pattern = re.compile(r'000[\d+]{3}$|^002[\d+]{3}$|^300[\d+]{3}$|^600[\d+]{3}$|^601[\d+]{3}$|^603[\d+]{3}$')
code = pattern.findall(post_code)
# 異常處理
try:
num = code[0].__len__()
if num == 6:
Mas = Stock(stock_name=stock_name, code=code[0])
Mas.save()
return HttpResponse("<center><h1>基金池數(shù)據(jù)添加成功!</h1></center>")
else:
return HttpResponse("<center><h1>錯誤代碼!</h1></center>")
except Exception as e:
return HttpResponse("<center><h1>錯誤代碼!</h1></center>")
def check(request):
'''
信息合規(guī)查詢(僅限A股數(shù)據(jù))
需對基金經(jīng)理、股票代碼、交易數(shù)量同時做判斷
'''
if request.method == "POST":
name = request.POST['name']
code = request.POST['code']
number = request.POST['number']
# 基金經(jīng)理信息過濾
try:
check_name = Fund_Manger.objects.filter(name=name)
if check_name:
# 基金池數(shù)據(jù)過濾
try:
check_code = Stock.objects.filter(code=code)
# 交易數(shù)量過濾
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>交易數(shù)量填寫錯誤!</h1></center>')
else:
return HttpResponse('<center><h1>基金池?zé)o該股票信息!</h1></center>')
except Exception as e:
print('異常信息為:%s' % str(e))
pass
else:
return HttpResponse('<center><h1>沒有該基金經(jīng)理!</h1></center>')
except Exception as e:
print('異常信息為:%s' % str(e))
pass
def trading(request):
'''
按照操作進(jìn)行劃分(買入賣出)
若買入只需判斷交易金額與剩余現(xiàn)金資產(chǎn)對比即可
若賣出還需對其持股數(shù)量加以判斷
'''
if request.method == "POST":
name = request.POST['name']
code = request.POST['code']
number = request.POST['number']
price = request.POST['price']
operate = request.POST['operate']
# 獲取剩余可用資金
try:
total_price = float(Trading.objects.all().order_by('-time')[0].total_price)
except Exception as e:
total_price = 1000000
if operate == '賣出':
# 獲取此股票持倉數(shù)量
stock_nums = Trading.objects.filter(code=code)
stock_num = sum([i.number for i in stock_nums])
number = -int(number)
if abs(number) <= stock_num:
# 計(jì)算交易所需金額
trade_price = float(price) * int(number)
balance = total_price - trade_price
Time_ = timezone.localtime(timezone.now()).strftime("%Y-%m-%d %H:%M:%S")
Mas = Trading(name=name, time=Time_, code=code, number=number, price=price, operate=operate,
total_price=balance)
Mas.save()
return HttpResponse("<center><h1>交易完成!</h1></center>")
else:
return HttpResponse("<center><h1>持倉數(shù)小于賣出數(shù),無法交易!</h1></center>")
elif operate == '買入':
trade_price = float(price) * int(number)
balance = total_price - trade_price
Time_ = timezone.localtime(timezone.now()).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)
Mas.save()
print(total_price)
return HttpResponse("<center><h1>交易完成!</h1></center>")
else:
print(total_price)
return HttpResponse("<center><h1>資金總額不足!</h1></center>")
else:
return HttpResponse("<center><h1>無效指令!</h1></center>")
def Fund_pool_(request):
return render(request, 'fund_pool.html')
def Account(request):
'''
清算只需查詢操作人是否為基金經(jīng)理即可
'''
if request.method == "POST":
name = request.POST['name']
# 基金經(jīng)理信息
check_name = Fund_Manger.objects.filter(name=name)
# 基金操作人數(shù)統(tǒng)計(jì)
oprate_people = Trading.objects.all()
if check_name:
total_price = float(Trading.objects.all().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_ = timezone.localtime(timezone.now()).strftime("%Y-%m-%d %H:%M:%S")
Mas = Fund_pool(time=Time_, total_pool=total_pool, oprate_people=name, people_num=oprate_people_num)
Mas.save()
return HttpResponse("<center><h1>數(shù)據(jù)清算成功!</h1></center>")
else:
return HttpResponse('<center><h1>非法操作!</h1></center>')
4、admin.py
from django.contrib import admin
from Stock.models import Fund_Manger, Stock, Trading, Fund_pool
# Register your models here.
class Fund_MangerAdmin(admin.ModelAdmin):
list_display = ('name', 'age', 'entry_time')
class StockAdmin(admin.ModelAdmin):
list_display = ('stock_name', 'code')
class TradingAdmin(admin.ModelAdmin):
list_display = ('name', 'time', 'code', 'number', 'price', 'operate', 'total_price')
class Fund_PoolAdmin(admin.ModelAdmin):
list_display = ('time', 'total_pool', 'oprate_people', 'people_num')
admin.site.register(Fund_Manger, Fund_MangerAdmin)
admin.site.register(Stock, StockAdmin)
admin.site.register(Trading, TradingAdmin)
admin.site.register(Fund_pool, Fund_PoolAdmin)
第五步:在templates文件夾下面創(chuàng)建業(yè)務(wù)頁面
1、index.html
<!DOCTYPE html>
<html lang="en">
<head>
{# <meta http-equiv="refresh" content="3;URL=data_entry/">#}
<meta charset="UTF-8">
<title>首頁</title>
<style>
a{ font-size:25px; color: white}
li{ color: white; font-size: 30px}
</style>
</head>
<body style="background:url('../static/images/background.jpg') 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/logo.jpg" width="245" height="100">
<h2 style="color: white; size: 10px">基金模擬系統(tǒng):</h2>
<li><a href="{% url 'data_entry' %}" rel="external nofollow" >數(shù)據(jù)錄入系統(tǒng)</a></li>
<li><a href="{% url 'check' %}" rel="external nofollow" aria-setsize="10px">合規(guī)管理系統(tǒng)</a></li>
<li><a href="{% url 'fund_pool' %}" rel="external nofollow" >尾盤清算系統(tǒng)</a></li>
</div>
</center>
</body>
</html>
2、check.html
<!DOCTYPE html>
<html>
<head>
<title>合規(guī)查詢系統(tǒng)</title>
</head>
<body style="background:url('../static/images/background.jpg') 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/logo.jpg" width="245" height="100">
<h2 style="color: white; size: 10px">合規(guī)查詢系統(tǒng):</h2>
<form action="/trading/" method="POST">
{% csrf_token %}
<label style="color: white; size: 10px">姓 名: </label>
<input type="text" name="name"> <br>
<label style="color: white; size: 10px">代 碼: </label>
<input type="text" name="code"> <br>
<label style="color: white; size: 10px">數(shù) 量: </label>
<input type="text" name="number"> <br><br>
<input type="submit" type="submit" style="width: 80px;height: 30px;border-radius: 7px;" value="提 交">
</form>
</div>
</center>
</body>
</html>
3、data_entry.html
<!DOCTYPE html>
<html>
<head>
<title>數(shù)據(jù)錄入系統(tǒng)</title>
</head>
<body style="background:url('../static/images/background.jpg') 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">重陽投資</h1>
<h4 style="color: white; size: 10px">基金交易職員信息錄入系統(tǒng):</h4>
<form action="/add_fund_manger/" method="post">
{% csrf_token %}
<label style="color: white; size: 10px">姓 名: </label>
<input type="text" name="name"> <br>
<label style="color: white; size: 10px">年 齡: </label>
<input type="text" name="age"> <br>
<label style="color: white; size: 10px">入職時間: </label>
<input type="text" name="Time"> <br><br>
<input type="submit" style="width: 80px;height: 30px;border-radius: 7px;" value="提 交">
</form>
<h4 style="color: white; size: 10px">基金池信息錄入系統(tǒng):</h4>
<form action="/add_stock/" method="post">
{% csrf_token %}
<label style="color: white; size: 10px">股票簡稱: </label>
<input type="text" name="stock_name"> <br>
<label style="color: white; size: 10px">代 碼: </label>
<input type="text" name="code"> <br><br>
<input type="submit" style="width: 80px;height: 30px;border-radius: 7px;" value="提 交">
</form>
</div>
</center>
</body>
</html>
4、trade_index.html
<!DOCTYPE html>
<html>
<head>
<title>交易系統(tǒng)</title>
</head>
<body style="background:url('../static/images/background.jpg') 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">重陽投資</h1>
<h2 style="color: white; size: 10px">交易系統(tǒng):</h2>
<form action="/trading_success/" method="POST">
{% csrf_token %}
<label style="color: white; size: 10px">姓 名: </label>
<input type="text" name="name" value={{ name }} readonly="readonly" /> <br>
<label style="color: white; size: 10px">代 碼: </label>
<input type="text" name="code" value={{ code }} readonly="readonly" /> <br>
<label style="color: white; size: 10px">數(shù) 量: </label>
<input type="text" name="number" value={{ number }} readonly="readonly" /> <br>
<label style="color: white; size: 10px">價 格: </label>
<input type="text" name="price"> <br>
<label style="color: white; size: 10px">操 作: </label>
<input type="text" name="operate"> <br><br>
<input type="submit" type="submit" style="width: 80px;height: 30px;border-radius: 7px;" value="提 交">
</form>
</div>
</center>
</body>
</html>
5、fund_pool.html
<!DOCTYPE html>
<html>
<head>
<title>基金清算系統(tǒng)</title>
</head>
<body style="background:url('../static/images/background.jpg') 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">重陽投資</h1>
<h4 style="color: white; size: 10px">基金清算系統(tǒng):</h4>
<form action="/account/" method="post">
{% csrf_token %}
<label style="color: white; size: 10px">姓 名: </label>
<input type="text" name="name"> <br><br>
<input type="submit" style="width: 80px;height: 30px;border-radius: 7px;" value="清 算">
</form>
</div>
</center>
</body>
</html>
第六步:創(chuàng)建表結(jié)構(gòu),創(chuàng)建超級管理員,運(yùn)行項(xiàng)目即可
python manage.py makemigrations python manage.py migrate python manage.py createsuperuser python manage.py runserver 0.0.0.0:8000
以下內(nèi)容只是自己學(xué)習(xí)Django的一點(diǎn)總結(jié)分享,有不足的地方歡迎大家指導(dǎo)學(xué)習(xí),一起進(jìn)步。
這篇使用Django搭建一個基金模擬交易系統(tǒng)教程就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- 基于django micro搭建網(wǎng)站實(shí)現(xiàn)加水印功能
- python框架Django實(shí)戰(zhàn)商城項(xiàng)目之工程搭建過程圖文詳解
- python+Django+pycharm+mysql 搭建首個web項(xiàng)目詳解
- nginx+uwsgi+django環(huán)境搭建的方法步驟
- Python django搭建layui提交表單,表格,圖標(biāo)的實(shí)例
- 詳解使用django-mama-cas快速搭建CAS服務(wù)的實(shí)現(xiàn)
- python3.6+django2.0+mysql搭建網(wǎng)站過程詳解
- 使用Django搭建網(wǎng)站實(shí)現(xiàn)商品分頁功能
相關(guān)文章
opencv+playwright滑動驗(yàn)證碼的實(shí)現(xiàn)
滑動驗(yàn)證碼是常見的驗(yàn)證碼之一,本文主要介紹了opencv+playwright滑動驗(yàn)證碼的實(shí)現(xiàn),具有一定的參考價值,感興趣的可以了解一下2023-11-11
Python實(shí)現(xiàn)查找最小的k個數(shù)示例【兩種解法】
這篇文章主要介紹了Python實(shí)現(xiàn)查找最小的k個數(shù),結(jié)合實(shí)例形式對比分析了Python常見的兩種列表排序、查找相關(guān)操作技巧,需要的朋友可以參考下2019-01-01
Python向MySQL批量插數(shù)據(jù)的實(shí)例講解
下面小編就為大家分享一篇Python向MySQL批量插數(shù)據(jù)的實(shí)例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03
Python學(xué)習(xí)筆記之抓取某只基金歷史凈值數(shù)據(jù)實(shí)戰(zhàn)案例
這篇文章主要介紹了Python學(xué)習(xí)筆記之抓取某只基金歷史凈值數(shù)據(jù)案例,結(jié)合具體實(shí)例形式分析了Python基于selenium庫的數(shù)據(jù)抓取及mysql交互相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2019-06-06
Python設(shè)計(jì)模式中的結(jié)構(gòu)型適配器模式
這篇文章主要介紹了Python設(shè)計(jì)中的結(jié)構(gòu)型適配器模式,適配器模式即Adapter?Pattern,將一個類的接口轉(zhuǎn)換成為客戶希望的另外一個接口,下文內(nèi)容具有一定的參考價值,需要的小伙伴可以參考一下2022-02-02

