python预测股票价格tushare_用tushare对股票进行简单分析

用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=‘2008-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

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

#%%

price_last = df[‘open’][-1]

df = df[‘2008-01’:‘2020-01’] #剔除首尾无用的数据

df_monthly = df.resample(“MS” ).first() # 每月第一天

print(“df_monthly 2008:”)

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(2008,2020):

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()

原文链接:https://blog.csdn.net/tiankongzhike/article/details/106447839

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值