为方便每日查看买的股票基金, 尝试写了一个脚本可每天看到数据和图
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 18 16:20:19 2019
@author: xinran
"""
#先引入后面分析、可视化等可能用到的库
import tushare as ts
#import datetime
import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#正常显示画图时出现的中文和负号
from pylab import mpl
def get_code():
df = pro.stock_basic(exchange='', list_status='L')
codes = df.ts_code.values
names = df.name.values
stocks = dict(zip(names,codes))
df2 = pro.fund_basic(market='E')
codes2 = df2.ts_code.values
names2 = df2.name.values
stocks2 = dict(zip(names2,codes2))
dic = dict(stocks,**stocks2)
#合并指数和个股成一个字典
# stocks=dict(stock,**index)
return dic
def k_line_fund(ts_code,name,start_date,end_date):
#获取日行情数据
#
pa=pro.fund_daily(ts_code=ts_code, start_date=start_date,
end_date=end_date)
# pa.head()
pa.to_csv('/Users/xinran/07 长投/股票基金k线图/'+name+'.csv',
header=True, index=False)
# print(name+'已存')
#K线图可视化
from pyecharts import Kline
pa.index=pd.to_datetime(pa.trade_date)
pa=pa.sort_index()
v1=list(pa.loc[:,['open','close','low','high']].values)
t=pa.index
v0=list(t.strftime('%Y%m%d'))
kline = Kline(name,title_text_size=15)
kline.add("", v0, v1,is_datazoom_show=True,
mark_line=["average"],
mark_point=["max", "min"],
mark_point_symbolsize=60,
mark_line_valuedim=['highest', 'lowest'] )
path = '/Users/xinran/07 长投/股票基金k线图/'
kline.render(path+"%s.html" %name)
print(ts_code+' K线图已输出!')
def k_line_share(ts_code,name,start_date,end_date):
#获取日行情数据
# today = time.strftime("%Y%m%d", time.localtime())
pa=pro.daily(ts_code=ts_code, start_date=start_date,
end_date=today)
# pa.head()
pa.to_csv('/Users/xinran/07 长投/股票基金k线图/'+name+'.csv',
header=True, index=False)
#K线图可视化
from pyecharts import Kline
pa.index=pd.to_datetime(pa.trade_date)
pa=pa.sort_index()
v1=list(pa.loc[:,['open','close','low','high']].values)
t=pa.index
v0=list(t.strftime('%Y%m%d'))
kline = Kline(name,title_text_size=15)
kline.add("", v0, v1,is_datazoom_show=True,
mark_line=["average"],
mark_point=["max", "min"],
mark_point_symbolsize=60,
mark_line_valuedim=['highest', 'lowest'] )
path = '/Users/xinran/07 长投/股票基金k线图/'
kline.render(path+"%s.html" %name)
print(ts_code+' K线图已输出!')
if __name__ == "__main__":
today = time.strftime("%Y%m%d", time.localtime())
end_date = today
start_date = '20150101'
#设置token
token='需要tushare官网注册之后获取你的token'
ts.set_token(token)
pro = ts.pro_api(token)
#获取当前上市的股票代码、简称、注册地、行业、上市时间等数据
dic = get_code()##{name:ceode}
new_dict = {
v : k for k, v in dic.items()}#{code:name}
'''股票'''
share = pro.stock_basic(list_status='L') #股票
share_lst = ['601318.SH','600340.SH','002475.SZ','002475.SZ',
'300059.SZ','000725.SZ','002027.SZ']
for ts_code in share_lst:
# print(ts_code)
name = "%sK线图_%s" % (new_dict[ts_code],today)
k_line_share(ts_code,name,start_date,end_date)
'''基金'''
fund = pro.fund_basic(market='E')
fund_lst = ['159938.SZ','512980.SH','510880.SH','162411.SZ']
today = time.strftime("%Y%m%d", time.localtime())
for ts_code in fund_lst:
# print(ts_code)
name = "%sK线图_%s" % (new_dict[ts_code],today)
k_line_fund(ts_code,name,start_date,end_date)
# =============================================================================
# bonus
# 补充一个A股股指走势
=============================================================================
def get_index_data(indexs):
'''indexs是字典格式'''
index_data={
}
for name,code in indexs.items():
df=pro.index_daily(ts_code=code)
df.index=pd.to_datetime(df.trade_date)
index_data[name]=df.sort_index()
return index_data
#获取常见股票指数行情
indexs={
'上证综指': '000001.SH','深证成指': '399001.SZ',
'沪深300': '000300.SH','创业板指': '399006.SZ',
'上证50': '000016.SH', '中证500': '000905.SH',
'中小板指': '399005.SZ','上证180': '000010.SH'}
index_data=get_index_data(indexs)
#index_data['上证综指'].head()
#对股价走势进行可视化分析
subjects =list(index_data.keys())
#每个子图的title
plot_pos = [421,422,423,424,425,426,427,428]
# 每个子图的位置
new_colors = ['#1f77b4','#ff7f0e', '#2ca02c',
'#d62728','#9467bd','#8c564b', '#e377c2',
'#7f7f7f','#bcbd22','#17becf']
fig = plt.figure(figsize=(16,18))
fig.suptitle('A股股指走势',fontsize=18)
for pos in np.arange(len(plot_pos)):
ax = fig.add_subplot(plot_pos[pos])
y_data =index_data[subjects[pos]]['close']
b = ax.plot(y_data,color=new_colors[pos])
ax.set_title(subjects[pos])
# 将右上边的两条边颜色设置为空,相当于抹掉这两条边
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
plt.show()
plt.savefig('/Users/xinran/07 长投/股票基金k线图/A.png')
更新:
现在tushare设计了积分权限,导致获取数据出现权限问题
初始注册积分100分 只能获取股票日行情数据
基金数据获取不到门槛
可以用下面代码改一改,获取股票k线图
df = pro.daily(ts_code='601318.SH', start_date='20180701', end_date='20180718')
path = '/Users/xinran/07 长投/股票基金k线图/'
v1=list(df.loc[:,['open','close','low','high']].values)
t=df.trade_date
v0=list(pd.to_datetime(df.trade_date, format='%Y%m%d'))
#pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')
#v0=list(t.strftime('%Y%m%d'))
name = "601318.SH K线图"
kline = Kline(name,title_text_size=15)
kline.add("", v0, v1,is_datazoom_show=True,
mark_line=["average"],
mark_point=["max", "min"],
mark_point_symbolsize=60,
mark_line_valuedim=['highest', 'lowest'] )
kline.render(path+"%s.html" %name)