Tushare-SDK

泄露秘密 提交于 2020-12-04 10:12:39

tushare一直没有出java的sdk,好在出了http协议的api.本项目根据http的api封装而成

gitee地址

https://gitee.com/ichiva/tushare-sdk.git

项目目录

image.png

定义实体类

@Getter
@Setter
public class TuTable implements Serializable {
    private String[] fields;
    private String[][] items;
}

定义获取数据的接口

/**
 * tu 数据
 */
public interface TuData {

    /**
     * 获取数据
     * @return
     */
    Optional<TuTable> get();
}

定义api请求和应答

请求

@Data
public class TuRequest implements Serializable {

    /**
     * 接口名
     */
    private String api;
    private String token;
    /**
     * 输入参数
     */
    private Map<String,String> params;
    /**
     * 输出参数
     */
    private String[] fields;
    /**
     * 输出参数描述
     */
    private String[] fieldsName;
    /**
     * 接口描述
     */
    private String describe;

    /**
     * 简化输入
     * @param fieldMap
     */
    public void setFieldMap(Map<String,String> fieldMap) {
        Set<Map.Entry<String, String>> entries = fieldMap.entrySet();
        this.fields = new String[entries.size()];
        this.fieldsName = new String[entries.size()];

        int i = 0;
        for (Map.Entry<String, String> entry : entries) {
            this.fields[i] = entry.getKey();
            this.fieldsName[i] = entry.getValue();
            i++;
        }
    }

    public Object toQuery(){
        HashMap<String, Object> res = new HashMap<>();
        res.put("api_name",getApi());
        res.put("token",getToken());
        res.put("params",getParams());
        res.put("fields", Arrays.stream(getFields()).collect(Collectors.joining(",")));
        return res;
    }
}

应答

@Data
public class TuResponse {
    private int code;
    private TuTable data;
    private String msg;
}

抽象的数据读取实现

/**
 * 读取数据
 */
@Slf4j
public abstract class AbstractTuData implements TuData {

    private final TuClient client;

    private TuRequest request;

    public AbstractTuData(TuClient client){
        this.client = client;
    }

    public TuRequest getRequest() {
        return request;
    }

    public void setRequest(TuRequest request) {
        this.request = request;
    }

    @Override
    public Optional<TuTable> get() {
        log.info("读取服务器数据 api = {}",request.getApi());
        Optional<TuResponse> res = client.post(request);
        if (res.isPresent()) {
            TuTable data = res.get().getData();
            return Optional.ofNullable(data);
        }

        return Optional.empty();
    }
}

数据缓存

@Slf4j
public abstract class TuDataCacheAble extends AbstractTuData {

    private static DbImpl db;
    static {
        try {
            db = new DbImpl(new Options(), new File(SystemHelper.getTempDir(),"tushare-cache"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public TuDataCacheAble(TuClient client) {
        super(client);
    }

    /**
     * 取缓存数据
     * @return
     */
    @Override
    public Optional<TuTable> get() {
        TuRequest request = getRequest();
        byte[] key = getCacheKey(request);
        byte[] bytes = db.get(key);
        if(bytes != null){
            log.info("命中缓存 key = {}",new String(key));
            return Optional.of((TuTable)DataUtils.toObject(bytes));
        }

        Optional<TuTable> res = super.get();
        res.ifPresent(e -> db.put(key, DataUtils.toByte(e)));
        return res;
    }

    protected byte[] getCacheKey(TuRequest request) {
        return request.getApi().getBytes();
    }

    /**
     * 清除所有缓存
     */
    public void clearAll(){
        SeekingIteratorAdapter it = db.iterator();
        int n = 0;
        while (it.hasNext()) {
            byte[] key = it.next().getKey();
            clear(key);
            n++;
        }

        log.info("清理缓存,收影响记录 n = ",n);
    }

    /**
     * 清楚指定缓存
     * @param key
     */
    public void clear(byte[] key){
        db.delete(key);
    }
}

股票列表获取

api实现类

/**
 * 股票列表
 *
 * 获取2000年到现在的所有数据
 */
public class TuStockBasicData extends TuDataCacheAble {

    public TuStockBasicData(StringDB db, TuClient client) {
        super(db, client);

        TuRequest request = new TuRequest();
        request.setApi("stock_basic");
        request.setDescribe("获取基础信息数据,包括股票代码、名称、上市日期、退市日期等");

        HashMap<String,String> paramsMap = new HashMap<>();
        request.setParams(paramsMap);

        LinkedHashMap<String,String> fieldMap = new LinkedHashMap<>();
        fieldMap.put("ts_code","TS代码");
        fieldMap.put("symbol","股票代码");
        fieldMap.put("name","股票名称");
        fieldMap.put("area","所在地域");
        fieldMap.put("industry","所属行业");
        fieldMap.put("fullname","股票全称");
        fieldMap.put("enname","英文全称");
        fieldMap.put("market","市场类型 (主板/中小板/创业板/科创板)");
        fieldMap.put("exchange","交易所代码");
        fieldMap.put("curr_type","交易货币");

        request.setFieldMap(fieldMap);
        setRequest(request);
    }
}

测试

@Slf4j
public class TuDailyDataTests {

    private TuClient clinet;

    @Before
    public void Before() throws IOException {
        //token需要自己取申请,申请地址
        this.clinet = new TuClient("http://api.waditu.com/","token");

    }

    @Test public void testTuStockBasicData(){
        TuStockBasicData data = new TuStockBasicData(clinet);
        data.get().ifPresent(System.out::println);
    }
}

测试结果

C:\Users\Chiva\AppData\Local\Temp\tushare-cache
[main] INFO cn.ichiva.tushare.sdk.tushare.TuDataCacheAble - 命中缓存 key = stock_basic
ts_code	symbol	name	area	industry	fullname	enname	market	exchange	curr_type
000001.SZ	000001	平安银行	深圳	银行	平安银行股份有限公司	Ping An Bank Co., Ltd.	主板	SZSE	CNY
000002.SZ	000002	万科A	深圳	全国地产	万科企业股份有限公司	China Vanke Co.,Ltd.	主板	SZSE	CNY
...

gitee地址

https://gitee.com/ichiva/tushare-sdk.git

PS:部分暂时用不上的api没有实现,希望用到的朋友帮助实现

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!