tushare 开源数据包的使用

tushare 使用

  • python开源金融接口包:
    • tushare.org/trading.html#d2
  • 安装: pip install tushare
import tushare as ts
# 查看中国茅台 股票历史数据
df = tr.get_k_data('600519',"2000-01-01")
# 好存到本地
df.to_csv('./maotai.csv')
  • 修改数据中的 date 时间 值 为时间序列
# 查看date 列中元素类型
df['date'].dtype

import pandas as pd
# 读取本地 csv 文件中的数据
# index_col='date' 将date列作为行索引
# parse_dates=['date'] 将这一列转为时间 序列
df = pd.read_csv('./maotai.csv',index_col='date',parse_dates=['date'])

# 删除数据 一列数据
# inplace=True 映射回元数据 操作不返回数据
df.drop('Unnamed: 0',axis=1,inplace=True)


  • 根据时间序列查找数据
# 输出改股票 所有开盘比收盘上涨 3% 以上的 日期
b_index = (df['colse']-df['open'])/df['open'] > 0.03

# 可以将一组bool 值作为 df 的航索引
df.loc[b_index].index


  • 数据偏移

    df['close'].shift(1)

down_indexs = (df['colse']-df['open'].shift(1))/df['open'].shift(1) <= 0.02
df.loc[down_indexs].index

  • resample 数据的重新取样
  • 指定月份 年份查找第一个 或最后一个
df_ = df['2010','2019']
# 获取每月第一天的数据
df_.resample("M").first().head()
# 获取每年最后一天的数据
df_.resample("Y").last()

  • 从 2010-1019 年每月开始买入 100支 每年卖出 收益
# 假如我从2010年1月1日开始,每月第一个交易日买入1手股票,
# 每年最后一个交易日卖出所有股票,到今天为止,我的收益如何?

df_ = df["2010":"2019"]
df_.head()

df = df_
price_last = df['open'][-1]
#df = df['2010-01':'2019-01'] #剔除首尾无用的数据
#Pandas提供了resample函数用便捷的方式对时间序列进行重采样,根据时间粒度的变大或者变小分为降采样和升采样:
df_monthly = df.resample("M").first()
df_yearly = df.resample("Y").last()[:-1] #去除最后一年
cost_money = 0  # 持有的金钱
hold = 0 #每年持有的股票
for year in range(2010, 2020):
    cost_money -= df_monthly[str(year)]['open'].sum()*100
    hold += len(df_monthly[str(year)]['open']) * 100
    if year != 2019:
        cost_money +=df_yearly[str(year)]['close'][0]*hold
        hold = 0
cost_money += hold * price_last
print(cost_money)

1. 创建多层列索引

1) 隐式构造

最常见的方法是给DataFrame构造函数的index或者columns参数传递两个或更多的数组

qizhong qizhong qimo qimo chinese math chinese math tom 100 90 80 70

jay 100 90 80 70

# - 使用product:
# 最简单,推荐使用
col=pd.MultiIndex.from_product([['qizhong','qimo'],
                                ['chinese','math']])

#创建DF对象
df = DataFrame(data=np.random.randint(60,120,size=(2,4)),index=['tom','jay'], columns=col)
df
posted @ 2019-04-22 12:34  拐弯  阅读(415)  评论(0编辑  收藏  举报