ECharts 金融数据可视化实战
📋 项目概述
构建专业的金融数据分析平台,支持K线图、技术指标、分时图等金融图表,提供实时行情和深度分析功能。
核心功能
- ✅ K线图表:蜡烛图 + 成交量
- ✅ 技术指标:MA、MACD、KDJ、RSI
- ✅ 分时图:实时价格曲线
- ✅ 深度图:买卖盘口可视化
- ✅ 多周期切换:1分钟/5分钟/日线/周线
🎯 技术架构
typescript
const stack = {
frontend: 'Vue 3 + TypeScript',
charts: 'ECharts 5.4 + echarts-financial',
realtime: 'WebSocket (行情推送)',
state: 'Pinia',
dataProcessing: 'Day.js + Decimal.js',
backend: 'Python FastAPI + Redis'
};1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
💻 核心实现
1. K线蜡烛图
vue
<!-- components/Financial/KLineChart.vue -->
<template>
<div class="kline-chart">
<!-- 工具栏 -->
<div class="chart-toolbar">
<PeriodSelector v-model="period" @change="onPeriodChange" />
<IndicatorSelector v-model="indicators" @change="onIndicatorChange" />
<ToolButtons @zoomIn="zoomIn" @zoomOut="zoomOut" @reset="resetZoom" />
</div>
<!-- 主图 -->
<div ref="mainChartRef" class="main-chart" />
<!-- 副图(成交量/指标) -->
<div ref="subChartRef" class="sub-chart" />
</div>
</template>
<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts/core';
import { CandlestickChart, BarChart, LineChart } from 'echarts/charts';
import {
GridComponent,
TooltipComponent,
DataZoomComponent,
AxisPointerComponent,
LegendComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { useKLineData } from '@/composables/useKLineData';
import { useTechnicalIndicators } from '@/composables/useTechnicalIndicators';
import PeriodSelector from './PeriodSelector.vue';
import IndicatorSelector from './IndicatorSelector.vue';
import ToolButtons from './ToolButtons.vue';
echarts.use([
CandlestickChart,
BarChart,
LineChart,
GridComponent,
TooltipComponent,
DataZoomComponent,
AxisPointerComponent,
LegendComponent,
CanvasRenderer
]);
interface KLineDataPoint {
date: string;
open: number;
close: number;
low: number;
high: number;
volume: number;
amount: number;
}
const props = defineProps<{
symbol: string; // 股票代码
initialPeriod?: string;
}>();
const mainChartRef = ref<HTMLDivElement>();
const subChartRef = ref<HTMLDivElement>();
const period = ref(props.initialPeriod || 'day');
const indicators = ref<string[]>(['MA']);
let mainChart: echarts.ECharts | null = null;
let subChart: echarts.ECharts | null = null;
// 使用K线数据Hook
const { klineData, loading, fetchKLineData, subscribeRealtime, unsubscribeRealtime } =
useKLineData(props.symbol);
// 使用技术指标Hook
const { calculateMA, calculateMACD, calculateKDJ } = useTechnicalIndicators();
// 初始化图表
function initCharts() {
if (!mainChartRef.value || !subChartRef.value) return;
mainChart = echarts.init(mainChartRef.value);
subChart = echarts.init(subChartRef.value);
// 联动两个图表
mainChart.on('dataZoom', (params: any) => {
const start = params.batch ? params.batch[0].start : params.start;
const end = params.batch ? params.batch[0].end : params.end;
subChart?.dispatchAction({
type: 'dataZoom',
start,
end
});
});
}
// 生成主图配置
function generateMainChartOption(data: KLineDataPoint[]) {
const dates = data.map(item => item.date);
const values = data.map(item => [item.open, item.close, item.low, item.high]);
const series: any[] = [
{
name: 'K线',
type: 'candlestick',
data: values,
itemStyle: {
color: '#ef232a', // 涨(红色)
color0: '#14b143', // 跌(绿色)
borderColor: '#ef232a',
borderColor0: '#14b143'
}
}
];
// 添加均线
if (indicators.value.includes('MA')) {
const ma5 = calculateMA(data, 5);
const ma10 = calculateMA(data, 10);
const ma20 = calculateMA(data, 20);
series.push(
{
name: 'MA5',
type: 'line',
data: ma5,
smooth: true,
lineStyle: { width: 1 },
showSymbol: false
},
{
name: 'MA10',
type: 'line',
data: ma10,
smooth: true,
lineStyle: { width: 1 },
showSymbol: false
},
{
name: 'MA20',
type: 'line',
data: ma20,
smooth: true,
lineStyle: { width: 1 },
showSymbol: false
}
);
}
return {
animation: false,
legend: {
left: 0,
data: ['K线', 'MA5', 'MA10', 'MA20']
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross'
},
formatter: (params: any) => {
const kline = params.find((p: any) => p.seriesType === 'candlestick');
if (!kline) return '';
const [open, close, low, high] = kline.data;
const change = ((close - open) / open * 100).toFixed(2);
return `
<div style="padding: 8px;">
<div>开盘: ${open}</div>
<div>收盘: ${close}</div>
<div>最低: ${low}</div>
<div>最高: ${high}</div>
<div>涨跌: ${change}%</div>
</div>
`;
}
},
grid: {
left: '10%',
right: '8%',
top: '15%',
bottom: '10%'
},
xAxis: {
type: 'category',
data: dates,
scale: true,
boundaryGap: false,
axisLine: { onZero: false },
splitLine: { show: false },
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
};
}
// 生成副图配置(成交量)
function generateSubChartOption(data: KLineDataPoint[]) {
const dates = data.map(item => item.date);
const volumes = data.map((item, index) => ({
value: item.volume,
itemStyle: {
color: item.close >= item.open ? '#ef232a' : '#14b143'
}
}));
return {
animation: false,
grid: {
left: '10%',
right: '8%',
top: '10%',
bottom: '10%'
},
xAxis: {
type: 'category',
data: dates,
show: false
},
yAxis: {
scale: true,
splitNumber: 2,
axisLabel: { show: false },
splitLine: { show: false }
},
series: [
{
name: '成交量',
type: 'bar',
data: volumes
}
]
};
}
// 更新图表
function updateCharts() {
if (!mainChart || !subChart) return;
const mainOption = generateMainChartOption(klineData.value);
const subOption = generateSubChartOption(klineData.value);
mainChart.setOption(mainOption);
subChart.setOption(subOption);
}
// 周期切换
async function onPeriodChange(newPeriod: string) {
await fetchKLineData(newPeriod);
updateCharts();
}
// 指标切换
function onIndicatorChange(newIndicators: string[]) {
updateCharts();
}
// 缩放
function zoomIn() {
mainChart?.dispatchAction({
type: 'dataZoom',
start: 40,
end: 60
});
}
function zoomOut() {
mainChart?.dispatchAction({
type: 'dataZoom',
start: 20,
end: 80
});
}
function resetZoom() {
mainChart?.dispatchAction({
type: 'dataZoom',
start: 0,
end: 100
});
}
// 监听数据变化
watch(klineData, updateCharts);
// 生命周期
onMounted(async () => {
initCharts();
await fetchKLineData(period.value);
updateCharts();
// 订阅实时行情
subscribeRealtime((newData) => {
// 更新最后一根K线
klineData.value[klineData.value.length - 1] = newData;
updateCharts();
});
});
onUnmounted(() => {
unsubscribeRealtime();
mainChart?.dispose();
subChart?.dispose();
});
</script>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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
2. 技术指标计算
typescript
// composables/useTechnicalIndicators.ts
import { computed } from 'vue';
interface KLineDataPoint {
date: string;
open: number;
close: number;
low: number;
high: number;
volume: number;
}
export function useTechnicalIndicators() {
/**
* 计算移动平均线
*/
function calculateMA(data: KLineDataPoint[], period: number): number[] {
const result: number[] = [];
for (let i = 0; i < data.length; i++) {
if (i < period - 1) {
result.push(NaN);
continue;
}
let sum = 0;
for (let j = 0; j < period; j++) {
sum += data[i - j].close;
}
result.push(sum / period);
}
return result;
}
/**
* 计算MACD
*/
function calculateMACD(
data: KLineDataPoint[],
fastPeriod: number = 12,
slowPeriod: number = 26,
signalPeriod: number = 9
): { dif: number[]; dea: number[]; macd: number[] } {
const ema12 = calculateEMA(data, fastPeriod);
const ema26 = calculateEMA(data, slowPeriod);
const dif = ema12.map((val, i) => val - ema26[i]);
const dea = calculateEMA(dif.map(v => isNaN(v) ? 0 : v), signalPeriod);
const macd = dif.map((val, i) => (val - dea[i]) * 2);
return { dif, dea, macd };
}
/**
* 计算指数移动平均
*/
function calculateEMA(data: KLineDataPoint[], period: number): number[] {
const result: number[] = [];
const k = 2 / (period + 1);
let ema = data[0]?.close || 0;
for (let i = 0; i < data.length; i++) {
if (i < period - 1) {
result.push(NaN);
ema = data[i].close;
} else {
ema = data[i].close * k + ema * (1 - k);
result.push(ema);
}
}
return result;
}
/**
* 计算KDJ
*/
function calculateKDJ(
data: KLineDataPoint[],
period: number = 9
): { k: number[]; d: number[]; j: number[] } {
const k: number[] = [];
const d: number[] = [];
const j: number[] = [];
let prevK = 50;
let prevD = 50;
for (let i = 0; i < data.length; i++) {
if (i < period - 1) {
k.push(NaN);
d.push(NaN);
j.push(NaN);
continue;
}
// 计算RSV
let highestHigh = -Infinity;
let lowestLow = Infinity;
for (let n = 0; n < period; n++) {
highestHigh = Math.max(highestHigh, data[i - n].high);
lowestLow = Math.min(lowestLow, data[i - n].low);
}
const rsv = ((data[i].close - lowestLow) / (highestHigh - lowestLow)) * 100;
// 计算K、D、J
const currentK = (2 / 3) * prevK + (1 / 3) * rsv;
const currentD = (2 / 3) * prevD + (1 / 3) * currentK;
const currentJ = 3 * currentK - 2 * currentD;
k.push(currentK);
d.push(currentD);
j.push(currentJ);
prevK = currentK;
prevD = currentD;
}
return { k, d, j };
}
/**
* 计算RSI
*/
function calculateRSI(data: KLineDataPoint[], period: number = 14): number[] {
const result: number[] = [];
for (let i = 0; i < data.length; i++) {
if (i < period) {
result.push(NaN);
continue;
}
let gainSum = 0;
let lossSum = 0;
for (let j = 0; j < period; j++) {
const change = data[i - j].close - data[i - j - 1].close;
if (change > 0) {
gainSum += change;
} else {
lossSum -= change;
}
}
const avgGain = gainSum / period;
const avgLoss = lossSum / period;
const rs = avgGain / (avgLoss || 1);
const rsi = 100 - (100 / (1 + rs));
result.push(rsi);
}
return result;
}
return {
calculateMA,
calculateMACD,
calculateKDJ,
calculateRSI
};
}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
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
3. 分时图
vue
<!-- components/Financial/TimeSharingChart.vue -->
<template>
<div ref="chartRef" class="time-sharing-chart" />
</template>
<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
const chartRef = ref<HTMLDivElement>();
let chart: echarts.ECharts | null = null;
interface TimeSharingData {
time: string;
price: number;
avgPrice: number;
volume: number;
}
const props = defineProps<{
data: TimeSharingData[];
previousClose: number;
}>();
function initChart() {
if (!chartRef.value) return;
chart = echarts.init(chartRef.value);
updateChart();
}
function updateChart() {
if (!chart) return;
const times = props.data.map(d => d.time);
const prices = props.data.map(d => d.price);
const avgPrices = props.data.map(d => d.avgPrice);
const volumes = props.data.map(d => d.volume);
const option = {
animation: false,
tooltip: {
trigger: 'axis',
formatter: (params: any) => {
const price = params[0];
const volume = params[2];
return `
<div style="padding: 8px;">
<div>时间: ${price.axisValue}</div>
<div>价格: ${price.value.toFixed(2)}</div>
<div>均价: ${avgPrices[price.dataIndex].toFixed(2)}</div>
<div>成交量: ${volume.value}</div>
</div>
`;
}
},
grid: [
{
left: '10%',
right: '8%',
height: '60%'
},
{
left: '10%',
right: '8%',
top: '70%',
height: '20%'
}
],
xAxis: [
{
type: 'category',
data: times,
gridIndex: 0
},
{
type: 'category',
data: times,
gridIndex: 1,
show: false
}
],
yAxis: [
{
scale: true,
gridIndex: 0,
splitNumber: 4,
formatter: '{value}'
},
{
scale: true,
gridIndex: 1,
show: false
}
],
series: [
{
name: '价格',
type: 'line',
data: prices,
smooth: true,
symbol: 'none',
lineStyle: {
color: '#5470c6',
width: 2
},
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: 'rgba(84, 112, 198, 0.3)' },
{ offset: 1, color: 'rgba(84, 112, 198, 0.05)' }
])
},
markLine: {
silent: true,
symbol: 'none',
data: [
{
yAxis: props.previousClose,
lineStyle: {
color: '#999',
type: 'dashed'
}
}
]
}
},
{
name: '均价',
type: 'line',
data: avgPrices,
smooth: true,
symbol: 'none',
lineStyle: {
color: '#f39c12',
width: 1,
type: 'dashed'
}
},
{
name: '成交量',
type: 'bar',
xAxisIndex: 1,
yAxisIndex: 1,
data: volumes,
itemStyle: {
color: (params: any) => {
const price = prices[params.dataIndex];
const prevPrice = params.dataIndex > 0 ? prices[params.dataIndex - 1] : price;
return price >= prevPrice ? '#ef232a' : '#14b143';
}
}
}
]
};
chart.setOption(option);
}
watch(() => props.data, updateCharts, { deep: true });
onMounted(initChart);
</script>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
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
💎 总结
本实战案例展示了金融数据可视化的核心实现:
- K线蜡烛图:专业金融图表
- 技术指标计算:MA、MACD、KDJ
- 实时更新:WebSocket行情推送
- 多图表联动:主图+副图同步
适用于股票、期货、外汇等金融场景。
