001 用python和tushare获取股票数据

数据获取可以用爬虫,api。api我了解的有tushare和pandas_datareader,用conda或者pip命令安装即可。此处只介绍tushare。

一、 注册

到tushare官网注册,并获取自己的token(调用api需要token才可以访问数据)。官网链接如下:

tushare pro官网(积分制,积分越多,权限越高)

Tushare数据

tushare官网(基础版,可获取的数据少,免费,已不再更新)

Tushare -财经数据接口包

注册后会有100积分,修改个人资料获得20积分,貌似积分越高允许的数据获取频率越高。

toke在个人主页可以查看。

二、 安装

pip instal tushare

三、 使用

简单例子如下:

1. 导入相关的库

import datetime
import tushare as ts
import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt

import seaborn as sns    # 画图用的

# token_str是在tushare注册的token
pro=ts.pro_api(token_str)

 2 获取的股票数据

# 获取某个股票的日数据。SZ代表深交所,SH代表上交所
start=datetime.date(2022,1,1).strftime('%Y%m%d')
end=datetime.date(2023,2,15).strftime('%Y%m%d')
df1 = pro.daily(ts_code='300474.SZ', start_date=start, end_date=end)

# 获取上证指数数据,需要2000积分权限
# df1 = pro.index_daily(ts_code='000001.SH', start_date=start, end_date=end)
print(df1)

# 升序
df1 = df1.sort_index(ascending=False)

 3. 查看前若干行数据

 4.  股票的描述性统计信息

df1.describe().round(2)    # 描述性统计

 5. 绘制收盘价趋势

df1.index = df1['trade_date']
df1['close'].plot(figsize=(12, 6))
plt.ylabel('close price')
plt.show()

 6. 绘制成交量数据

df1.index = df1['trade_date']
df1['vol'].plot(figsize=(12, 6))
plt.ylabel('vol')
plt.show()

7. 移动平均值

ma_days = [10, 20, 50]
for ma in ma_days:
    df1['ma{}'.format(ma)] = df1['close'].rolling(ma).mean()

df1[['close', 'ma10', 'ma20', 'ma50']].plot(figsize=(12, 6))
plt.ylabel('close price')
plt.show()

 8. 日收益率

df1['daily_yield'] = df1['close'].pct_change()
df1['daily_yield'].plot(figsize=(12, 6))
plt.ylabel('daily yield')
plt.show()

9. 股票相关性

 

sns.jointplot(x='300474.SZ', y='603893.SH', data=daily_yield)

10. 蒙特卡洛模拟

# 定义蒙特卡洛函数
def monte_carlo(start_price, days, mu, sigma):
    dt = 1/days
    price = np.zeros(days)
    price[0] = start_price
    shock = np.zeros(days)
    drift = np.zeros(days)
    
    for x in range(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

# 获取某个股票的日数据。SZ代表深交所,SH代表上交所
start=datetime.date(2022,1,1).strftime('%Y%m%d')
end=datetime.date(2023,2,16).strftime('%Y%m%d')
df2 = pro.daily(ts_code='300474.SZ', start_date=start, end_date=end)
df2 = df2.sort_index(ascending=False)

rets = df2.close.pct_change()[1:]    # 涨幅
rets = rets.dropna()
rets.quantile(0.05)    # 95%置信空间外的分位数对应的可能涨跌


runs = 10000    # 模拟次数
start_price = 82.67
days = 3    # 预测若干天后价格
mu = rets.mean()
sigma = rets.std()
simulations = np.zeros(runs)

for run in range(runs):
    simulations[run] = monte_carlo(start_price, days, mu, sigma)[days-1]

q = np.percentile(simulations, 1)

print(simulations)
plt.figure(figsize=(8, 6))
plt.hist(simulations, bins=50, color='grey')
plt.figtext(0.6, 0.8, s='start price:%.2f' % start_price)
plt.figtext(0.6,0.7, 'predicted price:%.2f' % simulations.mean())
plt.figtext(0.15, 0.6, "q(0.99: %.2f)" % q)
plt.axvline(x=q, linewidth=6, color='r')
plt.title('%d天后模拟价格分布图' %days, weight='bold')
plt.show()

 

 

  • 6
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值