def rebalancing_porfolio(symbols=None, bench='^VNINDEX'): start0 = "2015-1-2" end0 = "2017-1-2" allocations, cr, adr, sddr, sr = optimize_portfolio(sd=start0, ed=end0, syms=symbols, benchmark=bench, gen_plot=True) print("Optimize start Date:", start0) print("Optimize end Date:", end0) print("Optimize volatility (stdev of daily returns):", sddr) print("Optimize average Daily Return:", adr) print("Optimize cumulative Return:", cr) print(" -----------------------------------------------------") start_date_list = ["2017-1-3", "2017-7-3"] end_date_list = ["2017-7-2", "2018-4-1"] for start, end in zip(start_date_list, end_date_list): cr, adr, sddr, sr = compute_portfolio(sd=start, ed=end, syms=symbols, allocs=allocations, benchmark=bench, gen_plot=True) print("Start Date:", start) print("End Date:", end) print("Volatility (stdev of daily returns):", sddr) print("Average Daily Return:", adr) print("Cumulative Return:", cr) print(" -----------------------------------------------------") allocations, cr, adr, sddr, sr = optimize_portfolio(sd=start, ed=end, syms=symbols, benchmark=bench, gen_plot=False) print("Optimize volatility (stdev of daily returns):", sddr) print("Optimize average Daily Return:", adr) print("Optimize cumulative Return:", cr) print(" -----------------------------------------------------") # Out of sample testing optimisation algorithm end_date = "2018-9-27" start_date = "2018-4-2" cr, adr, sddr, sr = compute_portfolio(sd=start_date, ed=end_date, syms=symbols, allocs=allocations, benchmark=bench, gen_plot=True) print( "....................... Out of sample performance .................") print("Start Date:", start_date) print("End Date:", end_date) print("Volatility (stdev of daily returns):", sddr) print("Average Daily Return:", adr) print("Cumulative Return:", cr) # Assess the portfolio investment = 60E6 df_result = pd.DataFrame(index=symbols) df_result['Opt allocs'] = allocations df_result['Cash'] = allocations * investment dates = pd.date_range(start_date, end_date) # date range as index df_data = get_data(symbols, dates, benchmark=bench) # get data for each symbol df_high = get_data(symbols, dates, benchmark=bench, colname='<High>') df_low = get_data(symbols, dates, benchmark=bench, colname='<Low>') max_high = pd.Series(df_high.max(), name='MaxHigh') min_low = pd.Series(df_low.min(), name='MinLow') cpm = pd.Series(max_high / min_low, name='CPM') volatility = df_data[symbols].pct_change().std() # Fill missing values df_result['Close'] = df_data[symbols].iloc[-1, :].values df_result['CPM'] = cpm[symbols] df_result['Shares'] = round( df_result['Cash'] / df_result['Close'].values / 1000, 0) df_result['Volatility'] = volatility alpha_beta = analysis_alpha_beta(df_data, symbols, market=bench) df_result['Alpha'] = alpha_beta['Alpha'] df_result['Beta'] = alpha_beta['Beta'] relative_strength = 40*df_data[symbols].pct_change(periods = 63).fillna(0) \ + 20*df_data[symbols].pct_change(periods = 126).fillna(0) \ + 20*df_data[symbols].pct_change(periods = 189).fillna(0) \ + 20*df_data[symbols].pct_change(periods = 252).fillna(0) df_result['RSW'] = relative_strength.iloc[-1, :].values return df_result
def passive_strategy(start_date, end_date, market="SPY"): symbols = getliststocks(typestock=market) dates = pd.date_range(start_date, end_date) # date range as index df_data = get_data_us(symbols, dates, benchmark=market) # get data for each symbol df_volume = get_data_us(symbols, dates, benchmark=market, colname='Volume') # get data for each symbol df_high = get_data_us(symbols, dates, benchmark=market, colname='High') df_low = get_data_us(symbols, dates, benchmark=market, colname='Low') df_value = (df_volume * df_data).fillna(0) valueM30 = df_value.rolling(window=30).mean() vol_mean = pd.Series(df_volume.mean(), name='Volume') max_high = pd.Series(df_high.max(), name='MaxHigh') min_low = pd.Series(df_low.min(), name='MinLow') cpm = pd.Series(max_high / min_low, name='CPM') value_mean = pd.Series(df_value.mean(), name='Value') # Fill missing values fill_missing_values(df_data) # Assess the portfolio allocations, cr, adr, sddr, sr = optimize_portfolio(sd=start_date, ed=end_date, syms=symbols, benchmark=market, country='US', gen_plot=True) # Print statistics print("Start Date:", start_date) print("End Date:", end_date) print("Symbols:", symbols) print("Optimal allocations:", allocations) print("Sharpe Ratio:", sr) print("Volatility (stdev of daily returns):", sddr) print("Average Daily Return:", adr) print("Cumulative Return:", cr) investment = 50000000 df_result = pd.DataFrame(index=symbols) df_result['Opt allocs'] = allocations df_result['Cash'] = allocations * investment df_result['Close'] = df_data[symbols].iloc[-1, :].values df_result['Volume'] = df_volume[symbols].iloc[-1, :].values df_result['VolumeMean'] = vol_mean[symbols] df_result['Value'] = df_result['Close'] * df_result['Volume'] df_result['ValueMean'] = value_mean[symbols] df_result['ValueMA30'] = valueM30[symbols].iloc[-1, :].values # df_result['MaxH'] = max_high # df_result['MinL'] = min_low df_result['CPM'] = cpm[symbols] df_result['Shares'] = round( df_result['Cash'] / df_result['Close'].values / 1000, 0) df_result['Volatility'] = df_data[symbols].pct_change().std() alpha_beta = analysis_alpha_beta(df_data, symbols, market) df_result['Alpha'] = alpha_beta['Alpha'] df_result['Beta'] = alpha_beta['Beta'] relative_strength = 40*df_data[symbols].pct_change(periods = 63).fillna(0) \ + 20*df_data[symbols].pct_change(periods = 126).fillna(0) \ + 20*df_data[symbols].pct_change(periods = 189).fillna(0) \ + 20*df_data[symbols].pct_change(periods = 252).fillna(0) df_result['RSW'] = relative_strength.iloc[-1, :].values return df_result, df_data
def passive_strategy(start_date, end_date, market="^VNINDEX", symbols=None): if symbols == None: symbols = getliststocks(typestock=market) dates = pd.date_range(start_date, end_date) # date range as index df_data = get_data(symbols, dates, benchmark=market) # get data for each symbol df_volume = get_data(symbols, dates, benchmark=market, colname='<Volume>') # get data for each symbol df_high = get_data(symbols, dates, benchmark=market, colname='<High>') df_low = get_data(symbols, dates, benchmark=market, colname='<Low>') # covariance = numpy.cov(asset , SPY)[0][1] # variance = numpy.var(asset) # # beta = covariance / variance df_volume = df_volume.fillna(0) df_value = (df_volume * df_data).fillna(0) valueM30 = df_value.rolling(window=30).mean() vol_mean = pd.Series(df_volume.mean(), name='Volume') max_high = pd.Series(df_high.max(), name='MaxHigh') min_low = pd.Series(df_low.min(), name='MinLow') cpm = pd.Series(max_high / min_low, name='CPM') value_mean = pd.Series(df_value.mean(), name='ValueMean') # Fill missing values fill_missing_values(df_data) # Assess the portfolio allocations, cr, adr, sddr, sr = optimize_portfolio(sd=start_date, ed=end_date, syms=symbols, benchmark=market, gen_plot=True) # Print statistics print("Start Date:", start_date) print("End Date:", end_date) print("Symbols:", symbols) print("Optimal allocations:", allocations) print("Sharpe Ratio:", sr) print("Volatility (stdev of daily returns):", sddr) print("Average Daily Return:", adr) print("Cumulative Return:", cr) investment = 50000000 df_result = pd.DataFrame(index=symbols) df_result['Opt allocs'] = allocations df_result['Cash'] = allocations * investment df_result['Close'] = df_data[symbols].iloc[-1, :].values df_result['PCT_Change'] = 100 * (df_data[symbols].iloc[-1, :].values - df_data[symbols].iloc[0, :].values ) / df_data[symbols].iloc[0, :].values df_result['Volume'] = df_volume[symbols].iloc[-1, :].values df_result['VolumeMean'] = vol_mean[symbols] df_result['Value'] = df_result['Close'] * df_result['Volume'] df_result['ValueMean'] = value_mean[symbols] df_result['ValueMA30'] = valueM30[symbols].iloc[-1, :].values # df_result['MaxH'] = max_high # df_result['MinL'] = min_low df_result['CPM'] = cpm[symbols] df_result['Shares'] = round( df_result['Cash'] / df_result['Close'].values / 1000, 0) df_result['Volatility'] = df_data[symbols].pct_change().std() df_result['PCT_Change0D'] = df_data[symbols].pct_change().iloc[ -1, :].values * 100 df_result['PCT_Change1D'] = df_data[symbols].pct_change().iloc[ -2, :].values * 100 df_result['PCT_Change2D'] = df_data[symbols].pct_change().iloc[ -3, :].values * 100 alpha_beta = analysis_alpha_beta(df_data, symbols, market) df_result['Alpha'] = alpha_beta['Alpha'] df_result['Beta'] = alpha_beta['Beta'] relative_strength = 40*df_data[symbols].pct_change(periods = 63).fillna(0) \ + 20*df_data[symbols].pct_change(periods = 126).fillna(0) \ + 20*df_data[symbols].pct_change(periods = 189).fillna(0) \ + 20*df_data[symbols].pct_change(periods = 252).fillna(0) relative_strength1M = 100 * df_data[symbols].pct_change( periods=21).fillna(0) relative_strength2M = 100 * df_data[symbols].pct_change( periods=42).fillna(0) df_result['RSW'] = relative_strength.iloc[-1, :].values df_result['RSW1M'] = relative_strength1M.iloc[-1, :].values df_result['RSW2M'] = relative_strength2M.iloc[-1, :].values marketVNI = df_data[symbols].pct_change() advances = marketVNI[marketVNI > 0] declines = marketVNI[marketVNI <= 0] dec = advances.isnull().sum(axis=1) adv = declines.isnull().sum(axis=1) df_market = pd.DataFrame(index=marketVNI.index) df_market[market + 'Volume'] = df_volume[market] df_market[market + 'PCT_Volume'] = df_volume[market].pct_change() * 100 df_market[market + 'PCT_Index'] = df_data[market].pct_change() * 100 # df_market['Adv'] = adv # df_market['Dec'] = dec df_market[market + 'Adv_Dec'] = adv - dec df_market[market + 'Dec/Adv'] = dec / adv strength = pd.Series(index=marketVNI.index) strength[(df_market[market + 'Adv_Dec'] > 0) & (df_market[market + 'PCT_Index'] > 0)] = 1 strength[(df_market[market + 'Adv_Dec'] < 0) & (df_market[market + 'PCT_Index'] < 0)] = -1 strength[(df_market[market + 'Adv_Dec'] < 0) & (df_market[market + 'PCT_Index'] > 0)] = 0 df_market[market + 'Strength'] = strength # np.where((df_data[symbols].pct_change() > 0), 1, -1) return df_result, df_data, df_market