借助akshare数据源,多只股票采用同种策略,分析判断策略的综合表现。
import akshare as ak
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
from datetime import timedelta
import warnings
warnings.filterwarnings('ignore')
import matplotlib.pyplot as plt
%matplotlib inline
list = ['603719','002427','600309','600903']
last = pd.DataFrame()
for stock in list:
print(stock)
end =datetime.now().strftime('%Y-%m-%d')
start = (datetime.now()-timedelta(days=10000)).strftime('%Y-%m-%d')
data = ak.stock_zh_a_hist(symbol=stock, period="daily", start_date="19900301", end_date='20230218', adjust="")
data['日期'] = pd.to_datetime(data['日期'], format='%Y-%m-%d')
data.rename(columns= {'日期':'date','开盘':'open','最高':'high','最低':'low','收盘':'close','成交量':'volume'},inplace=True)
data.set_index('date',inplace=True)
trading_signal =pd.DataFrame(index=data.index)
trading_signal['price'] = data['close']
trading_signal['diff'] = trading_signal['price'].diff(5)
trading_signal = trading_signal.fillna(0.0)
trading_signal['signal'] = np.where(trading_signal['diff']<0,0,1)
trading_signal['code'] = stock
trading_signal['order'] = trading_signal['signal'].diff()*1000
trading_signal['cost'] = np.where(trading_signal['order']>0,-50,0)
trading_signal['bj'] = 100000.00
initial_cash = 100000.00
trading_signal['stock'] = trading_signal['order']*trading_signal['price']
trading_signal['cash'] = initial_cash-(trading_signal['order'].diff()*trading_signal['price']).cumsum()
trading_signal['total'] = trading_signal['stock'] + trading_signal['cash']+trading_signal['cost']
trading_signal['total2'] = trading_signal['total']
trading_signal['total2'].plot()
#trading_signal= trading_signal.reset_index()
last = pd.concat([last,trading_signal],axis=1)
(last['total2'].ffill()).sum(axis=1).plot()
plt.figure(figsize=(16,9))
plt.plot(last['total'].sum(axis=1),label='total asset')
# plt.plot(trading_signal['order'].cumsum()*trading_signal['price'],'--',
# label='stock value')
#plt.xticks([0,120,240])
plt.grid()
plt.legend(loc='best')
plt.show()
last['count'] = (last['total2'].ffill().count(axis=1))