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.mzph.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;继续从未排序序列中找…