V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
LittleUqeer
V2EX  ›  Python

『python 金融应用』如何用 seaborn 包来分析股票

  •  
  •   LittleUqeer · 2016-12-29 15:54:20 +08:00 · 2513 次点击
    这是一个创建于 2674 天前的主题,其中的信息可能已经有所发展或是发生改变。

    今天,我想和大家分享一下一些分析股票的方法。在这里以贴代码为主,大家感兴趣的话直接复制运行就可以生成相应的图表分析了。

    一、股票的基本信息

    分析股票示例(以 600050.XSHG 中国联通 为例),导入股票各项信息

    data = DataAPI.MktEqudGet(secID=u"",ticker=u"600050",beginDate=u"",endDate=u"",isOpen="",field=u"secID,secShortName,tradeDate,openPrice,highestPrice,lowestPrice,closePrice,turnoverVol",pandas="1")
    data_hou = DataAPI.MktEqudAdjAfGet(secID=u"",ticker=u"600050",tradeDate=u"",isOpen="",beginDate=u"",endDate=u"",field=u"secID,tradeDate,closePrice",pandas="1")
    data_hou = data_hou.rename(columns = {'closePrice':'Adj_closePrice'})
    data_new = pd.merge(data,data_hou,on='tradeDate')
    data_new = data_new.set_index('tradeDate')
    data_new1 = data_new.copy()
    data_new1.head().append(data_new1.tail())
    
    

    简单统计分析,输入下方代码即可显示出股票的开盘价,最高价,最低价,收盘价,成交量,前复权收盘价。

    data_new1.describe()
    
    

    股票收盘价走势

    data_new1['Adj_closePrice'].plot(legend=True,figsize=(14,6))
    
    

    成交量走势

    data_new1['turnoverVol'].plot(legend=True,figsize=(14,6))
    
    

    移动平均线走势图

    ma_day = [10,20,50]
    
    for ma in ma_day:
        column_name = "MA for %s days" %(str(ma))
        data_new1[column_name]=pd.rolling_mean(data_new1['Adj_closePrice'],ma)
    
    
    data_new1[['Adj_closePrice','MA for 10 days','MA for 20 days','MA for 50 days']].plot(subplots=False,figsize=(14,6))
    
    

    股票每天的百分比变化

    data_new1['Daily Return'] = data_new1['Adj_closePrice'].pct_change()
    data_new1['Daily Return'].plot(figsize=(14,6),legend=True,linestyle='--',marker='o')
    
    

    平均收益直方图

    data_new1['Daily Return'].hist(color="#4878cf")
    
    

    每日收益图

    sns.distplot(data_new1['Daily Return'].dropna(),bins=100, color="b")
    
    

    分析多支股票示例(以 600050.XSHG , 000651.XSHG , 600158.XSHG,600115.XSHG 为例)

    将每个公司的每日收盘价的百分数变化,及涨幅或者降幅,可以评估其涨幅前景

    tech_rets = data_all2.pct_change()
    tech_rets.head()
    
    

    然后看某一支股票自身的线性相关系

    sns.jointplot('000930','000930',tech_rets,kind='scatter',color='seagreen')
    
    

    不同股票的线性相关系

    sns.jointplot('000930','600115',tech_rets,kind='scatter')
    
    

    四个公司一起比较,该函数用于成对的比较不同数据集之间的相关性,而对角线则会显示该数据集的直方图

    sns.pairplot(tech_rets.dropna())
    
    

    对角线直方图

    returns_fig = sns.PairGrid(tech_rets.dropna())
    
    

    右上角散点图

    returns_fig.map_upper(plt.scatter,color='purple')
    
    

    左下角核密度图

    returns_fig.map_lower(sns.kdeplot,cmap='cool_d')
    
    

    对角线直方图

    returns_fig.map_diag(plt.hist,bins=30)
    
    

    原股票数据的分析

    returns_fig = sns.PairGrid(data_all2)
    returns_fig.map_upper(plt.scatter,color='purple')
    returns_fig.map_lower(sns.kdeplot,cmap='cool_d')
    returns_fig.map_diag(plt.hist,bins=30)
    
    

    四支股票相关系数

    sns.corrplot(tech_rets.dropna(),annot=True)
    
    

    二、股票的风险信息

    推测最多亏多少钱

    rets = tech_rets.dropna()
    area = np.pi*20
    plt.scatter(rets.mean(), rets.std(),alpha = 0.5,s =area)
    plt.xlabel('Expected returns')
    plt.ylabel('Risk')
    
    #分别以 rets 的平均值,标准差为 xy 轴
    for label, x, y in zip(rets.columns, rets.mean(), rets.std()):
        plt.annotate(
            label, 
            xy = (x, y), xytext = (50, 50),
            textcoords = 'offset points', ha = 'right', va = 'bottom',
            arrowprops = dict(arrowstyle = '-', connectionstyle = 'arc3,rad=-0.3'))
    
    

    运行一下可以看到图表中 600158.中体产业 的预计收益要高于其他三家公司,但是风险值也要高于其他三家公司。

    分析之前看一下基本信息,以 600050.XSHG 为例

    sns.distplot(data_new1['Daily Return'].dropna(),bins=100, color="b")
    
    

    百位分数, 95%的置信

    rets['600050'].quantile(0.05)
    
    

    一天的损失不会超过 0.0356, 如果我们有一百万的投资,我们一天 5% VaR 为 0.0356 * 1000000 = 35600 元

    三、基于风险价值的蒙特卡洛方法

    days = 365
    dt = 1./days
    mu = rets.mean()['600050']
    sigma = rets.std()['600050']
    
    def stock_monte_carlo(start_price,days,mu,sigma):
        price = np.zeros(days)
        price[0] = start_price
        shock = np.zeros(days)
        drift = np.zeros(days)
        
        for x in xrange(1,days):
            shock[x] = np.random.normal(loc=mu * dt, scale=sigma * np.sqrt(dt))
            drift[x] = mu * dt
            price[x] = price[x-1] + (price[x-1] * (drift[x] + shock[x]))
        return price
    
    
    start_price = 2.924
    
    for run in xrange(100):
        plt.plot(stock_monte_carlo(start_price,days,mu,sigma))
    plt.xlabel("Days")
    plt.ylabel("Price")
    
    
    runs = 10000
    simulations = np.zeros(runs)
    np.set_printoptions(threshold=5)
    for run in xrange(runs):    
        simulations[run] = stock_monte_carlo(start_price,days,mu,sigma)[days-1];
    
    
    q = np.percentile(simulations, 1)
    plt.hist(simulations,bins=200)
    plt.figtext(0.6, 0.8, s="Start price: %.2f" %start_price)
    plt.figtext(0.6, 0.7, "Mean final price: %.2f" % simulations.mean())
    plt.figtext(0.6, 0.6, "VaR(0.99): %.2f" % (start_price - q,))
    plt.figtext(0.15, 0.6, "q(0.99): %.2f" % q)
    plt.axvline(x=q, linewidth=4, color='r')
    plt.title(u"Final price distribution for 600050 after %s days" % days, weight='bold')
    
    

    这种方法基本上是你购买的股票的风险将在 0.16 元 (约 99% 的时间里,蒙特卡洛模拟的结果) 如果想自己画股票的 K 线图,可以参考这篇帖子: https://uqer.io/community/share/57cac259228e5b5b831173c2

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3401 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 11:40 · PVG 19:40 · LAX 04:40 · JFK 07:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.