trade_date = str(trade_date)[:-4]
时间: 2024-05-17 13:17:05 浏览: 54
这行代码的作用是将日期类型的变量 trade_date 转换成字符串类型,并且去掉最后四位字符。通常情况下,最后四位字符表示日期的时间部分,因此这段代码可能是为了将日期变量转换成只包含年月日的字符串格式。例如,如果 trade_date 的值为 "20211231123000",那么经过这段代码处理后,它的值将变成 "20211231"。
相关问题
def __stk_surv(): df=pd.read_sql("select ts_code from stock_basic", con = con0) ts_code = (df[df['ts_code'].str.contains('[HZ]')]['ts_code'] .drop_duplicates() .apply(lambda x: f"'{x}'") .reset_index(drop=True)) for i in ts_code: try: start_date = str(pd.read_sql("select surv_date from stk_surv", con = con3).sort_values('surv_date',ascending = False).iloc[0,0]) start_date=pd.to_datetime(start_date)+pd.Timedelta(1,'days') start_date=start_date.strftime('%Y%m%d') except: start_date = 20220101 dateToday = datetime.date.today().strftime('%Y%m%d') end_date = dateToday i = i[1:10] df = pro.stk_surv(**{ "ts_code": i, "trade_date": "", "start_date": start_date, "end_date": end_date, "limit": "", "offset": "" }, fields=[ "ts_code", "name", "surv_date", "fund_visitors", "rece_place", "rece_mode", "rece_org", "org_type", "comp_rece" ]) # print(df) time.sleep(0.31) df = df[df['rece_mode'].str.contains('调研')] df.to_sql(name='stk_surv',con=con3,if_exists='append',index=False) 增加进度条
你可以在循环中使用tqdm库来添加进度条。以下是修改后的代码示例:
```
from tqdm import tqdm
import time
def __stk_surv():
df=pd.read_sql("select ts_code from stock_basic", con = con0)
ts_code = (df[df['ts_code'].str.contains('[HZ]')]['ts_code']
.drop_duplicates()
.apply(lambda x: f"'{x}'")
.reset_index(drop=True))
for i in tqdm(ts_code):
try:
start_date = str(pd.read_sql("select surv_date from stk_surv", con = con3).sort_values('surv_date',ascending = False).iloc[0,0])
start_date=pd.to_datetime(start_date)+pd.Timedelta(1,'days')
start_date=start_date.strftime('%Y%m%d')
except:
start_date = 20220101
dateToday = datetime.date.today().strftime('%Y%m%d')
end_date = dateToday
i = i[1:10]
df = pro.stk_surv(**{
"ts_code": i,
"trade_date": "",
"start_date": start_date,
"end_date": end_date,
"limit": "",
"offset": ""
}, fields=[
"ts_code",
"name",
"surv_date",
"fund_visitors",
"rece_place",
"rece_mode",
"rece_org",
"org_type",
"comp_rece"
])
# print(df)
time.sleep(0.31)
df = df[df['rece_mode'].str.contains('调研')]
df.to_sql(name='stk_surv',con=con3,if_exists='append',index=False)
```
在上面的代码中,我们使用了tqdm库来包装循环,以自动为你添加进度条。你可以根据需要自定义进度条的样式和位置。
2、为下面的程序的每一行标上注释; import requests import re import pandas as pd import time import datetime url = 'http://datacenter-web.eastmoney.com/api/data/v1/get?' name_list = [] code_list = [] trader_date_list = [] close_list = [] change_rate_list = [] buy_num_list = [] result_list = [] result_df = pd.DataFrame() for page in range(1, 4): params = ( ('callback', 'jQuery112305930880286224138_1632364981303'), ('sortColumns', 'NET_BUY_AMT,TRADE_DATE,SECURITY_CODE'), ('sortTypes', '-1,-1,1'), ('pageSize', '50'), ('pageNumber', str(page)), ('reportName', 'RPT_ORGANIZATION_TRADE_DETAILS'), ('columns', 'ALL'), ('source', 'WEB'), ('clientl', 'WE'), ('filter', "(TRADE_DATE>='2021-09-17')") ) response = requests.get(url, params=params) text = response.text print(text) # re准则查找数据 name = re.findall('"SECURITY_NAME_ABBR":"(.*?)"', text) # 名称 code = re.findall('"SECURITY_CODE":"(.*?)"', text) # 股票代码 trader_date = re.findall('"TRADE_DATE":"(.*?)"', text) # 交易日期 close = re.findall('"CLOSE_PRICE":(.*?)\,', text) # 收盘价 change_rate = re.findall('"CHANGE_RATE":(.*?)\,', text) # 涨幅 buy_num = re.findall('"BUY_TIMES":(.*?)\,', text) # 买入机构数量 # 将对应的列表里的数据全部加起来 name_list = name_list + name code_list = code_list + code trader_date_list = trader_date_list + trader_date close_list = close_list + close change_rate_list = change_rate_list + change_rate buy_num_list = buy_num_list + buy_num time.sleep(2) # 将所有列表合并成二维数组 result_list = [trader_date_list, code_list, name_list, close_list, change_rate_list, buy_num_list] # 将数据转为DataFrame格式 result_df = pd.DataFrame(result_list).T.rename( columns={0: '交易日期', 1: '股票代码', 2: '股票名称', 3: '收盘价', 4: '涨幅', 5: '买入机构'}) result_df['交易日期'] =pd.to_datetime(result_df['交易日期']) # 时间只取年月日 result_df = result_df.sort_values(by='交易日期', ascending=True) print(result_df)
# 导入需要的库
import requests
import re
import pandas as pd
import time
import datetime
# 定义请求的url
url = 'http://datacenter-web.eastmoney.com/api/data/v1/get?'
# 定义空列表用于存储数据
name_list = []
code_list = []
trader_date_list = []
close_list = []
change_rate_list = []
buy_num_list = []
result_list = []
result_df = pd.DataFrame()
# 循环请求数据
for page in range(1, 4):
params = (
('callback', 'jQuery112305930880286224138_1632364981303'),
('sortColumns', 'NET_BUY_AMT,TRADE_DATE,SECURITY_CODE'),
('sortTypes', '-1,-1,1'),
('pageSize', '50'),
('pageNumber', str(page)),
('reportName', 'RPT_ORGANIZATION_TRADE_DETAILS'),
('columns', 'ALL'),
('source', 'WEB'),
('clientl', 'WE'),
('filter', "(TRADE_DATE>='2021-09-17')")
)
# 发送请求,并获取响应数据
response = requests.get(url, params=params)
text = response.text
print(text)
# 使用正则表达式查找数据
name = re.findall('"SECURITY_NAME_ABBR":"(.*?)"', text) # 名称
code = re.findall('"SECURITY_CODE":"(.*?)"', text) # 股票代码
trader_date = re.findall('"TRADE_DATE":"(.*?)"', text) # 交易日期
close = re.findall('"CLOSE_PRICE":(.*?)\,', text) # 收盘价
change_rate = re.findall('"CHANGE_RATE":(.*?)\,', text) # 涨幅
buy_num = re.findall('"BUY_TIMES":(.*?)\,', text) # 买入机构数量
# 将对应的列表里的数据全部加起来
name_list = name_list + name
code_list = code_list + code
trader_date_list = trader_date_list + trader_date
close_list = close_list + close
change_rate_list = change_rate_list + change_rate
buy_num_list = buy_num_list + buy_num
# 暂停2秒钟
time.sleep(2)
# 将所有列表合并成二维数组
result_list = [trader_date_list, code_list, name_list, close_list, change_rate_list, buy_num_list]
# 将数据转为DataFrame格式
result_df = pd.DataFrame(result_list).T.rename(columns={0: '交易日期', 1: '股票代码', 2: '股票名称', 3: '收盘价', 4: '涨幅', 5: '买入机构'})
# 将时间列转换为日期格式,并只取年月日
result_df['交易日期'] = pd.to_datetime(result_df['交易日期'])
# 根据交易日期排序
result_df = result_df.sort_values(by='交易日期', ascending=True)
# 打印结果
print(result_df)
阅读全文