#对私人电脑来讲。python自带的数据库更#加方便。不用进行安装。
#要用行以下代码。需要先去tushare注册一#个账号。拿到自己token
import sqlite3
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
import requests
import re
import os
import time
import datetime
import tushare as ts
os.chdir(r’E:\study_python\DB’)#数据存储的数径
ts.set_token(’***************************’)#用户token—没有的去tushare注册就有了
pro = ts.pro_api()#实例化
DB_name=‘stock.db’
Table_Name=‘ts_table’
conn=sqlite3.connect(DB_name)#连接数据库,没有会自动建立
cursor = conn.cursor()#建议游标,通过此命令来实例化
def Create_Table(Table_Name):
# 创建表的SQL语句,默认编码为UTF-8
SQL = ‘’’
CREATE TABLE IF NOT EXISTS %s (
ts_code TEXT,
trade_date INTEGER,
open REAL,
high REAL,
low REAL,
close REAL,
pre_close REAL,
change REAL,
pct_chg REAL,
vol REAL,
amount REAL
)
‘’’ % (Table_Name)
# 创建数据库表
return cursor.execute(SQL)
def db_time(Table_Name):
#找出数据库最近的时间,并增加一天
sql_max=f’select max(“trade_date”) from {Table_Name}’
cursor.execute(sql_max)
da=cursor.fetchall()
ds=datetime.datetime.strptime(str(da[0][0]),’%Y%m%d’)+datetime.timedelta(days=1)
return ds.strftime(’%Y%m%d’)
def GetTables(Table_Name):
#来检查数据库中是否有这个表
cursor.execute(“select name from sqlite_master where type=‘table’ order by name”)
Tb=cursor.fetchall()
#for i in Tb:
#print(i)
return Table_Name in Tb
if GetTables(Table_Name)==False:#如果数据库是空的,将下载全部数据
Create_Table(Table_Name)
start=‘19820101’
else:#如果已有下载的数据,将在原有基础上更新
start=db_time(Table_Name)
end=datetime.datetime.now().strftime(’%Y%m%d’)#更新时所在的日期
exchange_date=pro.trade_cal(exchange=’’,start_date=start,end_date=end)#调用TUSHARE中的交易日历
df_date=exchange_date[exchange_date[‘is_open’]==1]#找出开是的日期
count=0
for i in df_date[‘cal_date’]:
#此为进度条,只为看起去更直观些, 没有此循环,也不影响下载。
count+=1
time.sleep(0.1)
df = pro.daily(trade_date=i)
df.to_sql(‘TS_DB’, conn, if_exists=‘append’,index=False)
dis=int(50*count/len(df_date))
print(’\r’,‘■’dis+‘□’(50-dis),’{:.2%} Date:{}’.format(count/len(df_date),i),end=’’)
conn.commit()
cursor.close()
conn.close()
print(’\n’,‘已全部完成’)
#以上内容花我三天晚上的时间,码字不易, 难创艰辛,请来个点赞,下次再把一次统计学的公式做上去,通过类的方式调用,更加方便。
#学pyghon的朋友,一个人鼓捣,容易懈怠,大家一起来(加微13967332389),共勉励,同分享,事半功倍,也话对炒股不一定有收益,不过能因些而成就一门语言也行。