您當前的位置:首頁 > 詩詞

獲取jqdatasdk資料到本地並儲存為csv檔案

作者:由 淺涼0000 發表于 詩詞時間:2019-06-05

成功連線上jqdatasdk後最想做的一件事就是先把資料都下載下來,尤其是在聚寬對每日獲取資料設限的條件下。本人使用的程式設計環境是Mac,目前還沒有比Excel更適合本人的視覺化工具,所以選擇了儲存為csv檔案。不過還是真心希望小夥伴有比較好的sql視覺化工具可以推薦給我[比心]。以下是程式碼部分:

首先是一個引用檔案,裡面儲存了一些共用的程式碼部分

escape_list中的都是沒有資料的股票或指數

escape_list = [‘399940。XSHE’, ‘399984。XSHE’, ‘000765。XSHE’]

orig = {“index”: ‘data_index_orig/’, “stock”: “data_stock_orig/”}

# 獲取股票或指數程式碼

def get_codes(key, data_path):

f_codes = data_path + codes_list

if os。path。isfile(f_codes):

with open(f_codes, ‘r’) as f:

code_set = f。readline()

code_set = code_set。strip(‘\n’)。split(‘,’)

else:

code_set = get_all_securities(key)。index。tolist()

with open(f_codes, ‘w’) as f:

f。writelines(‘,’。join(code_set))

return code_set

以下是實際的獲取資料程式碼

# -*- coding: utf-8 -*-

#!/usr/bin/env python3

import pdb

import csv

import datetime

import data_util

import os。path as path

import pandas as pd

from jqdatasdk import *

auth(‘######’, ‘###’)

date_format = ‘%Y-%m-%d’

# 獲取股票或指數的日牌價,只補齊沒有下載的

def get_code_price(code, data_path=None):

print(“獲取”+code+“的牌價”)

filename = data_path + code + ‘。csv’

if path。isfile(filename):

# 需要計算已有檔案應該適用什麼起止時間

pre_price = pd。read_csv(filename, header=0, index_col=0)

pre_price。index = pd。to_datetime(pre_price。index)

dates = pre_price。index。tolist()

startdate = (dates[-1] + datetime。timedelta(days=1))。strftime(date_format)

else:

startdate = “2005-01-01”

pre_price = pd。DataFrame(columns=[‘open’, ‘close’, ‘high’, ‘low’, ‘volume’, ‘money’])

enddate = (datetime。date。today() - datetime。timedelta(days=1))。strftime(date_format)

price = get_price(code, start_date=startdate, end_date=enddate)

if not pre_price。empty:

price = pd。concat([pre_price, price], axis=0)

price。to_csv(filename, header=True, date_format=“%Y-%m-%d”)

def main():

# 編寫程式碼時只用index的,正式測試的時候需要做成包含stock的列表型的

# 後期用dict,key為index,value為DATA_INDEX_ORIG

# 不知道字典是不是這麼寫的

for key, data_path in data_util。orig。items():

if not data_path:

assert “Don‘t exist the directory。”

continue

code_set = data_util。get_codes(key, data_path)

nums = len(code_set)

# 獲取指數牌價

print(’Start to load index price for #{} indexes。‘。format(nums))

for code in code_set:

if code not in data_util。escape_list:

get_code_price(code, data_path=data_path)

if __name__ == ’__main__‘:

main()

標簽: code  data  Price  path  index