def calculate_sma(self, recalculate: bool = False): df = tl.load_csv(self.signal_stocks) if recalculate or 'SMA_' + str(self.sma_period) not in df.keys(): print( f"Calculate SMA for {self.signal_stocks} with {self.sma_period} period" ) df['SMA_' + str(self.sma_period)] = round( df['Close'].rolling(self.sma_period).mean(), 2) tl.save_csv(self.FOLDER_WITH_DATA, self.signal_stocks, df) else: return
def calculate_momentum(self, recalc: bool = False): for ticker in set(self.tickers_for_mom): df = tl.load_csv(ticker) for mom in self.momentums.keys(): if recalc or 'Momentum_' + str(mom) not in df.keys(): print( f"Calculate momentum for {ticker} with {mom} month-period" ) mom_list = [] for day in range(len(df.Date)): if day != len(df) - 1 and df.Date[ day].month != df.Date[day + 1].month: find_month = df.Date[day] - rdelta(months=mom) month_cls = df[ (df.Date.dt.year == find_month.year) & (df.Date.dt.month == find_month.month)].Close if len(month_cls) != 0: mom_list.append(df.Close[day] / month_cls.iloc[-1]) else: mom_list.append(None) elif day != 0 and df.Date[day].month != df.Date[ day - 1].month: find_month = df.Date[day] - rdelta(months=mom) month_opn = df[ (df.Date.dt.year == find_month.year) & (df.Date.dt.month == find_month.month)].Open if len(month_opn) != 0: mom_list.append(df.Open[day] / month_opn.iloc[0]) else: mom_list.append(None) else: mom_list.append(None) else: continue df['Momentum_' + str(mom)] = mom_list tl.save_csv(self.FOLDER_WITH_DATA, ticker, df)
def calculate_momentum(self, asset: str, recalculate: bool = False): if asset == 'stocks': ticker, mom = self.signal_stocks, self.momentum_stocks elif asset == 'bonds': ticker, mom = self.signal_bonds, self.momentum_bonds else: raise ValueError( "Incorrect value for 'asset' in 'calculate_momentum' func") df = tl.load_csv(ticker) if recalculate or 'Momentum_' + str(mom) not in df.keys(): print(f"Calculate momentum for {ticker} with {mom} month-period") mom_list = [] for day in range(len(df.Date)): if day != len(df) - 1 and df.Date[day].month != df.Date[ day + 1].month: find_month = df.Date[day] - rdelta(months=mom) month_cls = df[(df.Date.dt.year == find_month.year) & ( df.Date.dt.month == find_month.month)].Close if len(month_cls) != 0: mom_list.append(df.Close[day] / month_cls.iloc[-1]) else: mom_list.append(None) elif day != 0 and df.Date[day].month != df.Date[day - 1].month: find_month = df.Date[day] - rdelta(months=mom) month_opn = df[(df.Date.dt.year == find_month.year) & (df.Date.dt.month == find_month.month)].Open if len(month_opn) != 0: mom_list.append(df.Open[day] / month_opn.iloc[0]) else: mom_list.append(None) else: mom_list.append(None) else: return df['Momentum_' + str(mom)] = mom_list tl.save_csv(self.FOLDER_WITH_DATA, ticker, df)
'(' + f"Period_Range {test_port.vol_calc_period} {test_port.vol_calc_range}" + ') ' + \ '(' + f"Type_Leverage {test_port.vola_type} {test_port.use_margin}" + ') ' return df_strategy, df_yield_by_years, chart_name if __name__ == "__main__": portfolios = {'risk_on': {'QQQ': 1.0}, 'risk_off': {'IEF': 1.0}} test_port = TargetVolatility(portfolios=portfolios, date_start=datetime(1915, 1, 1), benchmark='QQQ', vol_target=6.0, rebalance='monthly', vol_calc_period='month', vol_calc_range=1) df_strategy, df_yield_by_years, chart_name = start(test_port) tl.plot_capital_plotly(test_port.FOLDER_WITH_IMG + chart_name, list(df_strategy.Date), list(df_strategy.Capital), df_yield_by_years, portfolios) tl.save_csv(test_port.FOLDER_TO_SAVE, chart_name + str(test_port.ports_tickers()), df_strategy) # portfolios = {'risk_on': # {'DJIndex': 1.0}, # 'risk_off': # {'Treasures': 1.0} # }
both_strategies_df = df_strategy_vol.merge(df_strategy_mom, left_on='Date', right_on='Date') both_strategies_df['Capital'] = both_strategies_df[ 'Capital_x'] + both_strategies_df['Capital_y'] df_yield_by_years = core_port.df_yield_std_by_every_year( both_strategies_df) chart_name = 'CoreSattelitePort ' + \ '(' + rebalance + ') ' + \ '(' + 'by ' + trade_rebalance_at + ') ' + \ '(' + f"VolTarget {core_port.vol_target}" + ') ' + \ '(' + f"Period_Range {core_port.vol_calc_period} {core_port.vol_calc_range}" + ') ' + \ '(' + f"Mom {satelt_port.momentum_stocks} {satelt_port.momentum_bonds}" + ') ' + \ '(' + f"SMA {satelt_port.sma_period}" + ') ' tl.plot_capital_plotly(core_port.FOLDER_WITH_IMG + chart_name, list(both_strategies_df.Date), list(both_strategies_df.Capital), df_yield_by_years, { **core_ports, **satelt_ports }) tl.save_csv(core_port.FOLDER_TO_SAVE, chart_name, both_strategies_df) # make_charts_for_site() # make_json_for_site()
from datetime import datetime from libs import trading_lib as tl import pandas as pd import SMA_and_Mom port = {'high_risk': {'VFINX': .5, 'VEIEX': .5} } port_class = SMA_and_Mom.SMAandMomentum(portfolios=port, date_start=datetime(1980, 1, 1), signal_stocks='VFINX', signal_bonds='VEIEX', benchmark='VFINX') port_class.download_data() start_date, end_date = port_class.find_oldest_newest_dates() port_class.cut_data_by_dates(start_date, end_date) port_class.all_tickers_data['VFINX_VEIEX'] = {} port_class.all_tickers_data['VFINX_VEIEX']['Date'] = port_class.all_tickers_data['VFINX']['Date'] port_class.all_tickers_data['VFINX_VEIEX']['Close'] = \ port_class.all_tickers_data['VFINX']['Close'] / port_class.all_tickers_data['VEIEX']['Close'] sma = port_class.all_tickers_data['VFINX_VEIEX']['Close'] port_class.all_tickers_data['VFINX_VEIEX']['SMA_200'] = round(sma.rolling(200).mean(), 2) df = pd.DataFrame.from_dict(port_class.all_tickers_data['VFINX_VEIEX']) tl.save_csv(port_class.FOLDER_WITH_DATA, 'VFINX_VEIEX', df)