# coding:utf-8
import urllib.request as ulr
from relpath import *
import pymysql
import threading
'''version 3.0'''
def stocks(switch):
def data_request(market, stockid, switch):
# 连接数据库
conn = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='你的密码',
db='你的数据库'
)
# 拿到游标
cursor = conn.cursor()
table = {}
stop=False
# 数据获取
# iplist=ip.get_ip()
# iplist=['39.106.223.134:80','58.240.52.114:80','218.16.62.152:3128']
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36 Edg/91.0.864.48'}
# url='http://quote.eastmoney.com/sz000001.html'
url = f'http://11.push2his.eastmoney.com/api/qt/stock/kline/get?cb=jQuery112404820468452785698_1624813216413&secid={market}.{stockid}&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=101&fqt=2&end=20500101&lmt=120&_=1624813216485'
opener = ulr.build_opener()
request = ulr.Request(url, headers=header)
response = opener.open(request).read().decode('utf-8', 'ignore') # decode(dw(url),'ignore')
# 数据处理 - 后复权
data = response.split(sep=',')
try:
table['d0'] = data[-11][-10:] # 日期
table['d1'] = data[7][8:12] # 名称
table['d2'] = float(data[-10]) # 开盘价
table['d3'] = float(data[-9]) # 收盘
table['d4'] = float(data[-8]) # 最高
table['d5'] = float(data[-7]) # 最低
table['d6'] = float(data[-3]) # 涨跌幅
table['d7'] = float(data[-2]) # 涨跌额
table['d8'] = int(data[-6]) # 成交量
table['d9'] = float(data[-5]) # 成交额
table['d10'] = float(data[-4]) # 振幅
table['d11'] = float(data[-1].split(sep='"')[0]) # 换手率
except ValueError:
stop=True
if stop==False:
# 设置表名前缀
if market == '0':
pre = 'sz'
elif market == '1':
pre = 'sh'
elif market == '2':
pre = 'zs'
# 读取表数据
sql0 = f'select date from {pre}{stockid} order by date desc limit 1;'
# 创建表
sql1 = f'CREATE TABLE {pre}{stockid}(date DATE primary key, name char(5), latest_price FLOAT not null default"-1", latest_price_before FLOAT not null default"-1", average_price FLOAT not null default"-1", increase_percentage FLOAT not null default"-1", increase_value FLOAT not null default"-1", trade_times BIGINT not null default"-1", trade_amount FLOAT not null default"-1", amplitude FLOAT not null default"-1", exchange_percentage FLOAT not null default"-1", highest FLOAT not null default"-1", lowest FLOAT not null default"-1", today_start FLOAT not null default"-1", buyer_active BIGINT not null default"-1", seller_active BIGINT not null default"-1")'
# 表添加数据行
sql2 = f"insert into {pre}{stockid}(date,name,today_start,latest_price,highest,lowest,increase_percentage,increase_value,trade_times,trade_amount,amplitude,exchange_percentage) values('{table['d0']}','{table['d1']}','{table['d2']}','{table['d3']}','{table['d4']}','{table['d5']}','{table['d6']}','{table['d7']}','{table['d8']}','{table['d9']}','{table['d10']}','{table['d11']}');"
# 更新表数据
sql4 = f"update {pre}{stockid} set latest_price={table['d3']},increase_percentage={table['d6']},increase_value={table['d7']},trade_times={table['d8']},trade_amount={table['d9']},amplitude={table['d10']},exchange_percentage={table['d11']},highest={table['d4']},lowest={table['d5']},today_start={table['d2']} where date='{table['d0']}';"
try:
# 对数据库最后一条数据获取
cursor.execute(sql0)
lastdate = cursor.fetchone()
# 与当前日期比对并执行
if lastdate == None or str(lastdate[0]) != table['d0']:
cursor.execute(sql2)
else:
cursor.execute(sql4)
except pymysql.err.ProgrammingError:
# 如报错提示不存在表,则创建并填写数据
cursor.execute(sql1)
cursor.execute(sql2)
'''插入before'''
def before(market, stockid, specified_date):
table = {}
url = f'http://push2.eastmoney.com/api/qt/stock/get?ut=fa5fd1943c7b386f172d6893dbfba10b&invt=2&fltt=2&fields=f43,f57,f58,f169,f261,f170,f46,f44,f51,f168,f47,f164,f163,f116,f60,f45,f52,f50,f48,f167,f117,f71,f161,f49,f530,f135,f136,f137,f138,f139,f141,f142,f144,f145,f147,f148,f140,f143,f146,f149,f55,f62,f162,f92,f173,f104,f105,f84,f85,f183,f184,f185,f186,f187,f188,f189,f190,f191,f192,f107,f111,f86,f177,f78,f110,f262,f263,f264,f267,f268,f250,f251,f252,f253,f254,f255,f256,f257,f258,f266,f269,f270,f271,f273,f274,f275,f127,f199,f128,f193,f196,f194,f195,f197,f80,f280,f281,f282,f284,f285,f286,f287,f292&secid={market}.{stockid}'
# proxy_support=ulr.ProxyHandler({'http':random.choice(iplist)})
# opener=ulr.build_opener(proxy_support)
opener = ulr.build_opener()
request = ulr.Request(url, headers=header)
response = opener.open(request).read().decode('utf-8',
'ignore') # decode(dw(url),'ignore')
# 数据处理 - 前复权
response = response.replace('"', '').replace('{', '').replace('}', '').replace('[', '').replace(
']', '').replace('\\', '').replace('-', '-1')
data = response.split(sep=',')
for n in range(len(data)):
data[n] = (f'{data[n]}'.split(sep=':'))
# if market in ('0','1','2'): #沪深股票
table['d1'] = float(data[5][2]) # 最新价
table['d2'] = float(data[20][1]) # 均价
table['d15'] = int(data[11][1]) # 外盘
table['d16'] = int(data[54][1]) # 内盘
# 更新表数据
sql4 = f"update {pre}{stockid} set latest_price_before={table['d1']},average_price={table['d2']},buyer_active={table['d15']},seller_active={table['d16']} where date='{specified_date}';"
cursor.execute(sql4)
if switch == 0:
pass
else:
before(market, stockid, table['d0'])
conn.commit()
else:
pass
cursor.close()
conn.close()
with open(relpath('stock_id.txt')) as f:
stocks=[]
for line in f:
stockid=str(line).replace('\n','')
if stockid[0]=='0' or stockid[0]=='2' or stockid[0]=='3':
market='0'
elif stockid[0]=='5' or stockid[0]=='6' or stockid[0]=='7':
market='1'
elif stockid[0]=='9' or stockid[0]=='H':
market='2'
elif stockid[0]=='#':
continue
#table={'d1':'-1','d2':'-1','d3':'-1','d4':'-1','d5':'-1','d6':'-1','d7':'-1','d9':'-1','d10':'-1','d11':'-1','d15':'-1','d16':'-1'}
stocks.append((market,stockid,switch))
# 多线程
threads=[]
for stock in stocks:
if len(threads)<=100:
threads.append(
threading.Thread(target=data_request,args=(stock[0],stock[1],stock[2]))
)
else:
for thread in threads:
thread.start()
for thread in threads:
thread.join()
threads.clear()
threads.append(
threading.Thread(target=data_request, args=(stock[0], stock[1], stock[2]))
)
continue