利用tushare数据获得近两年上市的大市值股票走势

import tushare as ts
import time
import pandas as pd
import os
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.finance as mpf
import datetime
from matplotlib.pylab import date2num
import sys

def getstockbasicinfo():
    filebasic = './output/stockbasic.csv'
    filetoday = './output/stocktoday.csv'
    if os.path.exists(filebasic):
        print("Get basic data from csv")
        dfstockbasic = pd.read_csv(filebasic, encoding="utf-8")
    else:
        print("Get basic data from internet")
        try:
            dfstockbasic = ts.get_stock_basics()
            dfstockbasic.to_csv(filebasic, encoding='utf-8')
        except Exception as e:
            print(e)
    if os.path.exists(filetoday):
        print("Get today data from csv")
        dfstocktoday = pd.read_csv(filetoday, encoding="utf-8")
    else:
        print("Get today data from internet")
        try:
            dfstocktoday = ts.get_today_all()
            dfstocktoday.to_csv(filetoday, encoding='utf-8')
        except Exception as e:
            print(e)

    dfstockbasic['tomarket'] = pd.to_numeric(dfstockbasic.timeToMarket)
    dflateststock = dfstockbasic[(dfstockbasic.tomarket >= 20151001)]
    dfmerge = pd.merge(dflateststock, dfstocktoday, on=['code', 'name'], how='left')
    dfmerge['totalnessets'] = (dfmerge.totals * dfmerge.trade)
    dfbigstock = dfmerge[dfmerge.totalnessets > 400]
    print(dfbigstock)
    codes = {}
    for index, row in dfbigstock.iterrows():
        codes['{:0>6}'.format(row['code'])] = row['totalnessets']
    getcandlecharts(codes)

def getcandlecharts(codes):
    chinese = mpl.font_manager.FontProperties(fname='C:\Windows\Fonts\simhei.ttf')
    plt.figure(figsize=(10, 8), facecolor='w')
    index = 1
    for code in codes:
        print(code)
        shyh = ts.get_k_data(code)
        mat_shyh = shyh.as_matrix()
        num_time = date_to_num(mat_shyh[:,0])
        mat_shyh[:,0]=num_time
        ax = plt.subplot(4, 4, index)
        mpf.candlestick_ochl(ax, mat_shyh,width=0.6, colorup="r", colordown="g", alpha=1.0)
        plt.grid(True)
        plt.xticks(rotation=30)
        plt.title('%s: %.2f' % (getstockinfo(code), codes[code]), fontproperties=chinese)
        plt.xlabel("Date")
        plt.ylabel("Price")
        ax.xaxis_date()
        index = index + 1
        if index == 16:
            break
    plt.suptitle('2015-10-01之后上市总市值超过400亿人民币的股票', fontproperties=chinese)
    plt.tight_layout(1.5)
    plt.subplots_adjust(top=0.92)
    plt.show()

if __name__ == "__main__":
        getstockbasicinfo()

图片示例:


2018-05-23 18_20_35-Figure 1.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容