数据分析之DataFrame基础操作巩固-股票分析

需求:股票分析

  • 使用tushare包获取某股票的历史行情数据。
    • tushare财经数据接口包,基于该模块可以获取任意股票的历史交易数据
    • pip install tushare
  • 输出该股票所有收盘比开盘上涨3%以上的日期。
  • 输出该股票所有开盘比前日收盘跌幅超过2%的日期。
  • 假如我从2010年1月1日开始,每月第一个交易日买入1手股票,每年最后一个交易日卖出所有股票,到今天为止,我的收益如何?
import pandas as pd
import tushare as ts

df = ts.get_k_data(code='600519',start='1990')
#df的持久化存储
df.to_csv('maotai.csv')
#读取本地数据
df = pd.read_csv('./maotai.csv')
df.head(5)

df.info()
#每一列的数据类型
#哪些列中存在空值
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4493 entries, 0 to 4492
Data columns (total 7 columns):
date      4493 non-null object
open      4493 non-null float64
close     4493 non-null float64
high      4493 non-null float64
low       4493 non-null float64
volume    4493 non-null float64
code      4493 non-null int64
dtypes: float64(5), int64(1), object(1)
memory usage: 245.8+ KB
  • 在观察数据的时候,如果发现时间数据为字符串类型则需要将其转换成时间序列类型
df['date'] = pd.to_datetime(df['date'])
#将date列作为源数据的行索引,inplace=True 意思是对df进行直接操作
df.set_index('date',inplace=True)
# 输出该股票所有收盘比开盘上涨3%以上的日期
#(收盘-开盘)/开盘 > 0.03
(df['close'] - df['open']) / df['open'] > 0.03

# 经验:在df的处理过程中,如果遇到了一组布尔值,下一步马上将布尔值作为源数据的行索引
df.loc[(df['close'] - df['open']) / df['open'] > 0.03] #可以获取true对应行数据
df.loc[(df['close'] - df['open']) / df['open'] > 0.03].index

# 输出该股票所有开盘比前日收盘跌幅超过2%的日期。
# (开盘-前日收盘)/前日收盘 < -0.02
(df['open'] - df['close'].shift(1)) / df['close'].shift(1) < -0.02
df.loc[(df['open'] - df['close'].shift(1)) / df['close'].shift(1) < -0.02].index
# shift(1)正数表示数据下移,负数表示上移
  • 假如我从2010年1月1日开始,每月第一个交易日买入1手股票,每年最后一个交易日卖出所有股票,到今天为止,我的收益如何?
    • 买入(开盘)
      • 一个完整的年需要买入12手==1200只
    • 卖出(收盘)
      • 一个完整的年需要卖出1次股票,一次卖出1200只
      • 特殊情况:2020年只可以买入股票无法卖出股票,没有及时卖出的股票的实际价值也要计算到总收益中
new_df = df['2010':'2020']
# 买股票
# 1.获取每一个完整的年对应每个月第一个交易日的行数据,行数据中可以提取出开盘价(买入股票的单价)
# 实现的技术:数据的重新取样
new_df.resample(rule='M') #将每一年中每一个对应的数据取出
new_df.resample(rule='M').first() #将月份数据中的第一行数据取出
#买入股票花费的总钱数
cost_money = (new_df.resample(rule='M').first()['open']).sum() * 100
cost_money
#卖出股票的钱数
new_df.resample(rule='A')#将2010-2020年,每一年的数据取出
new_df.resample(rule='A').last()[:-1] #每一年最后一个交易日对应的行数据

recv_money = new_df.resample(rule='A').last()[:-1]['close'].sum() *1200
recv_money
#剩余股票的价值也要计算到总收益中,剩余股票价值的单价可以用最近一天的收盘价来表示
last_price = new_df[-1:]['close'][0]
last_monry = 6*100*last_price
#总收益
last_monry + recv_money - cost_money
  • 注意:上述对数据进行重新取样操作的前提,源数据中行索引为时间序列类型

  • 总结

    • df的持久化存储
      • df.to_xxx():可以将df中的值进行任意形式的持久化存储
    • df的加载:
      • pd.read_xxx():可以将外部数据加载到df中
    • 如何将字符串形式的时间值转换成时间序列类型
      • pd.to_datetime(df['date])
    • 如何将某一列作为源数据的行索引
      • df.set_index('colName')
    • 如何将Series进行整体的上下移动
      • Series.shift(1)
        • 正数表示下移,负数表示上移
    • 数据的重新取样
      • df.resample(rule='')
      • df.resample(rule='').last/first()
    • 可以直接将布尔值作为df的行索引,就可以取出True对应的行数据。
posted @ 2020-06-30 16:58  小渣猫  阅读(727)  评论(0编辑  收藏  举报