TuShare是個獲取股票數據的模塊包,咱們進行分析,須要將股票數據保存到本地,避免每次都從網上獲取,因爲本機裝有ORCALE,以ORACLE爲例介紹如何保存股票數據到本地。sql
1、大體思路:咱們先獲取滬深的全部股票信息,保存到數據庫中,主要使用的是dataframe的to_sql函數。數據庫
to_sql(self, name, con, flavor='sqlite', schema=None, if_exists='fail',
index=True, index_label=None, chunksize=None, dtype=None):oracle
if_exists參數值有三個,fail:若是表存在返回,append:在表後面追加數據;replace:把表替換掉app
2、具體實現:函數
一、股票價格明細表ui
create table IQ_STOCK
(
op_time VARCHAR2(10),
open FLOAT,
high FLOAT,
close FLOAT,
low FLOAT,
volume FLOAT,
price_change FLOAT,
p_change FLOAT,
ma5 FLOAT,
ma10 FLOAT,
ma20 FLOAT,
v_ma5 FLOAT,
v_ma10 FLOAT,
v_ma20 FLOAT,
turnover FLOAT,
stockid VARCHAR2(10),
ktype VARCHAR2(1)
)code
二、股票基本信息表orm
create table IQ_STOCK_BASE
(
code VARCHAR2(10),
name VARCHAR2(100),
industry VARCHAR2(100),
area VARCHAR2(100),
pe FLOAT,
outstanding FLOAT,
totals FLOAT,
"totalAssets" FLOAT,
"liquidAssets" FLOAT,
"fixedAssets" FLOAT,
reserved FLOAT,
"reservedPerShare" FLOAT,
esp FLOAT,
bvps FLOAT,
pb FLOAT,
"timeToMarket" NUMBER(19),
undp FLOAT,
perundp FLOAT,
rev FLOAT,
profit FLOAT,
gpr FLOAT,
npr FLOAT,
holders NUMBER(19)
)sqlite
三、先獲取股票的基本信息:vps
def Get_Stock_List():
##取得股票基本信息
df = ts.get_stock_basics()
#股票數據保存
engine = create_engine('oracle+cx_oracle://user:password@localhost/orcl')
cnx = engine.connect()
##先清空
strSql = 'truncate table iq_stock_base'
cnx.execute(strSql)
df.to_sql('iq_stock_base', cnx,if_exists='append',chunksize=500)
cnx.close()
return df
四、更新近30天的K線數據,此處更新的是周K線
def Update_StockData():
##開始日期 format:YYYY-MM-DD 爲空時取到API所提供的最先日期數據
p_start=time.strftime('%Y-%m-%d',time.localtime(time.time()-24*60*60*30))
p_ktype='W'
#股票數據保存
engine = create_engine('oracle+cx_oracle://user:password@localhost/orcl')
cnx = engine.connect()
#取出股票基本數據
result=pd.read_sql('select * from iq_stock_base',cnx)
for row in result['code']:
try:
##避免重複先刪除
strSql = 'delete from iq_stock where stockid=\'{}\' and ktype=\'{}\' and op_time>=\'{}\''.format(row,p_ktype,p_start)
cnx.execute(strSql)
df=ts.get_hist_data(code=row,start=p_start,ktype=p_ktype)
##索引列是oracle保留關鍵字,必須更名 df.index.names = ['op_time'] df['STOCKID']= row df['ktype']= p_ktype df.to_sql('iq_stock', cnx,if_exists='append') print('code:{}'.format(row)) except: print('Exception',":",row) cnx.close()