def analysis_stocks_RTS(start_date, end_date, margin=50, factor=0.325, investment_size=200): df_result = pd.read_csv('dataRTS.csv', index_col='Ticker') df_result = df_result.sort_index() symbols = df_result.index dates = pd.date_range(start_date, end_date) # date range as index df_data = get_data_us(symbols, dates, benchmark=None) # get data for each symbol # Fill missing values fill_missing_values(df_data) # return prices # df_result['Commision'] = prices['Commision'] df_result['Spread'] = df_result['Spread'] * factor df_result['Close'] = df_data[symbols].iloc[-1, :].values df_result['MinNbStock'] = df_result['Lot'] * 0.01 df_result['PriceStockMarg'] = df_result['MinNbStock'] * df_result[ 'Close'] / margin df_result['NbMaxVol'] = round( investment_size / df_result['PriceStockMarg'], 0) df_result['MaxVolLot'] = round( investment_size / df_result['PriceStockMarg'] * 0.01, 2) df_result['CommMin'] = ( df_result['Spread'] - df_result['Buy'] - df_result['Sell']) / df_result['Lot'] * df_result['MinNbStock'] df_result['Comm_Trade'] = ( df_result['Spread'] - df_result['Buy'] - df_result['Sell']) / df_result['Lot'] * df_result['NbMaxVol'] df_result['Comm_Price'] = round( df_result['CommMin'] / df_result['MinNbStock'] / df_result['Close'].values * 100, 3) df_result['Comm_Invest'] = round( df_result['Comm_Trade'] / investment_size * 100, 3) 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 my_portfolio(start="2018-7-10", end="2018-10-16"): dates = pd.date_range(start, end) symbols = [ 'PHC', 'MBB', 'GEX', 'MBS', 'NDN', 'PNJ', 'STB', 'PVD', 'VRC', 'VIX' ] # symbols = ['PHC','MBB','GEX', 'MBS'] df_data = get_data(symbols, dates, benchmark='^VNINDEX') # get data for each symbol fill_missing_values(df_data) plot_normalized_data(df_data, title=" Daily porfolio value with VNINDEX ", xlabel="Date", ylabel=" Normalized price ")
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
def analysis_market(tickers, start, end, update=False, market="^VNINDEX", source="cp68"): if tickers == None: tickers = getliststocks(typestock=market) if update: end_date = datetime.datetime.today() dates = pd.date_range(start, end_date) # date range as index df_data = pd.DataFrame(index=dates) df_volume = pd.DataFrame(index=dates) else: dates = pd.date_range(start, end) # date range as index df_data = pd.DataFrame(index=dates) df_volume = pd.DataFrame(index=dates) for ticker in tickers: # print(" Analysing ..." , ticker) # try: # df = process_data(ticker=ticker, start=start, end=end, realtime=update, source=source) # print(df_temp.head()) df_data = df_data.join(df['Close']) df_data = df_data.rename(columns={'Close': ticker}) df_volume = df_volume.join(df['Volume']) df_volume = df_volume.rename(columns={'Volume': ticker}) # except Exception as e: # print (e) # print("Error in reading symbol: ", ticker) # pass fill_missing_values(df_data) fill_missing_values(df_volume) marketVNI = df_data[tickers].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[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 return df_market
def passive_strategy(start_date, end_date, market=None, symbols=None, realtime=True, source='yahoo'): if symbols == None: symbols = getliststocks(typestock=market) if realtime: end_date = datetime.datetime.today() dates = pd.date_range(start_date, end_date) # date range as index df_data = get_data(symbols, dates, benchmark=market, colname='Adj Close', realtime=realtime, source=source) # get data for each symbol # Fill missing values fill_missing_values(df_data) df_volume = get_data(symbols, dates, benchmark=market, colname='Volume', realtime=realtime, source=source) # get data for each symbol df_rsi = get_RSI(symbols, df_data) df_volume = df_volume.fillna(0) df_result = pd.DataFrame(index=symbols) df_result['Ticker'] = symbols df_result['Close'] = df_data[symbols].iloc[-1, :].values df_result['PCT_C'] = 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_volume[symbols].iloc[-2, :].values df_result['Value'] = df_result['Close'] * df_result['Volume'] df_result['Volatility'] = df_data[symbols].pct_change().std() df_result['PCT_3D'] = df_data[symbols].pct_change().iloc[ -4, :].values * 100 df_result['PCT_2D'] = df_data[symbols].pct_change().iloc[ -3, :].values * 100 df_result['PCT_1D'] = df_data[symbols].pct_change().iloc[ -2, :].values * 100 df_result['PCT_0D'] = df_data[symbols].pct_change().iloc[ -1, :].values * 100 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 df_result['RSI'] = df_rsi[symbols].iloc[-1, :].values return df_result, df_data