import pandas as pd
import tushare as ts
from sqlalchemy import create_engine
import time
ts.set_token('048c7580595543d905c115ffa9d95a36e2b7e926cd7ebc078edd0160')
pro = ts.pro_api()
engine = create_engine('mysql+pymysql://root:root@localhost:3306/lh?charset=utf8')
# 获取所有股票的代码
def getStockBasic():
# 读取数据库
sql = ''' select ts_code from basic; '''
df = pd.read_sql_query(sql, engine)
return df
# 获取所有股票的代码
def saveStockBasic():
data = pro.stock_basic(exchange='', list_status='L')
# 获取所有股票信息
# data = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,area,industry,list_date')
data.to_sql('basic', engine, index=False);
# 保存一只股票
def saveStock(stock):
# 获取该股票的日数据
df = pro.daily(ts_code=stock, start_date='20100101', end_date='20220418')
# 把日期转成index
df['trade_date'] = pd.to_datetime(df['trade_date'])
df.set_index('trade_date', inplace=True)
# 均线
df['ma5'] = df['close'].rolling(5).mean()
df['ma10'] = df['close'].rolling(10).mean()
df['ma20'] = df['close'].rolling(20).mean()
df['ma30'] = df['close'].rolling(30).mean()
df['ma60'] = df['close'].rolling(60).mean()
df.to_sql(('day_' + stock).lower(), engine, index=True)
# 保存所有股票
def saveStockAll(stocks):
for stock in stocks['ts_code']:
time.sleep(0.1)
saveStock(stock)
print(stock)
sb = getStockBasic()
saveStockAll(sb)