!pip install -i https://pypi.tuna.tsinghua.edu.cn/simple tushare
import tushare as ts
import pandas as pd
from pandas import DataFrame,Series
import numpy as np
df = pd.read_csv('./maotai.csv').drop(labels='Unnamed: 0',axis=1)
df
# 将date列转为时间序列且将其作为源数据的行索引
df['date'] = pd.to_datetime(df['date'])
df.set_index('date',inplace=True)
df.head()
# df['close'].rolling(5) 依次取出第一个“前五天”、第二个“前五天”...
# df['close'].rolling(5).mean() 计算均值
ma5 = df['close'].rolling(5).mean()
ma30 = df['close'].rolling(30).mean()
ma5
date
2001-08-27 NaN
2001-08-28 NaN
2001-08-29 NaN
2001-08-30 NaN
2001-08-31 -162.504
...
2023-09-22 1825.506
2023-09-25 1826.142
2023-09-26 1823.954
2023-09-27 1821.954
2023-09-28 1821.986
Name: close, Length: 5289, dtype: float64
import matplotlib.pyplot as plt
%matplotlib inline
plt.plot(ma5[50:180])
plt.plot(ma30[50:180])
[<matplotlib.lines.Line2D at 0x1f3c9adc610>]
# 过滤NaN值
ma5 = ma5[30:]
ma30 = ma30[30:]
s1 = ma5 < ma30
s2 = ma5 > ma30
df = df[30:]
death_ex = s1 & s2.shift(1) # 判定死叉的条件 F -> T
df.loc[death_ex] # 死叉对应的行数据
death_date = df.loc[death_ex].index
golden_ex = ~(s1 | s2.shift(1)) # 判定金叉的条件 T -> F
golden_date = df.loc[golden_ex].index # 金叉的时间
============================================
如果我从假如我从2010年1月1日开始,初始资金为100000元,金叉尽量买入,死叉全部卖出,则到今天为止,我的炒股收益率如何?
============================================
s1 = Series(data=1,index=golden_date) # 1作为金叉的标识
s2 = Series(data=0,index=death_date) # 0作为死叉的标识
s = s1.append(s2)
s = s.sort_index() # 存储的是金叉和死叉对应的时间
s = s['2010':'2020'] # 存储的是金叉和死叉对应的时间
first_money = 100000 # 本金,不变
money = first_money # 可变的,买股票花的钱和卖股票收入的钱都从该变量中进行操作
hold = 0 # 持有股票的数量(股数:100股=1手)
for i in range(0,len(s)): # i表示的s这个Series中的隐式索引
# s[i] = 0 (死叉:卖)
# s[i] = 1(金叉:买)
if s[i] == 1: # 金叉的时间
# 基于100000的本金尽可能多的去买入股票
# 获取股票的单价(金叉时间对应的行数据中的开盘价)
time = s.index[i] # 金叉的时间
p = df.loc[time]['open'] # 股票的单价
hand_count = money // (p*100) # 使用100000最多买入多少手股票
hold = hand_count * 100 # 买股票的支数
money -= (hold * p) # 将买股票花的钱从money中减去
else:
# 将买入的股票卖出去
# 找出卖出股票的单价
death_time = s.index[i]
p_death = df.loc[death_time]['open'] # 卖股票的单价
money += (p_death * hold) # 卖出的股票收入加入到money
hold = 0
# 如何判定最后一天为金叉还是死叉
last_money = hold * df['close'][-1] #剩余股票的价值
# 总收益
# >0 赚钱
# <0 亏损
money + last_money - first_money
-22684925.799999997