用tushare对股票进行简单分析(仅供交流学习)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tushare as ts
#使用tushare 获取每只股票的行情数据
df = ts.get_k_data(‘600519’,start=‘-01-01’)
print(type(df))
df.to_csv(‘600519.csv’)
df = pd.read_csv(‘600519.csv’,index_col=‘date’,parse_dates=[‘date’])[[‘open’,‘close’,‘high’,‘low’]]
print(df)
#输出该股票所有收盘比开盘上涨3%以上的日期
print(df[(df[‘close’]-df[‘open’])/df[‘open’]>0.03].index)
#df.shift() 移动,正数向下移动,负数向上移动
#输出该股票所有开盘比前日收盘跌幅超过2%的日期
df[(df[‘open’]-df[‘close’].shift(1))/df[‘close’].shift(1)<=-0.02].index
#%% raw
#假如我从1月1日开始,每月第一个交易日买入1手股票,每年最后一个交易日卖出所有股票,到今天为止,我的收益如何?
#%%
price_last = df[‘open’][-1]
df = df[‘-01’:‘-01’] #剔除首尾无用的数据
df_monthly = df.resample(“MS” ).first() # 每月第一天
print(“df_monthly :”)
print(df_monthly)
print(“df_yearly:”)
df_yearly = df.resample(“A”).last()[:-1] # 每年最后一天
print(df_yearly)
cost_money=0
hold = 0
for year in range(,):
cost_money = cost_money+df_monthly[str(year)][‘open’].sum() * 100
hold = cost_money+len(df_monthly[str(year)][‘open’])*100
cost_money =cost_money - df_yearly[str(year)][‘open’][0] * hold
hold = 0
print(‘cost_money: %s’%(0-cost_money))
#求5日均线和30日均线
df = pd.read_csv(‘600519.csv’,index_col=‘date’,parse_dates=[‘date’])[[‘open’,‘close’,‘low’,‘high’]]
print(df.head())
df[‘ma5’] = np.NAN
df[‘ma30’] = np.NAN
df[‘ma5’] = df[‘close’].rolling(5).mean() # 窗口向下滚动5个
df[‘ma30’] = df[‘close’].rolling(30).mean() # 窗口向下滚动30个
#画均线图
df = df[:800]
df[[‘close’,‘ma5’,‘ma30’]].plot()
plt.show()
原文链接:/tiankongzhike/article/details/106447839