你可以通过以下几种方式获取 Apache ECharts (incubating)TM。

引入 ECharts

通过标签方式直接引入构建好的 echarts 文件

1
2
3
4
5
6
7
8
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!-- 引入 ECharts 文件 -->
<script src="echarts.min.js"></script>
</head>
</html>

绘制一个简单的图表

在绘图前我们需要为 ECharts 准备一个具备高宽的 DOM 容器。

1
2
3
4
<body>
<!-- 为 ECharts 准备一个具备大小(宽高)的 DOM -->
<div id="main" style="width: 600px;height:400px;"></div>
</body>

然后就可以通过 echarts.init 方法初始化一个 echarts 实例并通过 setOption 方法生成一个简单的柱状图,下面是完整代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ECharts</title>
<!-- 引入 echarts.js -->
<script src="echarts.min.js"></script>
</head>
<body>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));

// 指定图表的配置项和数据
var option = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data:['销量']
},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
};

// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
</body>
</html>

这样你的第一个图表就诞生了!

在这里插入图片描述

爬取数据,并使用websocket连接,发送数据到前端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import requests

from lxml import etree

from dwebsocket.decorators import accept_websocket

import json

import time

def exchange():
url = 'http://fx.cmbchina.com/hq/'

# ua伪装

header = {

'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36"

}

res = requests.get(url=url,headers=header)

tree = etree.HTML(res.text)

# xpath定位,爬取数据

tr_list = tree.xpath('//div[@id="realRateInfo"]/table/tr[position()>1]')

data={
'Time': tr_list[2].xpath("./td[8]/text()")[0].replace('\r', "").replace("n", "").strip(),

'HongKong':format(float(tr_list[0].xpath("./td[2]/text()")[0].replace('\r',"").replace("n","").strip())/float(tr_list[0].xpath("./td[4]/text()")[0].replace('\r',"").replace("n","").strip()),".4f"),

'NewZealand': format(float(tr_list[1].xpath("./td[2]/text()")[0].replace('\r',"").replace("n","").strip())/float(tr_list[1].xpath("./td[4]/text()")[0].replace('\r',"").replace("n","").strip()),".4f"),

'Australia': format(float(tr_list[2].xpath("./td[2]/text()")[0].replace('\r',"").replace("n","").strip())/float(tr_list[2].xpath("./td[4]/text()")[0].replace('\r',"").replace("n","").strip()),".4f"),

'USA': format(float(tr_list[3].xpath("./td[2]/text()")[0].replace('\r',"").replace("n","").strip())/float(tr_list[3].xpath("./td[4]/text()")[0].replace('\r',"").replace("n","").strip()),".4f"),

'Europe' : format(float(tr_list[4].xpath("./td[2]/text()")[0].replace('\r',"").replace("n","").strip())/float(tr_list[4].xpath("./td[4]/text()")[0].replace('\r',"").replace("n","").strip()),".4f"),

'Canada' : format(float(tr_list[5].xpath("./td[2]/text()")[0].replace('\r',"").replace("n","").strip())/float(tr_list[5].xpath("./td[4]/text()")[0].replace('\r',"").replace("n","").strip()),".4f"),

'English' : format(float(tr_list[6].xpath("./td[2]/text()")[0].replace('\r',"").replace("n","").strip())/float(tr_list[6].xpath("./td[4]/text()")[0].replace('\r',"").replace("n","").strip()),".4f"),

'Japaense' : format(float(tr_list[7].xpath("./td[2]/text()")[0].replace('\r',"").replace("n","").strip())/float(tr_list[7].xpath("./td[4]/text()")[0].replace('\r',"").replace("n","").strip()),".4f"),

'Singapore' : format(float(tr_list[8].xpath("./td[2]/text()")[0].replace('\r',"").replace("n","").strip())/float(tr_list[8].xpath("./td[4]/text()")[0].replace('\r',"").replace("n","").strip()),".4f"),

'Switzerland' : format(float(tr_list[9].xpath("./td[2]/text()")[0].replace('\r',"").replace("n","").strip())/float(tr_list[9].xpath("./td[4]/text()")[0].replace('\r',"").replace("n","").strip()),".4f"),

}
return data

exchange()

# 容器
clients={}

# websocket连接

@accept_websocket

def Websocketlink(request):


if request.is_websocket():

key = request.session.session_key # 缓存在session中的键

print(key)

while True:

message = request.websocket.wait()

if not message:

clients.clear()

break

else:

while True:

clients[str(key)] = request.websocket

for i in clients:
message = exchange()

clients[i].send(json.dumps(message))

time.sleep(2)

K线图绘制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271

//数组处理
function splitData(rawData) {
var datas = [];
var times = [];
var vols = [];
var macds = []; var difs = []; var deas = [];
for (var i = 0; i < rawData.length; i++) {
datas.push(rawData[i]);
times.push(rawData[i].splice(0, 1)[0]);
vols.push(rawData[i][4]);
macds.push(rawData[i][6]);
difs.push(rawData[i][7]);
deas.push(rawData[i][8]);
}
return {
datas: datas,
times: times,
vols: vols,
macds: macds,
difs: difs,
deas: deas
};
}

//分段计算
function fenduans(){
var markLineData = [];
var idx = 0; var tag = 0; var vols = 0;
for (var i = 0; i < data.times.length; i++) {
//初始化数据
if(data.datas[i][5] != 0 && tag == 0){
idx = i; vols = data.datas[i][4]; tag = 1;
}
if(tag == 1){ vols += data.datas[i][4]; }
if(data.datas[i][5] != 0 && tag == 1){
markLineData.push([{
xAxis: idx,
yAxis: data.datas[idx][1]>data.datas[idx][0]?(data.datas[idx][3]).toFixed(2):(data.datas[idx][2]).toFixed(2),
value: vols
}, {
xAxis: i,
yAxis: data.datas[i][1]>data.datas[i][0]?(data.datas[i][3]).toFixed(2):(data.datas[i][2]).toFixed(2)
}]);
idx = i; vols = data.datas[i][4]; tag = 2;
}

//更替数据
if(tag == 2){ vols += data.datas[i][4]; }
if(data.datas[i][5] != 0 && tag == 2){
markLineData.push([{
xAxis: idx,
yAxis: data.datas[idx][1]>data.datas[idx][0]?(data.datas[idx][3]).toFixed(2):(data.datas[idx][2]).toFixed(2),
value: (vols/(i-idx+1)).toFixed(2)+' M'
}, {
xAxis: i,
yAxis: data.datas[i][1]>data.datas[i][0]?(data.datas[i][3]).toFixed(2):(data.datas[i][2]).toFixed(2)
}]);
idx = i; vols = data.datas[i][4];
}
}
return markLineData;
}

//MA计算公式
function calculateMA(dayCount) {
var result = [];
for (var i = 0, len = data.times.length; i < len; i++) {
if (i < dayCount) {
result.push('-');
continue;
}
var sum = 0;
for (var j = 0; j < dayCount; j++) {
sum += data.datas[i - j][1];
}
result.push((sum / dayCount).toFixed(2));
}
return result;
}

var option = {
title: {
text: 'K线周期图表(matols.com)',
left: 0
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'line'
}
},
legend: {
data: ['KLine', 'MA5']
},
grid: [ {
left: '3%',
right: '1%',
height: '60%'
},{
left: '3%',
right: '1%',
top: '71%',
height: '10%'
},{
left: '3%',
right: '1%',
top: '82%',
height: '14%'
}],
xAxis: [{
type: 'category',
data: data.times,
scale: true,
boundaryGap: false,
axisLine: { onZero: false },
splitLine: { show: false },
splitNumber: 20,
min: 'dataMin',
max: 'dataMax'
},{
type: 'category',
gridIndex: 1,
data: data.times,
axisLabel: {show: false}
},{
type: 'category',
gridIndex: 2,
data: data.times,
axisLabel: {show: false}
}],
yAxis: [{
scale: true,
splitArea: {
show: false
}
},{
gridIndex: 1,
splitNumber: 3,
axisLine: {onZero: false},
axisTick: {show: false},
splitLine: {show: false},
axisLabel: {show: true}
},{
gridIndex: 2,
splitNumber: 4,
axisLine: {onZero: false},
axisTick: {show: false},
splitLine: {show: false},
axisLabel: {show: true}
}],
dataZoom: [{
type: 'inside',
xAxisIndex: [0, 0],
start: 20,
end: 100
},{
show: true,
xAxisIndex: [0, 1],
type: 'slider',
top: '97%',
start: 20,
end: 100
},{
show: false,
xAxisIndex: [0, 2],
type: 'slider',
start: 20,
end: 100
}],
series: [{
name: 'K线周期图表(matols.com)',
type: 'candlestick',
data: data.datas,
itemStyle: {
normal: {
color: '#ef232a',
color0: '#14b143',
borderColor: '#ef232a',
borderColor0: '#14b143'
}
},
markArea: {
silent: true,
itemStyle: {
normal: {
color: 'Honeydew'
}
},
data: fenduans()
},
markPoint: {
data: [
{type: 'max', name: '最大值'},
{type: 'min', name: '最小值'}
]
},
markLine: {
label: {
normal: {
position: 'middle',
textStyle:{color:'Blue',fontSize: 15}
}
},
data: fenduans(),
symbol: ['circle', 'none']

}
}, {
name: 'MA5',
type: 'line',
data: calculateMA(5),
smooth: true,
lineStyle: {
normal: {
opacity: 0.5
}
}
},{
name: 'Volumn',
type: 'bar',
xAxisIndex: 1,
yAxisIndex: 1,
data: data.vols,
itemStyle: {
normal: {
color: function(params) {
var colorList;
if (data.datas[params.dataIndex][1]>data.datas[params.dataIndex][0]) {
colorList = '#ef232a';
} else {
colorList = '#14b143';
}
return colorList;
},
}
}
},{
name: 'MACD',
type: 'bar',
xAxisIndex: 2,
yAxisIndex: 2,
data: data.macds,
itemStyle: {
normal: {
color: function(params) {
var colorList;
if (params.data >= 0) {
colorList = '#ef232a';
} else {
colorList = '#14b143';
}
return colorList;
},
}
}
},{
name: 'DIF',
type: 'line',
xAxisIndex: 2,
yAxisIndex: 2,
data: data.difs
},{
name: 'DEA',
type: 'line',
xAxisIndex: 2,
yAxisIndex: 2,
data: data.deas
}
]
};

设X轴、Y轴接收后端爬取的数据并展示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
<template>

<div id="mychart" class="chart" :style="{width: '100%', height: '500px'}" :option='exchange'></div>

</template>

<script>
import echarts from 'echarts'
export default {
name: 'demo2',
data() {
return {
// x轴
Time: [],

// y轴
HongKong: [],

NewZealand: [],

USA: [],

Europe: [],

Canada: [],

English: [],

Japaense: [],

Singapore: [],

Switzerland: [],

Australia:[]


}
},

watch:{
Time:function(){

this.exchange()
}
},

mounted() {

this.exchange()

this.websocketinit()
},


methods: {
exchange() {
var option = {

title: {

text: '外汇实时汇率'

},
tooltip: {

trigger: 'axis'

},
legend: {

data:[ '新西兰元', '澳大利亚元', '美元', '欧元',"加拿大元","英镑","新加坡元","瑞士法郎"]

},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
// x轴
xAxis: {
type: 'category',
boundaryGap: false,
data: this.Time
},
// y轴
yAxis: {
type: 'value'
},
series: [
{
name: '新西兰元',
type: 'line',

data: this.NewZealand
},
{
name: '澳大利亚元',
type: 'line',

data: this.Australia
},
{
name: '美元',
type: 'line',
stack: '总量',
data: this.USA
},
{
name: '欧元',
type: 'line',

data: this.Europe
},
{
name: '加拿大元',
type: 'line',

data: this.Canada
},
{
name: '新加坡元',
type: 'line',

data: this.Singapore
},
{
name: '瑞士法郎',
type: 'line',

data: this.Switzerland
},

]
}
this.mychart = echarts.init(document.getElementById('mychart'))

this.mychart.setOption(option)
},

//连接

websocketinit:function(){

//判断浏览器是否支持websocket

if('WebSocket' in window){

console.log('支持')

//生成websocket连接
var ws = new WebSocket('ws://192.168.1.171:8000/websocketlink/')

//发送链接请求
ws.onopen = function () {

ws.send('test')
}
//发送消息
ws.onmessage = (evt) =>{
//将获取信息打印
console.log(evt.data)

var msg =JSON.parse(evt.data)

this.Time.push(msg.Time)

console.log('Time',this.Time)

this.HongKong.push(msg.HongKong)

console.log('HongKong',this.HongKong)

this.NewZealand.push(msg.NewZealand)

console.log('NewZealand',this.NewZealand)

this.Australia.push(msg.Australia)

console.log('Australia',this.Australia)

this.USA.push(msg.USA)

console.log('USA',this.USA)

this.Europe.push(msg.Europe)

console.log('Europe',this.Europe)

this.Canada.push(msg.Canada)

console.log('Canada',this.Canada)

this.Japaense.push(msg.Japaense)

console.log('Japaense',this.Japaense)


}
ws.onerror = (e)=>{

console.log('错误信息为',e)

}

//断开连接

ws.onclose = function () {

console.log('链接已关闭')

}
}
}
}}
</script>