Tushare-SDK

tushare一直沒有出java的sdk,好在出了http協議的api.本項目根據http的api封裝而成java

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請求和應答

請求git

@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;
    }
}

應答api

@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沒有實現,但願用到的朋友幫助實現ide

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息