您好,登錄后才能下訂單哦!
小編給大家分享一下使用Django搭建一個(gè)基金模擬交易系統(tǒng)的案例,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
如何搭建一個(gè)基金模擬系統(tǒng)(基于Django框架)
第一步:創(chuàng)建項(xiàng)目、APP以及靜態(tài)文件存儲(chǔ)文件夾
django-admin startproject Chongyang django-admin startapp Stock # Chongyang文件夾里面操作
在chongyang項(xiàng)目創(chuàng)建statics和templates兩個(gè)文件夾
第二步:配置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' # 時(shí)區(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)建了一個(gè)擁有極其龐大功能的web網(wǎng)站,后續(xù)只需激活相應(yīng)的服務(wù)即可
url.py # 路由配置文件 views.py # 功能實(shí)現(xiàn)文件 admin.py # 后臺(tái)管理文件 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): ''' 添加時(shí)需判斷原始表是否已經(jīng)存在此用戶信息 同時(shí)添加年齡限制(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><h2>該用戶已處在!</h2></center>") else: if int(age) < 20 or int(age) >= 40: return HttpResponse("<center><h2>該用戶年齡不符合要求!</h2></center>") else: Mas = Fund_Manger(name=name, age=age, entry_time=entry_time) Mas.save() return HttpResponse("<center><h2>用戶注冊(cè)成功!</h2></center>") def add_stock(request): ''' 添加基金池?cái)?shù)據(jù)時(shí)需對(duì)股票代碼做限定 僅限A股市場(chǎng),同時(shí)做異常捕獲處理 ''' if request.method == "POST": stock_name = request.POST['stock_name'] post_code = request.POST['code'] # 過濾交易代碼(以0、3、6開頭長(zhǎng)度為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><h2>基金池?cái)?shù)據(jù)添加成功!</h2></center>") else: return HttpResponse("<center><h2>錯(cuò)誤代碼!</h2></center>") except Exception as e: return HttpResponse("<center><h2>錯(cuò)誤代碼!</h2></center>") def check(request): ''' 信息合規(guī)查詢(僅限A股數(shù)據(jù)) 需對(duì)基金經(jīng)理、股票代碼、交易數(shù)量同時(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: # 基金池?cái)?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><h2>交易數(shù)量填寫錯(cuò)誤!</h2></center>') else: return HttpResponse('<center><h2>基金池?zé)o該股票信息!</h2></center>') except Exception as e: print('異常信息為:%s' % str(e)) pass else: return HttpResponse('<center><h2>沒有該基金經(jīng)理!</h2></center>') except Exception as e: print('異常信息為:%s' % str(e)) pass def trading(request): ''' 按照操作進(jìn)行劃分(買入賣出) 若買入只需判斷交易金額與剩余現(xiàn)金資產(chǎn)對(duì)比即可 若賣出還需對(duì)其持股數(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 == '賣出': # 獲取此股票持倉(cāng)數(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><h2>交易完成!</h2></center>") else: return HttpResponse("<center><h2>持倉(cāng)數(shù)小于賣出數(shù),無法交易!</h2></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><h2>交易完成!</h2></center>") else: print(total_price) return HttpResponse("<center><h2>資金總額不足!</h2></center>") else: return HttpResponse("<center><h2>無效指令!</h2></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><h2>數(shù)據(jù)清算成功!</h2></center>") else: return HttpResponse('<center><h2>非法操作!</h2></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 > <center> <br/> <div > <img src="../static/images/logo.jpg" width="245" height="100"> <h3 >基金模擬系統(tǒng):</h3> <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 > <center> <br/> <div > <img src="../static/images/logo.jpg" width="245" height="100"> <h3 >合規(guī)查詢系統(tǒng):</h3> <form action="/trading/" method="POST"> {% csrf_token %} <label >姓 名: </label> <input type="text" name="name"> <br> <label >代 碼: </label> <input type="text" name="code"> <br> <label >數(shù) 量: </label> <input type="text" name="number"> <br><br> <input type="submit" type="submit" value="提 交"> </form> </div> </center> </body> </html>
3、data_entry.html
<!DOCTYPE html> <html> <head> <title>數(shù)據(jù)錄入系統(tǒng)</title> </head> <body > <center> <div > <h2 >重陽投資</h2> <h5 >基金交易職員信息錄入系統(tǒng):</h5> <form action="/add_fund_manger/" method="post"> {% csrf_token %} <label >姓 名: </label> <input type="text" name="name"> <br> <label >年 齡: </label> <input type="text" name="age"> <br> <label >入職時(shí)間: </label> <input type="text" name="Time"> <br><br> <input type="submit" value="提 交"> </form> <h5 >基金池信息錄入系統(tǒng):</h5> <form action="/add_stock/" method="post"> {% csrf_token %} <label >股票簡(jiǎn)稱: </label> <input type="text" name="stock_name"> <br> <label >代 碼: </label> <input type="text" name="code"> <br><br> <input type="submit" value="提 交"> </form> </div> </center> </body> </html>
4、trade_index.html
<!DOCTYPE html> <html> <head> <title>交易系統(tǒng)</title> </head> <body > <center> <div > <h2 >重陽投資</h2> <h3 >交易系統(tǒng):</h3> <form action="/trading_success/" method="POST"> {% csrf_token %} <label >姓 名: </label> <input type="text" name="name" value={{ name }} readonly="readonly" /> <br> <label >代 碼: </label> <input type="text" name="code" value={{ code }} readonly="readonly" /> <br> <label >數(shù) 量: </label> <input type="text" name="number" value={{ number }} readonly="readonly" /> <br> <label >價(jià) 格: </label> <input type="text" name="price"> <br> <label >操 作: </label> <input type="text" name="operate"> <br><br> <input type="submit" type="submit" value="提 交"> </form> </div> </center> </body> </html>
5、fund_pool.html
<!DOCTYPE html> <html> <head> <title>基金清算系統(tǒng)</title> </head> <body > <center> <br> <div > <h2 >重陽投資</h2> <h5 >基金清算系統(tǒng):</h5> <form action="/account/" method="post"> {% csrf_token %} <label >姓 名: </label> <input type="text" name="name"> <br><br> <input type="submit" value="清 算"> </form> </div> </center> </body> </html>
第六步:創(chuàng)建表結(jié)構(gòu),創(chuàng)建超級(jí)管理員,運(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
以上是“使用Django搭建一個(gè)基金模擬交易系統(tǒng)的案例”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。