echarts 詞云_python Flask+爬蟲制作股票查詢、歷史數據、股評詞云網頁

自學python的數據分析,爬蟲后,花了幾天時間看視頻學習Flask做了一個簡單的股票查詢網頁。本來還想著加入一些其他功能,比如財務指標分析,輿情分析,最完美的想法是做成一個股票評分系統,輸入股票代碼可以自動輸出分析結果和最終評分以及排名。但是限于沒有服務器(不想花錢買)于是先到此為止,后面計劃先實現股票評分的本地系統化,然后有機會再部署到網站上。有類似想法的歡迎交流~

先放一張最終效果圖。網頁左上角輸入股票代碼,可以在下方顯示實時行情、歷史走勢、股評詞云等信息。這是本菜雞第一次開發網頁,所以是非常簡單的版本。后面想要繼續實現本地化的打分系統,因為雖然同花順等炒股軟件包含智能篩選功能,但是缺少一些個性化的分析指標,不知道我的這個想法是否可行?有沒有價值去做?求建議!

fc5a21c83e17a029a7d06542cc89afd6.png

前端頁面輸入股票代碼傳到后端,即可從網易財經、騰訊財經提供的數據接口api爬取相關股票的數據,然后利用ajax和exharts呈現到網頁上。右下方的詞云圖是從東方財富爬取的股評信息后制作的。

具體實現過程一共花了不到一周時間,下面是全部文檔信息。主要文件有四個,app.py為flask寫的后端,main.html和main.css寫前端,utils.py寫了一些爬蟲和數據處理的函數。

fc2e50e559adc53992f3fb4ae0311526.png

下面分別貼出4個文檔的代碼,可能包括一些冗余信息(連接mysql的一些操作,之前想做財務指標呈現是用到的)。

1 app.py

flask寫的后端,模式比較固定,難點在于前后臺數據的交互(用到ajax)。

from flask import Flask
from flask import request
from flask import render_template
from flask import jsonify
# import pymysql
import uitls
import sys
from  jieba.analyse import extract_tags
import string# sys.setrecursionlimit(100000)
stock_id = '600009'app = Flask(__name__)@app.route("/be")
def get_data():data = uitls.get_be_data(str(stock_id))return jsonify({"股票名稱": data[1],"當前價格": data[3],"成交量": data[6],"漲跌幅": data[32],"流通市值": data[44]})@app.route("/his", methods=["get", "post"])
def get_history_data():msg = uitls.get_history_data(str(stock_id))print(msg)print(type(msg))return jsonify({"日期":msg['日期'],"開盤價":msg['開盤價'],"收盤價":msg['收盤價'],"最低價":msg['最低價'],"最高價":msg['最高價']})# jsonify({"日期": msg['日期'][0],"開盤價":msg['開盤價'][0]})@app.route("/gp", methods=["get", "post"])
def get_guping():data = uitls.get_guping(stock_id)d = []for i in data:k = i.rstrip(string.digits)v = i[len(k):]ks = extract_tags(k)# print(v)for j in ks:if not j.isdigit():d.append({'name': j, 'value': v})return jsonify({'kws':d})@app.route("/time", methods=["get", "post"])
def get_time():return uitls.get_time()@app.route("/", methods=["get", "post"])
def input_id():return render_template("main.html")@app.route("/ind", methods=["get", "post"])
def get_id():global stock_idstock_id = request.values.get("股票代碼")print(stock_id)return render_template("main.html")if __name__ == '__main__':app.run()

2.main.html

這里包含了echarts中的K線圖和詞云圖模板,所以看起來比較長。

<!DOCTYPE html>
<html><head link rel="shortcut icon" href="#" /><meta charset="utf-8"><title>股票數據</title><script src="../static/js/jquery-3.5.1.min.js"></script><script src="../static/js/echarts.min.js"></script><script src="../static/js/echarts-wordcloud.min.js"></script><link href = "../static/css/main.css" rel = "stylesheet"/></head><body><div id = "title">股票查詢</div><form action="/ind">股票代碼 <input name = "股票代碼" placeholder="請輸入股票代碼"><button>提交</button></form><div id = "tim">我是時間</div><div id = "be"><div class ="tex"><h2>股票名稱</h2></div><div class ="tex"><h2>當前價格</h2></div><div class ="tex"><h2>成交量</h2></div><div class ="tex"><h2>漲跌幅</h2></div><div class ="tex"><h2>流通市值</h2></div><div class ="num"><h1>123</h1></div><div class ="num"><h1>123</h1></div><div class ="num"><h1>123</h1></div><div class ="num"><h1>123</h1></div><div class ="num"><h1>123</h1></div></div><div id="bl"  style="width: 800px;height:435px;">我是瞎做</div><script>var hisdata = echarts.init(document.getElementById('bl'));var upColor = '#ec0000';var upBorderColor = '#8A0000';var downColor = '#00da3c';var downBorderColor = '#008F28';   hisdata_option = {title: {text: '歷史趨勢',left: 0},tooltip: {trigger: 'axis',axisPointer: {type: 'cross'}},legend: {data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30']},grid: {left: '10%',right: '10%',bottom: '15%'},xAxis: {type: 'category',data: [],scale: true,boundaryGap: false,axisLine: {onZero: false},splitLine: {show: false},splitNumber: 20,min: 'dataMin',max: 'dataMax'},yAxis: {scale: true,splitArea: {show: true}},dataZoom: [{type: 'inside',start: 50,end: 100},{show: true,type: 'slider',top: '90%',start: 50,end: 100}],series: [{name: '日K',type: 'candlestick',data: [],itemStyle: {color: upColor,color0: downColor,borderColor: upBorderColor,borderColor0: downBorderColor},markPoint: {label: {normal: {formatter: function (param) {return param != null ? Math.round(param.value) : '';}}},data: [{name: 'XX標點',coord: ['2013/5/31', 2300],value: 2300,itemStyle: {color: 'rgb(41,60,85)'}},{name: 'highest value',type: 'max',valueDim: 'highest'},{name: 'lowest value',type: 'min',valueDim: 'lowest'},{name: 'average value on close',type: 'average',valueDim: 'close'}],tooltip: {formatter: function (param) {return param.name + '<br>' + (param.data.coord || '');}}},markLine: {symbol: ['none', 'none'],data: [[{name: 'from lowest to highest',type: 'min',valueDim: 'lowest',symbol: 'circle',symbolSize: 10,label: {show: false},emphasis: {label: {show: false}}},{type: 'max',valueDim: 'highest',symbol: 'circle',symbolSize: 10,label: {show: false},emphasis: {label: {show: false}}}],{name: 'min line on close',type: 'min',valueDim: 'close'},{name: 'max line on close',type: 'max',valueDim: 'close'}]}},{name: 'MA5',type: 'line',data: '',smooth: true,lineStyle: {opacity: 0.5}},{name: 'MA10',type: 'line',data: '',smooth: true,lineStyle: {opacity: 0.5}},{name: 'MA20',type: 'line',data: '',smooth: true,lineStyle: {opacity: 0.5}},{name: 'MA30',type: 'line',data: '',smooth: true,lineStyle: {opacity: 0.5}},]};</script><div id="br" style="width: 800px;height:435px;">我是下游</div><script>var gp = echarts.init(document.getElementById('br'));var ddd = [{name: 'Farrah Abraham',value: 366,// Style of single text}];var maskResource = new Image()maskResource.src=image1;gp_option = {title:{text: '股評詞云圖',left:'center',},//數據可以點擊tooltip:{show:false},series: [{type: 'wordCloud',// The shape of the "cloud" to draw. Can be any polar equation represented as a// callback function, or a keyword present. Available presents are circle (default),// cardioid (apple or heart shape curve, the most known polar equation), diamond (// alias of square), triangle-forward, triangle, (alias of triangle-upright, pentagon, and star.shape: 'circle',// A silhouette image which the white area will be excluded from drawing texts.// The shape option will continue to apply as the shape of the cloud to grow.// maskImage: maskResource,//         // Folllowing left/top/width/height/right/bottom are used for positioning the word cloud//         // Default to be put in the center and has 75% x 80% size.left: 'center',top: 'center',width: '70%',height: '80%',right: null,bottom: null,// Text size range which the value in data will be mapped to.// Default to have minimum 12px and maximum 60px size.sizeRange: [12, 60],// Text rotation range and step in degree. Text will be rotated randomly in range [-90, 90] by rotationStep 45rotationRange: [-90, 90],rotationStep: 45,// size of the grid in pixels for marking the availability of the canvas// the larger the grid size, the bigger the gap between words.gridSize: 8,// set to true to allow word being draw partly outside of the canvas.// Allow word bigger than the size of the canvas to be drawndrawOutOfBound: false,// Global text styletextStyle: {normal: {fontFamily: 'sans-serif',fontWeight: 'bold',// Color can be a callback function or a color stringcolor: function () {// Random colorreturn 'rgb(' + [Math.round(Math.random() * 160),Math.round(Math.random() * 160),Math.round(Math.random() * 160)].join(',') + ')';}},emphasis: {shadowBlur: 10,shadowColor: '#333'}},// Data is an array. Each array item must have name and value property.data: [{name: 'Farrah Abraham',value: 366,// Style of single text}]}]}</script><script  >function getatime(){$.ajax({url:"/time",success:function(d){$("#tim").html(d)},error:function(jqXHR, textStatus, errorThrown){console.log(jqXHR.responseText);}})}function get_be_data(){$.ajax({url:"/be",success:function(data){$(".num h1").eq(0).text(data['股票名稱'])$(".num h1").eq(1).text(data['當前價格'])$(".num h1").eq(2).text(data['成交量'])$(".num h1").eq(3).text(data['漲跌幅'])$(".num h1").eq(4).text(data['流通市值'])},error:function(jqXHR, textStatus, errorThrown){console.log(jqXHR.responseText);}})}function get_guping(){$.ajax({url:"/gp",success:function(data){gp_option.series[0].data = data.kws;gp.setOption(gp_option);},error:function(jqXHR, textStatus, errorThrown){console.log(jqXHR.responseText);}})}function get_his_data(){$.ajax({url:"/his",                success:function(msg){                    var datalen = msg['日期'].lengthk_time =[]k_value = []for (var i = 0; i < datalen; i++) {k_time.push(msg['日期'][i]);k_value.push([msg['開盤價'][i],msg['收盤價'][i],msg['最低價'][i],msg['最高價'][i]])                               }  console.log(k_time)console.log(k_value)function calculateMA(dayCount) {var result = [];for (var i = 0, len = k_value.length; i < len; i++) {if (i < dayCount) {result.push('-');continue;}var sum = 0;for (var j = 0; j < dayCount; j++) {sum += k_value[i - j][1];}result.push(sum / dayCount);}return result;}hisdata_option.xAxis.data = k_time;hisdata_option.series[0].data = k_value;hisdata_option.series[1].data = calculateMA(5);hisdata_option.series[2].data = calculateMA(10);hisdata_option.series[3].data = calculateMA(20);hisdata_option.series[4].data = calculateMA(30);hisdata.setOption(hisdata_option);},error:function(){console.log("獲取失敗");}})          }setInterval(getatime,1000)setInterval(get_be_data,1000)get_his_data()get_guping()</script></body></html>

3 .main.css

用于網頁整體布局。

body{margin: 0;background: #333;
}#title{position: absolute;width: 40%;height: 10%;top: 0;left: 30%;/* background-color: #666666; */color: white;font-size: 30px;display: flex;align-items: center;justify-content: center;
}#ins{position: absolute;width: 40%;height: 20%;top: 10%;left: 0;background-color: grey;
}#tim{position: absolute;/* width: 30%; */height: 10%;top: 5%;right: 2%;color: #FFFFFF;font-size: 20px;/* background-color: green;     */
}#be{position: absolute;width: 100%;height: 30%;top: 10%;left: 0;color: white;/* background-color: #777777; */
}#bl{position: absolute;width: 50%;height: 60%;top: 40%;left: 0;background-color: #888888;
}#br{position: absolute;width: 50%;height: 60%;top: 40%;left: 50%;background-color: #999999;
}.num{width: 20%;float: left;display: flex;align-items: center;justify-content: center;color:yellow;font-size: 20px;
}.tex{width: 20%;float: left;font-family: "幼圓";display: flex;align-items: center;justify-content: center;

4.utils.py

寫了一些用于爬取數據和處理數據的函數。

import time
import pymysql
import urllib.request
import pandas as pd
import requests
import re
from bs4 import BeautifulSoupdef get_time():time_str = time.strftime("%Y{}%m{}%d{} %X")return time_str.format("年", "月", "日")def get_conn():conn = pymysql.connect(host='127.0.0.1', user='root', password='', db='stock', charset='utf8')cursor = conn.cursor()return conn,cursordef close_conn(conn,cursor):cursor.close()conn.close()def query(sql,*args):conn,cursor = get_conn()cursor.execute(sql,args)res = cursor.fetchall()close_conn(conn,cursor)return res# def get_be_data(*args):
#     sql = "SELECT * FROM hangqing where stockid = %s"
#     res = query(sql, args)
#     print(res)
#     return res[0]
def get_be_data(code):url = 'http://qt.gtimg.cn/q=sh' + str(code)content = urllib.request.urlopen(url, timeout=2).read()content = content.decode("gbk").encode("utf-8").decode("utf8", "ignore")content = content.split('~')return contentdef get_history_data(code):url = 'http://quotes.money.163.com/service/chddata.html?code=0'+str(code)try:content = urllib.request.urlopen(url).read()content = content.decode("gbk").encode("utf-8")with open('E:/hisdata.csv', 'wb')as f:f.write(content)data = pd.read_csv('E:/hisdata.csv')# data = data.to_dict('record')data = data[["日期","開盤價","收盤價","最低價","最高價"]]# print(data)data = data.to_dict()data['日期'] = list(data['日期'].values())data['開盤價'] = list(data['開盤價'].values())data['收盤價'] = list(data['收盤價'].values())data['最低價'] = list(data['最低價'].values())data['最高價'] = list(data['最高價'].values())data['日期'] = data['日期'][::-1]data['開盤價'] = data['開盤價'][::-1]data['收盤價'] = data['收盤價'][::-1]data['最低價'] = data['最低價'][::-1]data['最高價'] = data['最高價'][::-1]except Exception as e:print(e)return datadef get_guping(id):max_page = 2  # input('請輸入爬取頁數')b = []# head = {'User-Agent':' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'}for page in range(1, int(max_page) + 1):url = 'http://guba.eastmoney.com/list,{}_{}.html'.format(id, page)res = requests.get(url)soup = BeautifulSoup(res.text, 'html.parser')urllist = soup.find_all('div', {'class': 'articleh'})for i in urllist:if i.find('a') != None:try:title = i.find('a').get_text()yuedu = i.find('span',{'class':'l1 a1'}).get_text()# time = i.find('span', {'class': 'l5 a5'}).get_text()# a = [title + yuedu]b.append(title + yuedu)except Exception as e:print(e)passreturn b[7:]if __name__ == '__main__':msg = get_guping(600002)print(msg)

后面想要繼續實現本地化的打分系統,因為雖然同花順等炒股軟件包含智能篩選功能,但是缺少一些個性化的分析指標,不知道我的這個想法是否可行?有沒有價值去做?求建議!

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/397104.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/397104.shtml
英文地址,請注明出處:http://en.pswp.cn/news/397104.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

JavaSE基礎知識(6)—異常和異常處理

一、異常的理解及體系結構圖 1、理解 異常&#xff1a;程序運行過程中發生的不正常現象。java中的錯誤&#xff1a;   語法錯誤   運行異常   邏輯錯誤 2、體系圖 java程序在執行過程中所發生的異常分為兩類&#xff1a; Error&#xff1a;Java虛擬機無法解決的嚴重問題。…

peripheralStateNotificationCB

1 /*********************************************************************2 * fn peripheralStateNotificationCB 外圍設備 狀態 通知 回調函數3 *4 * brief Notification from the profile of a state change. 通知來自于profile的狀態改變&#xff01;5 *6 * …

mysql dump 1017_MySQL數據庫導出 - Can't Wait Any Longer - OSCHINA - 中文開源技術交流社區...

本文內容主要來自MySQL官方文檔&#xff1a;“MySQL5.1 Reference&#xff0c;2.10.3. 將MySQL數據庫拷貝到另一臺機器”注意&#xff1a;參數名與值間可以不用空格&#xff0c;如-uroot或-u root均可&#xff1b;某些參數會有不同含義1.數據庫導出(-A導出所有數據庫&#xff0…

Jsp2.0自定義標簽(第二天)——自定義循環標簽

今天是學習自定義標簽的第二天&#xff0c;主要是寫一個自定義的循環標簽。 先看效果圖&#xff1a; 前臺頁面Jsp代碼 <% page language"java" contentType"text/html; charsetUTF-8"pageEncoding"UTF-8"%> <%taglib prefix"myout…

正則表達式以什么開頭以什么結尾_股票hk是什么意思,股票st開頭是什么意思,新通聯股票...

股票hk是什么意思,股票st開頭是什么意思,新通聯股票股票hk是什么意思,股票st開頭是什么意思,新通聯股票我們首先解決時間跨度問題&#xff1a;如果您為諸如退休之類的遙遠目標投資&#xff0c;則應主要投資股票(同樣&#xff0c;我們建議您通過共同基金投資)。心理控制第一&…

讀書筆記--SQL必知必會03--排序檢索數據

3.1 排序數據 子句&#xff08;clause&#xff09; SQL語句由子句構成。一個子句通常由一個關鍵字加上所提供的數據組成。 ORDER BY子句可以取一個或多個列的名字&#xff0c;將SELECT語句檢索出的數據進行排序。 ORDER BY子句可以使用非檢索的列排序數據。 ORDER BY子句必須作…

mysql中編寫匿名塊_Oracle數據庫之Oracle_PL/SQL(1) 匿名塊

本文主要向大家介紹了Oracle數據庫之Oracle_PL/SQL(1) 匿名塊&#xff0c;通過具體的內容向大家展現&#xff0c;希望對大家學習Oracle數據庫有所幫助。1. PL/SQL 簡介PL/SQL是一種比較復雜的程序設計語言, 用于從各種環境中訪問Oracle數據庫。為什么使用PL/SQL&#xff1f;Ora…

安裝了多個Oracle11g的客戶端,哪個客戶端的tnsnames.ora會起作用?

如果我們由于需要安裝了多個Oracle的client&#xff0c;哪個客戶端的tnsnames.ora會起作用呢&#xff1f; 答案是&#xff1a; 在安裝好clinent端后&#xff0c;安裝程序會把client的bin目錄放到path里面&#xff0c;path中在前面的client會被首先搜索&#xff0c;其中的tnsnam…

電腦顯示連接了網絡但是不能上網_為什么電腦插上網線顯示已連接卻上不了網...

嘗試斷一下網&#xff0c;或者重啟一下系統看一下是否解決&#xff1b;也可能是開啟了網絡代理&#xff0c;可以重置一下瀏覽器或者網絡設置&#xff1b;還可以使用安全管家軟件&#xff0c;掃描一下網絡設置。以下是詳細介紹&#xff1a;1、有時候系統顯示已經連接其實并沒有真…

Atcoder ARC101 E 樹dp

https://arc101.contest.atcoder.jp/tasks/arc101_c 題解是也是dp&#xff0c;好像是容斥做的&#xff0c;但是看不懂&#xff0c;而且也好像沒講怎么變n^2&#xff0c;看了寫大佬的代碼&#xff0c;自己理解了一下 #include <bits/stdc.h> #include <ext/pb_ds/assoc…

compress命令--Linux命令應用大詞典729個命令解讀

內容來源于人民郵電出版社《Linux命令應用大詞典》講述729個命令&#xff0c;1935個例子學習Linux系統的參考書、案頭書&#xff0c;遇到不懂的命令或命令選項一查即可爭取每天都發布內容本文出自 “airfish2000” 博客&#xff0c;更多命令查看博客&#xff1a;http://airfish…

javaweb學習總結(三十九)——數據庫連接池

javaweb學習總結(三十九)——數據庫連接池 數據庫連接池的實現及原理 JNDI 在 J2EE 中的角色轉載于:https://www.cnblogs.com/daishuguang/p/5041845.html

python getopterror_python3 getopt用法

python channel_builder.py -s /Users/graypn/ -d /Users/graypn/Documents -m 7 --outreport/xx.html參數也分長格式和短格式短格式&#xff1a;-s長格式&#xff1a;--sourceopts, args getopt.getopt(sys.argv[1:], "hs:d:m:v:p:c:",["help", "sr…

excel刪除空行_Excel里99.9%的人都踩過的坑,早看早避開!

本文作者丨可可&#xff08;小 E 背后的小仙女&#xff09;本文由「秋葉 Excel」原創發布如需轉載&#xff0c;請在公眾號發送關鍵詞「轉載」查看說明2019 年上班第一天感覺怎么樣呢&#xff1f;望著滿屏幕鋪天蓋地的表格&#xff0c;我只能摸摸自己還沒下去的小肚子&#xff0…

CentOS 6.5 Zabbix-agent3.2 安裝 1.0版

1.關閉防火墻service iptables stop2.更換源、安裝zabbix-agentrpm -ivh http://repo.zabbix.com/zabbix/3.2/rhel/6/x86_64/zabbix-release-3.2-1.el6.noarch.rpmyum install -y zabbix-agent3.修改配置文件vim /etc/zabbix/zabbix_agentd.confServer192.168.8.228 ser…

centos下利用httpd搭建http服務器方法

centos下利用httpd搭建http服務器方法 1. 解決的問題 在開發測試過程中&#xff0c;分析圖片任務需要將圖片保存在服務器端&#xff0c;通過url來訪問和下載該圖片&#xff0c;這就需要使用一臺圖片服務器&#xff0c;但常常遇到圖片服務器匱乏的情況&#xff0c;為了解決該問題…

[轉]Java7中的ForkJoin并發框架初探(上)——需求背景和設計原理

詳見&#xff1a; http://blog.yemou.net/article/query/info/tytfjhfascvhzxcytp83 這篇我們來簡要了解一下JavaSE7中提供的一個新特性 —— Fork Join 框架。 0. 處理器發展和需求背景 回想一下并發開發的初衷&#xff0c;其實可以說是有兩點&#xff0c;或者說可以從兩個方面…

安裝oculus運行時出現問題_U盤安裝windows10出現的問題解決方法

安裝windows10 出現的問題之前安裝windows10都沒什么問題&#xff0c;今天安裝windows10出現了好多問題&#xff0c;記錄一下。我這個教程我覺得是最好的安裝教程安裝windows10教程問題1. 我們無法創建新的分區&#xff0c;找不到現有分區&#xff08;或者因為MBR分區表問題&am…

JavaFx導出文件

導出文件格式可選 protected void handExportDateAction(ActionEvent event) {// ShowDialog.showConfirmDialog(FXRobotHelper.getStages().get(0),// "是否導出數據到txt&#xff1f;", "信息");FileChooser fileChooser new FileChooser();FileChooser…

python選擇排序從大到小_Python實現選擇排序

一、選擇排序簡介選擇排序(Selection sort)是一種簡單直觀的排序算法。選擇排序首先從待排序列表中找到最小(大)的元素&#xff0c;存放到元素列表的起始位置(與起始位置進行交換)&#xff0c;作為已排序序列&#xff0c;第一輪排序完成。然后&#xff0c;繼續從未排序序列中找…