想要使用akshare获取a股代码
却没有写入相应文件夹下
import os
import time
import pandas as pd
import akshare as ak
import warnings
from datetime import timedelta, datetime
warnings.filterwarnings("ignore")
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.expand_frame_repr', False)
pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)
# 输入参数
start_date = '19990101'
end_date = '20220430'
adj="hfq" # 复权类型:None未复权 qfq前复权 hfq后复权
period = "daliy"
df=ak.stock_zh_a_spot_em()
code_list=df[['序号','代码','名称']].values
# 创建文件存储路径
def create_path():
global path
date_str = str(pd.to_datetime(start_date).date()) #日期转成字符串
path = os.path.join(".","all_stock_candle","stock",date_str)
# 保存数据
if not os.path.exists(path) :
# os.mkdir(path) # 可以建一级文件夹
os.makedirs(path) # 可以建多级文件夹
file_name = str(ak_code) + ".csv"
return os.path.join(path,file_name)
for i, ak_code,ak_name in code_list:
print(i,ak_code,ak_name)
try:
df= ak.stock_zh_a_hist(symbol=ak_code, period=period, start_date=start_date, end_date=end_date, adjust=adj)
except Exception as e:
print(e)
continue
if ak_code.startswith('6') == True:
ak_code = 'sh'+ak_code
elif ak_code.startswith('8') == True:
ak_code = 'bj'+ak_code
else:
ak_code = 'sz'+ak_code
df['股票代码'] = ak_code
df['股票名称'] = ak_name
df.rename(columns={'day': '交易日期', 'open': '开盘价', 'high': '最高价','low': '最低价', 'close': '收盘价','volume':'成交量'}, inplace=True)
df = df[['交易日期', '股票代码', '股票名称', '开盘价', '最高价', '最低价', '收盘价', '成交量']]
df.sort_values(by=['交易日期'],ascending=True,inplace=True)
df.reset_index(drop=True, inplace=True)
path=create_path()
df.to_csv(path, index=False, mode='w',encoding='gbk')
time.sleep(2)
运行代码并没有生成相应文件夹
能在对应的文件夹下输出.csv文件