python 數據分析學習 - 股票數據(一)

免責聲明:本人不是專業人士,純粹個人愛好,如有錯誤歡迎指正。

一、數據採集

本文分析的對象是股票數據,數據採集渠道和方式很多,可以自己寫爬蟲,也可以用開源的工具。這裏我們使用開源工具tushare, https://tushare.pro/register?reg=332190

step 1. 安裝tushare

pip install tushare -i https://pypi.tuna.tsinghua.edu.cn/simple

step 2. 註冊賬號

雖然是開源,但是需要先註冊後才能獲取數據。註冊地址:https://tushare.pro/register?reg=332190

step 3. 獲取token

獲取token方法請查看 https://tushare.pro/document/1?doc_id=39

step 4. 調取數據

import tushare as ts

# 設置token
ts.set_token('your token here')
# 初始化
pro = ts.pro_api()
# 調取日線數據
df = pro.daily(ts_code='000001.SZ', start_date='20180701', end_date='20180718')
# 查看數據
df.head()

二、計算移動平均線

# 計算平均線
ma5 = df['close'].rolling(5).mean()
ma10 = df['close'].rolling(10).mean()
ma20 = df['close'].rolling(20).mean()

# 合併,並重命名重複的字段後綴
m = pd.merge(df, ma5, on='trade_date', suffixes=('', '_ma5'))
m = pd.merge(m, ma10, on='trade_date', suffixes=('', '_ma10'))
m = pd.merge(m, ma20, on='trade_date', suffixes=('', '_ma20'))

# 刪除前120天的數據
m = m.iloc[120:, :]

# 重命名字段名
m = m.rename(columns={'close_ma5':'ma5', 'close_ma10':'ma10', 'close_ma20':'ma20'})

三、畫圖

step 1. 安裝matplotlib

pip install matplotlib

step 2. 引用

import matplotlib.pyplot as plt
from matplotlib.pyplot import MultipleLocator

step 3. 利用處理的數據畫圖

fig = plt.figure(figsize = (20,15))

x = m.index.astype('str')

# 繪圖
plt.plot(x, # x軸數據
         m.ma5, # y軸數據
         linestyle = '-', # 折線類型
         linewidth = 2, # 折線寬度
         color = 'brown', # 折線顏色
         marker = 'o', # 點的形狀
         markersize = 2, # 點的大小
         markeredgecolor='black', # 點的邊框色
         markerfacecolor='brown', # 點的填充色
         label = 'ma5') 

plt.plot(x, # x軸數據
         m.ma20, # y軸數據
         linestyle = '-', # 折線類型
         linewidth = 2, # 折線寬度
         color = 'purple', # 折線顏色
         marker = 'o', # 點的形狀
         markersize = 2, # 點的大小
         markeredgecolor='black', # 點的邊框色
         markerfacecolor='purple', # 點的填充色
         label = 'ma20') 

# 添加標題和座標軸標籤
plt.title('000001')
plt.xlabel('date')
plt.ylabel('p')

# 剔除圖框上邊界和右邊界的刻度
plt.tick_params(top = 'off', right = 'off')

# 爲了避免x軸日期刻度標籤的重疊,設置x軸刻度自動展現,並且45度傾斜
plt.xticks(rotation = 45)

x_major_locator = MultipleLocator(120)
ax = plt.gca()
ax.xaxis.set_major_locator(x_major_locator)

# 顯示圖形
plt.show()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章