转自 https://www.joinquant.com/view/community/detail/24862
打算做一个选股工具给自己用,选来选去还是发现聚宽的数据比较合适。
在开发上我使用NodeJS来做数据的采集,然后需要Docker容器化。我没有直接使用聚宽提供的SDK来完成开发,而是直接使用了聚宽的Restful API来获取数据。
话不多说,先贴上数据获取的部分代码:
//package.json中需要引如axios和csvtojson
const axios = require('axios');
const csvtojson = require("csvtojson");
class JQService {
static singleton() {
if (!this.instance) {
this.instance = new JQService();
}
return this.instance;
}
constructor() {
this.token = null;
this.isRefreshToken = false;
this.axiosInstance = axios.create({
baseURL: 'https://dataapi.joinquant.com',
timeout: 30000,
headers: { 'Content-Type': 'application/json' }
});
}
async _sendRequest(params) {
if (!this.token && params.method != 'get_token') {
await this.refreshToken();
}
if (params.method != 'get_token' && !this.token) return null;
const postBody = params.method != 'get_token' ? Object.assign({}, params, { token: this.token }) : params;
console.log(postBody)
const { status, headers, data } = await this.axiosInstance.post('/apis', postBody);
if (status != 200) { throw '聚宽数据请求失败' }
if (headers['content-type'].includes('text/plain')) {
if (data.includes('error')) {
this.token = null;
throw data
} else {
if (params.method == 'get_token') {
this.token = data;
return data;
} else {
//Parse csv plain text to json
return await csvtojson().fromString(data);
}
}
}
}
async refreshToken() {
if (this.isRefreshToken) { return }
this.isRefreshToken = true;
const params = {
"method": "get_token",
"mob": "你的电话号码",
"pwd": "你的密码"
}
const token = await this._sendRequest(params);
console.log('取得Token:', token);
this.isRefreshToken = false;
}
async getSymbolPrice(symbol = "A2005.XDCE", period = "60m", count = 100, endDate) {
const date = (new Date()).toLocaleDateString()
const arr = date.split('/');
const params = {
"method": "get_bars",
"code": symbol,
"count": count,
"unit": period,
"end_date": endDate
}
const price = await this._sendRequest(params);
return price
}
}
module.exports = JQService;
这部分代码其实比较简单,提供了一个单例来获取聚宽的数据。聚宽API都是使用同一个接口,然后通过在post body中写上具体的方法,来获取特定接口的数据。稍微需要注意点就是token的处理,会在没有token或者是token过期的时候先获取token。
聚宽返回的数据最开始我没注意文档,后来发现大部分结果都是csv的格式。在程序处理上直接使用csv数据不是太方便,因此需要把它转为json的格式。在各个语言平台下应该都有相因的工具能转化就不多说了。
接下来是代码的入口文件的主要代码index.js
const JQService = require('./你的路径/jqService');
(async function main() {
await JQService.getInstance().getSymbolPrice()
})();
然后附上Dockerfile的内容:
FROM node:10.15.3
RUN mkdir -p /workspace
COPY . /workspace
WORKDIR /workspace
RUN npm install
ENTRYPOINT ["node"]
CMD ["src/index.js"]
对了,在项目的根目录里的package.json中记得添加代码中依赖的比如axios等第三方库进去。
接下来就是构建docker镜像
docker build -t jqdemo .
接下来你可以使用这个镜像
docker run --name jqdemo-container jqdemo
整个过程还是比较简单的,如果有疑问欢迎来交流。