def 每日浮动收益统计(symbol:str, Type:str): from data_reader import get_index_day, get_stock_day, get_index_future_day, get_comm_future_day import pymssql start_date = str(date_list.iloc[1])[:10] end_date = str(date_list.iloc[-1])[:10] print("Fetching data from SQL database...") if Type=='stock': close = get_stock_day(symbol, start_date, end_date, freq = '1D') elif Type=='index': close = get_index_day(symbol, start_date, end_date, freq = '1D') elif Type=='index_future': close = get_index_future_day(symbol, start_date, end_date, freq = '1D') elif Type=='comm_future': close = get_comm_future_day(symbol, start_date, end_date, freq = '1D') elif Type=='coin': conn = pymssql.connect(server='192.168.0.28', port=1433, user='******', password='******', database='rawdata',charset = 'GBK') SQL = "select * from coin.dbo.coin_1min where "+"date between "+"\'"+start_date+"\' and \'" + end_date+"\'" temp_data = pd.read_sql(SQL, conn) close = temp_data.set_index('date') close = close.resample('1D').last() elif Type[:3] == 'AIP': if Type[-5:] == 'stock': close = get_stock_day(symbol, start_date, end_date, freq = '1D') elif Type[-5:] == 'index': close = get_index_day(symbol, start_date, end_date, freq = '1D') else:raise TypeError('Type "{}" is NOT acceptable, please check your input.'.format(Type)) else: raise TypeError('Type "{}" is NOT acceptable, please check your input.'.format(Type)) close.index = close.index + pd.Timedelta(24, unit='h') record = [] 截止当日的累计盈利, comfirmed_profit = 0, 0 for day in close.index: float_profit = 0 for deal in deal_list: if deal.is_valid(day): float_profit += deal.cal_floating(close.loc[day]['sclose']) deal.floating_profit=deal.cal_floating(close.loc[day]['sclose']) elif day.date()==deal.end.date(): #如果是当天结束的,当天确认收益 deal.confirm_profit() comfirmed_profit+=deal.profit #deal_list.remove(deal) 截止当日的累计盈利 = comfirmed_profit + float_profit #print(day, int(float_profit), int(comfirmed_profit), int(截止当日的累计盈利),sep='\t') record.append((day, float_profit, comfirmed_profit, 截止当日的累计盈利)) ans=pd.DataFrame(record,columns=('date','floating_profit','comfirmed_profit','accumulated_profit')) ans=ans.set_index('date') if Type.endswith('future'): choice = input("You are using futures;\nDo you want to multiply amount by 200?\nInput 1 for YES, 0 for NO: ") if choice=='0': future_multiplier = 1 else: future_multiplier = 200 ans[['floating_profit','comfirmed_profit','accumulated_profit']]*=future_multiplier ans['当日盈亏']=ans.accumulated_profit.diff() return ans
def 每日浮动收益统计(symbol='', Type='stock'): from data_reader import get_index_day, get_stock_day, get_index_future_day start_date = str(date_list[0])[:10] end_date = str(date_list[-1])[:10] # 如果未指定代码,则从ts原始文件中选取 if symbol=='': symbol = pd.read_excel(f, sheet_name=-1,header=2).columns[1] if Type=='stock': close = get_stock_day(symbol, start_date, end_date, freq = '1D') elif Type=='index': close = get_index_day(symbol, start_date, end_date, freq = '1D') elif Type=='future': close = get_index_future_day(symbol, start_date, end_date, freq = '1D') close.index=close.index+pd.Timedelta(15,unit='h') record=[] 截止当日的累计盈利=0 comfirmed_profit=0 for day in close.index: float_profit=0 for deal in deal_list: if deal.is_valid(day): float_profit += deal.cal_floating(close.loc[day]['close']) deal.floating_profit=deal.cal_floating(close.loc[day]['close']) elif day.date()==deal.end.date(): #如果是当天结束的,当天确认收益 deal.confirm_profit() comfirmed_profit+=deal.profit #deal_list.remove(deal) 截止当日的累计盈利 = comfirmed_profit + float_profit #print(day, int(float_profit), int(comfirmed_profit), int(截止当日的累计盈利),sep='\t') record.append((day, (float_profit), (comfirmed_profit), (截止当日的累计盈利))) ans=pd.DataFrame(record,columns=('date','floating_profit','comfirmed_profit','accumlated_profit')) ans=ans.set_index('date') ans['当日盈亏']=ans.accumlated_profit.diff() return ans
def 每日浮动收益统计(symbol:str, Type:str): from data_reader import get_index_day, get_stock_day, get_index_future_day, get_comm_future_day start_date = str(date_list[0])[:10] end_date = str(date_list[-1])[:10] if Type=='stock': close = get_stock_day(symbol, start_date, end_date, freq = '1D') elif Type=='index': close = get_index_day(symbol, start_date, end_date, freq = '1D') elif Type=='index_future': close = get_index_future_day(symbol, start_date, end_date, freq = '1D') elif Type=='comm_future': close = get_comm_future_day(symbol, start_date, end_date, freq = '1D') else: print('Type is NOT acceptable, please check your input.') quit() close.index = close.index + pd.Timedelta(15, unit='h') record = [] 截止当日的累计盈利, comfirmed_profit = 0, 0 for day in close.index: float_profit = 0 for deal in deal_list: if deal.is_valid(day): float_profit += deal.cal_floating(close.loc[day]['sclose']) deal.floating_profit=deal.cal_floating(close.loc[day]['sclose']) elif day.date()==deal.end.date(): #如果是当天结束的,当天确认收益 deal.confirm_profit() comfirmed_profit+=deal.profit #deal_list.remove(deal) 截止当日的累计盈利 = comfirmed_profit + float_profit #print(day, int(float_profit), int(comfirmed_profit), int(截止当日的累计盈利),sep='\t') record.append((day, float_profit, comfirmed_profit, 截止当日的累计盈利)) ans=pd.DataFrame(record,columns=('date','floating_profit','comfirmed_profit','accumlated_profit')) ans=ans.set_index('date') if Type.endswith('future'): choice = input("You are using futures;\nDo you want to multiply amount by 200?\nInput 1 for YES, 0 for NO: ") if choice=='0': future_multiplier = 1 else: future_multiplier = 200 ans[['floating_profit','comfirmed_profit','accumlated_profit']]*=future_multiplier ans['当日盈亏']=ans.accumlated_profit.diff() return ans
import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sn import sklearn as skl import talib from sklearn.linear_model import LinearRegression import pymssql from WindPy import w from WindPy import * N = 60 year_start = 2012 year_end = 2017 data = get_stock_day('600000.SH', '2010-01-01', '2017-12-31') w.start() rawdata = w.wsd("600000.SH", "dealnum", "2010-01-01", "2017-12-31", "") rawdata = pd.DataFrame(rawdata.Data[0], index=rawdata.Times, columns=['dealnum']) data = pd.concat([data, rawdata], axis=1) data['D'] = data['amt'] / data['dealnum'] data = data['2012':] # %% 选股 def collect_data(): data = pd.DataFrame()
def create_ta_data(stock): print("Processing", stock) if stock in stock_pool: SS = rd.get_stock_day(stock, "2010-01-01", "2019-01-01", "1D") SS = SS / SS.iloc[0] Return = holding_return[stock] target = holding_return.rank(axis=1)[stock] xlabel = label(target) target = pd.DataFrame(target) target["label"] = xlabel target = target[["label"]] elif stock == "benchmark": SS = benchmark SS.columns = ["sclose", "sopen", "high", "low", "vol"] MA = pd.DataFrame() # 计算10-90日均线 for i in range(10, 50, 10): local_MA = ta.MA(SS.sclose, timeperiod=i) local_MA.name = stock + "_MA_" + str(i) MA = pd.concat([MA, local_MA], axis=1) MACD1, MACD2, XX = ta.MACD(SS.sclose) MACD = pd.concat([MACD1, MACD2], axis=1) MACD.columns = [stock + "_MACD1", stock + "_MACD2"] ADX = ta.ADX(SS.high, SS.low, SS.sclose) / 25 ADXR = ta.ADXR(SS.high, SS.low, SS.sclose) / 25 aroondown, aroonup = ta.AROON(SS.high, SS.low) aroondown = aroondown / 100 aroonup = aroonup / 100 ATR = ta.ATR(SS.high, SS.low, SS.sclose) Bupper, Bmiddle, Blower = ta.BBANDS(SS.sclose) group1 = pd.concat( [ADX, ADXR, aroondown, aroonup, ATR, Bupper, Bmiddle, Blower], axis=1 ) group1.columns = [ stock + "_ADX", stock + "_ADXR", stock + "_aroondown", stock + "_aroonup", stock + "_ATR", stock + "_Bupper", stock + "_Bmiddle", stock + "_Blower", ] BOP = ta.BOP(SS.sopen, SS.high, SS.low, SS.sclose) CCI = ta.CCI(SS.high, SS.low, SS.sclose) CCI = CCI / 100 CMO = ta.CMO(SS.sclose) CMO = CMO / 100 DX = ta.DX(SS.high, SS.low, SS.sclose) EMA = ta.EMA(SS.sclose) KAMA = ta.KAMA(SS.sclose) MFI = ta.MFI(SS.high, SS.low, SS.sclose, SS.vol) MFI = MFI / 100 MOM = ta.MOM(SS.sclose) RSI = ta.RSI(SS.sclose) RSI = (RSI - 50) / 100 group2 = pd.concat([BOP, CCI, CMO, DX, EMA, KAMA, MFI, MOM, RSI], axis=1) group2.columns = [ stock + "_BOP", stock + "_CCI", stock + "_CMO", stock + "_DX", stock + "_EMA", stock + "_KAMA", stock + "_MFI", stock + "_MOM", stock + "_RSI", ] SAR = ta.SAR(SS.high, SS.low) TRANGE = ta.TRANGE(SS.high, SS.low, SS.sclose) TRIMA = ta.TRIMA(SS.sclose) group3 = pd.concat([SAR, TRANGE, TRIMA], axis=1) group3.columns = [stock + "_SAR", stock + "_TRANGE", stock + "_TRIMA"] SS.columns = [ stock + "_close", stock + "_open", stock + "_high", stock + "_low", stock + "_vol", ] raw_ta = pd.concat([SS, MA, MACD, group1, group2, group3], axis=1) if stock in stock_pool: raw_ta = pd.concat([raw_ta, target, Return], axis=1) return raw_ta
def 每日浮动收益统计(symbol: str, Type: str): from data_reader import get_index_day, get_stock_day, get_index_future_day, get_comm_future_day import pymssql start_date = str(date_list.iloc[1] - pd.Timedelta(30, 'd'))[:10] # 早30天,为了使用RSI数据 end_date = str(date_list.iloc[-1])[:10] print("[Time Range]", start_date, "~", end_date) print("Fetching data from SQL database...") if Type == 'stock': close = get_stock_day(symbol, start_date, end_date, freq='1D') elif Type == 'index': close = get_index_day(symbol, start_date, end_date, freq='1D') elif Type == 'index_future': close = get_index_future_day(symbol, start_date, end_date, freq='1D') elif Type == 'comm_future': close = get_comm_future_day(symbol, start_date, end_date, freq='1D') elif Type == 'coin': conn = pymssql.connect(server='192.168.0.28', port=1433, user='******', password='******', database='rawdata', charset='GBK') SQL = "select * from coin.dbo.coin_1min where " + "date between " + "\'" + start_date + "\' and \'" + end_date + "\'" temp_data = pd.read_sql(SQL, conn) close = temp_data.set_index('date') close = close.resample('1D').last() elif Type == 'AIP': close = get_stock_day(symbol, start_date, end_date, freq='1D') else: print('Type is NOT acceptable, please check your input.') quit() close.index = close.index + pd.Timedelta(24, unit='h') print("SQL data loaded...") print("统计当日盈亏中...") t0 = time.time() record = [] 截止当日的累计盈利, comfirmed_profit = 0, 0 for day in close.index[30:]: #close数据提前了30天 float_profit, 累计投入 = 0, 0 for deal in deal_list: if (deal.start < day) and (deal.end > day): 累计投入 += deal.investment if deal.is_valid(day): float_profit += deal.cal_floating(close.loc[day]['sclose']) deal.floating_profit = deal.cal_floating( close.loc[day]['sclose']) elif day.date() == deal.end.date(): #如果是当天结束的,当天确认收益 deal.confirm_profit() comfirmed_profit += deal.profit #deal_list.remove(deal) 截止当日的累计盈利 = comfirmed_profit + float_profit #print(day, int(float_profit), int(comfirmed_profit), int(截止当日的累计盈利),sep='\t') record.append((day, float_profit, comfirmed_profit, 截止当日的累计盈利, 累计投入)) ans = pd.DataFrame(record, columns=('date', 'floating_profit', 'comfirmed_profit', 'accumulated_profit', 'accumulated_investment')) ans = ans.set_index('date') if Type.endswith('future'): choice = input( "You are using futures;\nDo you want to multiply amount by 200?\nInput 1 for YES, 0 for NO: " ) if choice == '0': future_multiplier = 1 else: future_multiplier = 200 ans[['floating_profit', 'comfirmed_profit', 'accumulated_profit']] *= future_multiplier ans['当日盈亏'] = ans.accumulated_profit.diff() t1 = time.time() tpy = t1 - t0 print('统计当日盈亏已完成,用时 %5.3f 秒' % tpy) return ans, close
# worths, stock_close = {}, {} # for index in STOCK_POOL: # print("----- Now processing {} ...".format(index)) # s.read_files(FILEPATH + index + '.xlsx') # s.start() # s.AIP_net() # s.generate_profit_curve() # print("----- Processed successfully! -----", end='\n\n') # worths[index]=s.ans # stock_close[index]=s.stock_close.sclose # start_date = worths[index].index[0] #%% 获取收盘数据 price = {} for symbol in STOCK_POOL: temp = get_stock_day(symbol, START_DATE, END_DATE, '1D') price[symbol] = temp.sclose price = pd.DataFrame(price) price.fillna(method='ffill', inplace=True) price_diff = price.diff() price_pct_chg = price.pct_change() #%% 计算相对强弱指数RSI RSI_Duration = 12 rsi = {} for index in STOCK_POOL: rsi[index] = talib.RSI(price[index].shift(-1), RSI_Duration) rsi = pd.DataFrame(rsi) #%% 分配仓位 # 总共买3个标的