用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