最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Django搭建一個基金模擬交易系統(tǒng)教程

 更新時間:2019年11月18日 15:09:47   作者:Luzaofa  
今天小編就為大家分享一篇使用Django搭建一個基金模擬交易系統(tǒng)教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

親手教你如何搭建一個基金模擬系統(tǒng)(基于Django框架)

第一步:創(chuàng)建項目、APP以及靜態(tài)文件存儲文件夾

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

在chongyang項目創(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'),
]

第三步:運行項目

python manage.py runserver 0.0.0.0:8000

到目前為止,你已經(jīng)創(chuàng)建了一個擁有極其龐大功能的web網(wǎng)站,后續(xù)只需激活相應(yīng)的服務(wù)即可

url.py # 路由配置文件
views.py # 功能實現(xiàn)文件
admin.py # 后臺管理文件
model.py # 數(shù)據(jù)庫創(chuàng)建文件

第四步:具體項目配置

在配置好前面設(shè)置后直接在相應(yīng)的文件里復(fù)制如下代碼運行項目即可

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:
  # 計算交易所需金額
  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)計
 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">姓&nbsp;&nbsp;&nbsp;名: </label>
  <input type="text" name="name"> <br>
  <label style="color: white; size: 10px">代&nbsp;&nbsp;&nbsp;碼: </label>
  <input type="text" name="code"> <br>
  <label style="color: white; size: 10px">數(shù)&nbsp;&nbsp;&nbsp;量: </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">姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名: </label>
  <input type="text" name="name"> <br>
  <label style="color: white; size: 10px">年&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;齡: </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">代&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;碼: </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">姓&nbsp;&nbsp;&nbsp;名: </label>
  <input type="text" name="name" value={{ name }} readonly="readonly" /> <br>
  <label style="color: white; size: 10px">代&nbsp;&nbsp;&nbsp;碼: </label>
  <input type="text" name="code" value={{ code }} readonly="readonly" /> <br>
  <label style="color: white; size: 10px">數(shù)&nbsp;&nbsp;&nbsp;量: </label>
  <input type="text" name="number" value={{ number }} readonly="readonly" /> <br>
  <label style="color: white; size: 10px">價&nbsp;&nbsp;&nbsp;格: </label>
  <input type="text" name="price"> <br>
  <label style="color: white; size: 10px">操&nbsp;&nbsp;&nbsp;作: </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">姓&nbsp;&nbsp;名: </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)建超級管理員,運行項目即可

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的一點總結(jié)分享,有不足的地方歡迎大家指導(dǎo)學(xué)習(xí),一起進(jìn)步。

這篇使用Django搭建一個基金模擬交易系統(tǒng)教程就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • python生成二維矩陣的兩種方法小結(jié)

    python生成二維矩陣的兩種方法小結(jié)

    本文主要介紹了python生成二維矩陣,包含列表生成m行n列的矩陣和numpy生成想要維度的矩陣的兩種方法,具有一定的參考價值,感興趣的可以了解一下
    2024-08-08
  • Python爬蟲之urllib庫詳解

    Python爬蟲之urllib庫詳解

    大家好,本篇文章主要講的是Python爬蟲之urllib庫詳解,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下
    2022-02-02
  • python實現(xiàn)簡單倒計時功能

    python實現(xiàn)簡單倒計時功能

    這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)簡單倒計時功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-04-04
  • Pygame如何使用精靈和碰撞檢測

    Pygame如何使用精靈和碰撞檢測

    本文主要介紹了Pygame如何使用精靈和碰撞檢測,它們能夠幫助我們跟蹤屏幕上移動的大量圖像。我們還會了解如何檢測兩個圖像相互重疊或者碰撞的方法。
    2021-11-11
  • 三步解決python PermissionError: [WinError 5]拒絕訪問的情況

    三步解決python PermissionError: [WinError 5]拒絕訪問的情況

    這篇文章主要介紹了三步解決python PermissionError: [WinError 5]拒絕訪問的情況,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04
  • Python中類型檢查的詳細(xì)介紹

    Python中類型檢查的詳細(xì)介紹

    Python是一種非常動態(tài)的語言,函數(shù)定義中完全沒有類型約束。下面這篇文章主要給大家詳細(xì)介紹了Python中類型檢查的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-02-02
  • Python3+OpenCV2實現(xiàn)圖像的幾何變換(平移、鏡像、縮放、旋轉(zhuǎn)、仿射)

    Python3+OpenCV2實現(xiàn)圖像的幾何變換(平移、鏡像、縮放、旋轉(zhuǎn)、仿射)

    這篇文章主要介紹了Python3+OpenCV2實現(xiàn)圖像的幾何變換(平移、鏡像、縮放、旋轉(zhuǎn)、仿射),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-05-05
  • Python的Django框架中的表單處理示例

    Python的Django框架中的表單處理示例

    這篇文章主要介紹了Python的Django框架中的表單處理示例,表單處理是Django中的基礎(chǔ)操作,需要的朋友可以參考下
    2015-07-07
  • Python 占位符的使用方法詳解

    Python 占位符的使用方法詳解

    這篇文章主要介紹了Python 占位符的使用方法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-07-07
  • Python閉包思想與用法淺析

    Python閉包思想與用法淺析

    這篇文章主要介紹了Python閉包思想與用法,結(jié)合實例形式簡單分析了Python閉包的概念、原理、使用方法與相關(guān)操作注意事項,需要的朋友可以參考下
    2018-12-12

最新評論

同心县| 昭觉县| 云浮市| 彭阳县| 文昌市| 枞阳县| 洞口县| 双桥区| 永胜县| 宜章县| 青海省| 化隆| 兰西县| 开原市| 中宁县| 六安市| 建瓯市| 晴隆县| 长沙县| 定襄县| 乌兰县| 双峰县| 浪卡子县| 安宁市| 昔阳县| 道孚县| 中宁县| 文安县| 张家港市| 甘肃省| 江孜县| 扎鲁特旗| 腾冲县| 两当县| 锦州市| 长兴县| 溆浦县| 沐川县| 青田县| 东光县| 河北区|