import datetime
import tushare as ts
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
ts.set_token('*********************************************************')
pro=ts.pro_api()
# 獲取滬深300前一年的日線資料
df = pro.index_daily(ts_code = '399300.SZ' , start_date = '20191106', end_date = '20201106',\
fields='ts_code,trade_date,close,open,high,low')
# 獲取日線價
new_price = df[['close'][0]].values.tolist()
# 獲取周線均價
df1 = pro.index_weekly(ts_code = '399300.SZ' , start_date = '20191106', end_date = '20201106',\
fields='ts_code,trade_date,close,open,high,low')
week_price = df1[['close'][0]].values.tolist()
# 獲取月線均價
df2 = pro.index_monthly(ts_code = '399300.SZ' , start_date = '20191106', end_date = '20201106',\
fields='ts_code,trade_date,close,open,high,low')
mon_price = df2[['close'][0]].values.tolist()
# 獲取時間戳 顯示日線
date_list = []
for i in range(len(df[['trade_date'][0]])):
date_list.append(datetime.datetime.strptime(df[['trade_date'][0]][i],'%Y%m%d'))
plt.plot(date_list,new_price,color = 'blue')
plt.xticks(rotation = 45)
plt.legend(loc='upper left')
#設定周線
date_list1 = []
for i in range(len(df1[['trade_date'][0]])):
date_list1.append(datetime.datetime.strptime(df1[['trade_date'][0]][i],'%Y%m%d'))
plt.plot(date_list1,week_price,color = 'red')
plt.xticks(rotation = 45)
plt.legend(loc='upper left')
#設定月線
date_list2 = []
for i in range(len(df2[['trade_date'][0]])):
date_list2.append(datetime.datetime.strptime(df2[['trade_date'][0]][i],'%Y%m%d'))
plt.plot(date_list2,mon_price,linestyle = '--')
plt.xticks(rotation = 45)
plt.legend(loc='upper right')
# 折線圖顯示
plt.show()