最近一两年,股票量化分析越来越受欢迎了。想要入行,首先得搞定股票数据。毕竟,所有量化分析都是建立在数据之上的,实时交易、历史交易、财务、基本面,这些数据咱们都得有。咱们的目标就是挖掘这些数据中的价值,来指导咱们的投资策略。
为了找数据,我可是尝试了各种方法,自己动手写过网易、申万行业的爬虫,还试过同花顺问财的,连聚宽的免费API都用过。但爬虫这东西,数据总是不稳定,给量化分析带来不少困扰。
在量化分析领域,实时、准确的数据接口太重要了。现在我用Python、JavaScript(Node.js)、Java、C#和Ruby五种主流语言的实例代码给大家演示一下如何获取股票实时交易数据:
1、python
python
import requests
url = "http://api.mairui.club/hsrl/ssjy/000001/b997d4403688d5e66a"
response = requests.get(url)
data = response.json()
print(data)
- JavaScript (Node.js)
javascript
const axios = require('axios');
const url = "http://api.mairui.club/hsrl/ssjy/000001/b997d4403688d5e66a";
axios.get(url)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
- Java
java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://api.mairui.club/hsrl/ssjy/000001/b997d4403688d5e66a"))
.build();
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
- C#
csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
using (HttpClient client = new HttpClient())
{
string url = "http://api.mairui.club/hsrl/ssjy/000001/b997d4403688d5e66a";
HttpResponseMessage response = await client.GetAsync(url);
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
- Ruby
ruby
require 'net/http'
require 'json'
url = URI("http://api.mairui.club/hsrl/ssjy/000001/b997d4403688d5e66a")
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Get.new(url)
response = http.request(request)
data = JSON.parse(response.read_body)
puts data
返回的数据:
{"fm":"-0.20","h":"10.26","hs":"0.67","lb":"1.38","l":"10.11","lt":"197161074084.00","o":"10.11","pe":"3.81","pc":"0.30","p":"10.16","sz":"197164128892.00","cje":"1318858687.52","ud":"0.03","v":"1294059","yc":"10.13","zf":"1.48","zs":"-0.20","sjl":"0.48","zdf60":"-0.20","zdfnc":"17.19","t":"2024-08-30 15:29:03"}
API说明文档:
字段名称 | 数据类型 | 字段说明 |
---|---|---|
fm | number | 五分钟涨跌幅(%) |
h | number | 最高价(元) |
hs | number | 换手(%) |
lb | number | 量比(%) |
l | number | 最低价(元) |
lt | number | 流通市值(元) |
o | number | 开盘价(元) |
pe | number | 市盈率(动态,总市值除以预估全年净利润,例如当前公布一季度净利润1000万,则预估全年净利润4000万) |
pc | number | 涨跌幅(%) |
p | number | 当前价格(元) |
sz | number | 总市值(元) |
cje | number | 成交额(元) |
ud | number | 涨跌额(元) |
v | number | 成交量(手) |
yc | number | 昨日收盘价(元) |
zf | number | 振幅(%) |
zs | number | 涨速(%) |
sjl | number | 市净率 |
zdf60 | number | 60日涨跌幅(%) |
zdfnc | number | 年初至今涨跌幅(%) |
t | string | 更新时间yyyy-MM-dd HH:mm:ss |