python期货量化学习

  一直以来想要学习python去解决期货量化问题,通过数学描述变化的规律,从上海疫情封城开始学习一下python以及量化,在此记录一下;

  自学感觉非常艰难呀,尤其是python各项目代码更新频率并不同调导致项目中存在已弃用或即将弃用的方法,还需要经常性的补充或修改,以前辈代码为例进行修改

报错信息:

FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
sr = sr1.append(sr2).sort_index()

#改为
sr = pd.concat([sr1,sr2]).sort_index()

5日均线与30日均线双均线策略参考:

import pandas as pd
import tushare as ts

# 获取财经数据
#df = ts.get_k_data("601318",start="2000-01-01")
#df.to_csv("601318.csv")

# 读取财经数据并计算五日、三十日的平均收盘价
df = pd.read_csv("601318.csv",index_col = 'date',parse_dates = ['date'])[['open','close','low','high']]
df['ma5'] = df['close'].rolling(5).mean()
df['ma30'] = df['close'].rolling(30).mean()
df[['close','ma5','ma30']].plot()

# 获取金叉和死叉的日期
ar1 = df['ma5'] < df['ma30']
ar2 = df['ma5'] >= df['ma30']
death_cross = df[ar1 & ar2.shift(1)].index
golden_cross = df[-(ar1 | ar2.shift(1))].index
 
# 执行交易策略
first_money = 100000
money = first_money
hold = 0
sr1 = pd.Series(1,index=golden_cross)
sr2 = pd.Series(0,index=death_cross)
sr = pd.concat([sr1,sr2]).sort_index()

for i in range(0,len(sr)):
    p = df['open'][sr.index[i]]
    if sr.iloc[i] == 1:
        buy = money//(100*p)
        hold += buy*100
        money -= buy*100*p
    else:
        money += hold * p
        hold = 0

# 计算最后余下的金额总和
p = df['open'][-1]        
now_money = hold * p + money

print(now_money)
df['money']=now_money
df[['money']].plot()

你可能感兴趣的:(学习,python)