コード例 #1
0
    def init_data(self, type):
        """
        Fetch Data
        ----------
        获取收盘数据
        
        Type 0 for "index"; 1 for "stock"

        """
        print("Fetching Historical Data...")
        if type == 1:
            price = get_muti_close_day(self.POOL,
                                       self.START_DATE,
                                       self.END_DATE,
                                       adjust=True)
        elif type == 0:
            price = {}
            for symbol in self.POOL:
                price[symbol] = get_index_day(symbol, self.START_DATE,
                                              self.END_DATE).sclose
            price = pd.DataFrame(price)
        price.fillna(method="ffill", inplace=True)
        print("Historical Data Loaded!")

        self.price = price
        del price
コード例 #2
0
def 获取数据():
    global price
    START_DATE = '2007-02-01'
    END_DATE = datetime.date.today().strftime('%Y-%m-%d')
    print('正在获取数据...自 {} 至 {}'.format(START_DATE, END_DATE))
    price = get_muti_close_day(pool, START_DATE, END_DATE, HK=(underLying=='hsi'))
    price.fillna(method="ffill", inplace=True)
    print("Historical Data Loaded!")
コード例 #3
0
def 获取数据():
    START_DATE = '2007-02-01'
    END_DATE = TODAY
    print('正在获取数据...自 {} 至 {}'.format(START_DATE, END_DATE))
    price = get_muti_close_day(pool,
                               START_DATE,
                               END_DATE,
                               HK=(underLying == 'hsi'))
    priceFill = price.fillna(method="ffill")
    print("Historical Data Loaded!")
    return price, priceFill
コード例 #4
0

dateList = 当月最后一个交易日(data)
Mhigh = pd.DataFrame([row for row in M_high(data)],
                     columns=['date', '600000.SH']).set_index('date')
Mlow = pd.DataFrame([row for row in M_low(data)],
                    columns=['date', '600000.SH']).set_index('date')
M = Mhigh - Mlow
Ret20 = Ret(data, 20)

#factors = pd.concat([Mhigh.set_index('date'), Mlow.set_index('date')],axis=1)

#%% 获取价格数据
price = get_muti_close_day(selection.columns,
                           '2009-03-31',
                           '2018-11-30',
                           freq='M',
                           adjust=-1)  # 回测时还是使用前复权价格
priceFill = price.fillna(method='ffill')
price_change = priceFill.diff()
hs300 = get_index_day('000300.SH', '2009-4-30', '2018-11-30', 'M').sclose
szzz = get_index_day('000001.SH', '2009-4-30', '2018-11-30', 'M').sclose
zz500 = get_index_day('000905.SH', '2009-4-30', '2018-11-30', 'M').sclose
IC = pd.read_hdf("monthlyData-over10B.h5", 'IC')
IF = pd.read_hdf("monthlyData-over10B.h5", 'IF')

#%% 股票选择
isBig = (mv.T > mv.T.quantile(0.8)).T
isSmall = (mv.T < mv.T.quantile(0.3)).T

コード例 #5
0
        	server='192.168.0.28', port=1433,
        	user='******', password='******',
        	database='rawdata', charset='utf8'
        	)
SQL = 'SELECT * FROM dbo.[50成分]'
weight_for_50 = pd.read_sql(SQL, conn, index_col='0')

stock_pool = set(weight_for_50.values[0])

for i in weight_for_50.values:
    stock_pool = stock_pool.intersection(set(i))

print("Phase I : Gathering data")
open_data = rd.get_muti_open_day(stock_pool, "2010-01-01", "2019-01-01")
print("Open data fetched")
close_data = rd.get_muti_close_day(stock_pool, "2010-01-01", "2019-01-01")
print("Close data fetched")
high_data = rd.get_muti_high_day(stock_pool, "2010-01-01", "2019-01-01")
low_data = rd.get_muti_low_day(stock_pool, "2010-01-01", "2019-01-01")
vol_data = rd.get_muti_vol_day(stock_pool, "2010-01-01", "2019-01-01")
print("Phase I : Done ")


close_data = close_data / close_data.iloc[0]
open_data = open_data / open_data.iloc[0]
high_data = high_data / high_data.iloc[0]
low_data = low_data / low_data.iloc[0]
vol_data = vol_data / vol_data.iloc[0]


close_data["benchmark_close"] = close_data.mean(axis=1)
コード例 #6
0
    '000016.SH', '000905.SH', '000009.SH', '000991.SH', '000935.SH',
    '000036.SH'
]
# STOCK_POOL = ['600309.SH', '600585.SH', '000538.SZ', '000651.SZ', '600104.SH','601888.SH']
# STOCK_POOL = ["600104.SH"]
START_DATE = "2008-01-01"
END_DATE = datetime.date.today().strftime('%Y-%m-%d')
INITIAL_CAPITAL = 1000
# CAPITAL = INITIAL_CAPITAL / 3
DURATION = 250
Profit_Ceiling = [0.4, 0.2]  #止盈线
Trailing_Percentage = 0.2  #优先止盈百分比

# %% 获取收盘数据
if TYPE == 1:
    price = get_muti_close_day(STOCK_POOL, START_DATE, END_DATE)
# df = get_index_day('600519.SH',START_DATE,END_DATE)
elif TYPE == 0:
    price = {}
    for symbol in STOCK_POOL:
        price[symbol] = get_index_day(symbol, START_DATE, END_DATE).sclose
    price = pd.DataFrame(price)
price.fillna(method="ffill", inplace=True)
print("Historical Price Loaded!")

# %% 技术指标
price.fillna(value=0, inplace=True)  # 把早年暂未上市的股票价格填充为0
price_diff = price.diff()
price_pct_chg = price.pct_change()

price_std = price.rolling(window=DURATION).std()  # 计算标准差
コード例 #7
0
                           database='RawData')
    SQL = '''SELECT b.code FROM [中证500成分权重] as b
    where b.[Date] BETWEEN '2018-06-21' and '2018-07-03' '''
    zz500 = get_index_day('000905.SH', '2007-02-01',
                          datetime.date.today().strftime('%Y-%m-%d'), '1D')
    zz500 = zz500.sclose

data = pd.read_sql(SQL, conn)
pool = list(data['code'])
del data

# 获取数据,计算RSI
START_DATE = '20070201'
END_DATE = datetime.date.today().strftime('%Y-%m-%d')
print('正在获取数据...')
price = get_muti_close_day(pool, START_DATE, END_DATE)
price.fillna(method="ffill", inplace=True)
print("Historical Data Loaded!")

#%% 仓位计算和优化处理
RSI_arg = 30
RSI = price.apply(getattr(talib, 'RSI'), args=(RSI_arg, ))
RSI = RSI.replace(0, np.nan)
分母 = abs(RSI.T - 50).sum()
RSI_normalized = ((RSI.T - 50) / 分母).T
RSI_normalized.fillna(0, inplace=True)
pos = RSI_normalized[RSI_normalized > 0]
#pos = pos.multiply((RSI_normalized.T.sum().T + 0.3),axis=0)
#pos[pos<0] = 0
#pos[pos.T.sum()>1] /= pos.T.sum()
pos[pos.T.sum() > 0.6] *= 1.1