使用Django搭建一个基金模拟交易系统教程


Posted in Python onNovember 18, 2019

亲手教你如何搭建一个基金模拟系统(基于Django框架)

第一步:创建项目、APP以及静态文件存储文件夹

django-admin startproject Chongyang
django-admin startapp Stock # Chongyang文件夹里面操作

在chongyang项目创建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')], # 静态文件夹地址(必须配置)
 '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',
  ],
 },
 },
]

# 数据库配置(使用默认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' # 时区

STATIC_URL = '/static/'  # 静态文件配置
STATICFILES_DIRS = [
 os.path.join(BASE_DIR, 'statics'), # 具体的路径
 os.path.join(BASE_DIR, 'templates'),
]

第三步:运行项目

python manage.py runserver 0.0.0.0:8000

到目前为止,你已经创建了一个拥有极其庞大功能的web网站,后续只需激活相应的服务即可

url.py # 路由配置文件
views.py # 功能实现文件
admin.py # 后台管理文件
model.py # 数据库创建文件

第四步:具体项目配置

在配置好前面设置后直接在相应的文件里复制如下代码运行项目即可

1、models.py

from django.db import models
import uuid

# 基金经理数据表
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

# 股票信息数据表
class Stock(models.Model):
 stock_name = models.CharField(max_length=20)
 code = models.CharField(max_length=10)
 def __str__(self):
 return self.code

# 交易系统表
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)

# 清算数据表
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):
 '''
 添加时需判断原始表是否已经存在此用户信息
 同时添加年龄限制(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):
 '''
 添加基金池数据时需对股票代码做限定
 仅限A股市场,同时做异常捕获处理
 '''
 if request.method == "POST":
 stock_name = request.POST['stock_name']
 post_code = request.POST['code']
 # 过滤交易代码(以0、3、6开头长度为6的数字)
 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>基金池数据添加成功!</h1></center>")
  else:
  return HttpResponse("<center><h1>错误代码!</h1></center>")

 except Exception as e:
  return HttpResponse("<center><h1>错误代码!</h1></center>")

def check(request):
 '''
 信息合规查询(仅限A股数据)
 需对基金经理、股票代码、交易数量同时做判断
 '''
 if request.method == "POST":
 name = request.POST['name']
 code = request.POST['code']
 number = request.POST['number']
 # 基金经理信息过滤
 try:
  check_name = Fund_Manger.objects.filter(name=name)
  if check_name:
  # 基金池数据过滤
  try:
   check_code = Stock.objects.filter(code=code)
   # 交易数量过滤
   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>交易数量填写错误!</h1></center>')
   else:
   return HttpResponse('<center><h1>基金池无该股票信息!</h1></center>')

  except Exception as e:
   print('异常信息为:%s' % str(e))
   pass
  else:
  return HttpResponse('<center><h1>没有该基金经理!</h1></center>')

 except Exception as e:
  print('异常信息为:%s' % str(e))
  pass

def trading(request):
 '''
 按照操作进行划分(买入卖出)
 若买入只需判断交易金额与剩余现金资产对比即可
 若卖出还需对其持股数量加以判断
 '''
 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 == '卖出':
  # 获取此股票持仓数量
  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:
  # 计算交易所需金额
  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>持仓数小于卖出数,无法交易!</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):
 '''
 清算只需查询操作人是否为基金经理即可
 '''
 if request.method == "POST":
 name = request.POST['name']
 # 基金经理信息
 check_name = Fund_Manger.objects.filter(name=name)
 # 基金操作人数统计
 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>数据清算成功!</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文件夹下面创建业务页面

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">基金模拟系统:</h2>

 <li><a href="{% url 'data_entry' %}" rel="external nofollow" >数据录入系统</a></li>
 <li><a href="{% url 'check' %}" rel="external nofollow" aria-setsize="10px">合规管理系统</a></li>
 <li><a href="{% url 'fund_pool' %}" rel="external nofollow" >尾盘清算系统</a></li>

 </div>
</center>

</body>
</html>

2、check.html

<!DOCTYPE html>
<html>
<head>
<title>合规查询系统</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">合规查询系统:</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">数   量: </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>数据录入系统</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">基金交易职员信息录入系统:</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">基金池信息录入系统:</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>交易系统</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">交易系统:</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">数   量: </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>基金清算系统</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">基金清算系统:</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>

第六步:创建表结构,创建超级管理员,运行项目即可

python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver 0.0.0.0:8000

以下内容只是自己学习Django的一点总结分享,有不足的地方欢迎大家指导学习,一起进步。

这篇使用Django搭建一个基金模拟交易系统教程就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python字典序问题实例
Sep 26 Python
深入讲解Python中的迭代器和生成器
Oct 26 Python
python中input()与raw_input()的区别分析
Feb 27 Python
ubuntu中配置pyqt4环境教程
Dec 27 Python
对numpy 数组和矩阵的乘法的进一步理解
Apr 04 Python
Python+selenium 获取一组元素属性值的实例
Jun 22 Python
Python脚本按照当前日期创建多级目录
Mar 01 Python
pyqt5移动鼠标显示坐标的方法
Jun 21 Python
python函数装饰器之带参数的函数和带参数的装饰器用法示例
Nov 06 Python
pycharm安装及如何导入numpy
Apr 03 Python
python 对象真假值的实例(哪些视为False)
Dec 11 Python
python源码剖析之PyObject详解
May 18 Python
wxPython实现文本框基础组件
Nov 18 #Python
WxPython实现无边框界面
Nov 18 #Python
python中的RSA加密与解密实例解析
Nov 18 #Python
wxpython绘制圆角窗体
Nov 18 #Python
wxpython绘制音频效果
Nov 18 #Python
python导入不同目录下的自定义模块过程解析
Nov 18 #Python
解决django model修改添加字段报错的问题
Nov 18 #Python
You might like
WAR3重制版DOTA 5V5初体验
2020/04/09 DOTA
php中存储用户ID和密码到mysql数据库的方法
2013/02/06 PHP
php原生数据库分页的代码实例
2019/02/18 PHP
jQuery实现table隔行换色和鼠标经过变色的两种方法
2014/06/15 Javascript
深入理解逻辑表达式的用法 与或非的用法
2016/06/06 Javascript
如何解决手机浏览器页面点击不跳转浏览器双击放大网页
2016/07/01 Javascript
jQuery弹出div层过2秒自动消失
2016/11/29 Javascript
Angular.js去除页面中显示的空行方法示例
2017/03/30 Javascript
JS获取短信验证码倒计时的实现代码
2017/05/22 Javascript
js模块加载方式浅析
2017/08/12 Javascript
jquery+css实现下拉列表功能
2017/09/03 jQuery
JS实现把一个页面层数据传递到另一个页面的两种方式
2018/08/13 Javascript
解决layui中table异步数据请求不支持自定义返回数据格式的问题
2018/08/19 Javascript
详解js模板引擎art template数组渲染的方法
2018/10/09 Javascript
Vue 页面状态保持页面间数据传输的一种方法(推荐)
2018/11/01 Javascript
移动端(微信等使用vConsole调试console的方法
2019/03/05 Javascript
在vue项目中引用Antv G2,以饼图为例讲解
2020/10/28 Javascript
[01:08:44]NB vs VP 2018国际邀请赛小组赛BO2 第一场 8.18
2018/08/19 DOTA
Python修改Excel数据的实例代码
2013/11/01 Python
python函数装饰器用法实例详解
2015/06/04 Python
python实现图书馆研习室自动预约功能
2018/04/27 Python
Python爬虫实现简单的爬取有道翻译功能示例
2018/07/13 Python
windows、linux下打包Python3程序详细方法
2020/03/17 Python
python中绕过反爬虫的方法总结
2020/11/25 Python
HTML5 微格式和相关的属性名称
2010/02/10 HTML / CSS
含精油的天然有机化妆品:Indemne
2019/08/27 全球购物
少先队入队活动方案
2014/02/08 职场文书
爱情寄语大全
2014/04/09 职场文书
中国梦团日活动总结
2014/07/07 职场文书
教师党员学习群众路线心得体会
2014/11/04 职场文书
财务整改报告范文
2014/11/05 职场文书
华清池导游词
2015/02/02 职场文书
2015年共青团工作总结
2015/05/15 职场文书
导游词之重庆渣滓洞
2020/01/08 职场文书
Java代码规范与质量检测插件SonarLint的使用
2022/08/05 Java/Android
ECharts transform数据转换和dataZoom在项目中使用
2022/12/24 Javascript