示例#1
0
    def var_3d_surface(self):
        # iteration for only working date in range of start and end date
        holidays_PL = holidays.PL()
        start_dt = pd.to_datetime(self.start_date).date()
        end_dt = pd.to_datetime(self.end_date).date()
        date_lst = []
        var_3d_frame = pd.DataFrame(columns=[f'{n + 1}_day' for n in range(self.number_days_var)])
        for i in range(int((end_dt - start_dt).days) + 1):
            bd = start_dt + datetime.timedelta(i)
            if bd in holidays_PL or bd.weekday() > 4:
                continue
            date_lst.append(bd)
        # var_3d_frame['date'] = pd.to_datetime(date_lst)
        # var_3d_frame.set_index('date', inplace=True)
        # print(var_3d_frame)
        capital = []
        df_dict = {}
        for x in date_lst:
            reload = RiskAnalysis(start_date=self.start_date, end_date=self.end_date,
                                  eval_date=str(x), number_days_var=self.number_days_var, show_plot=False)

            df_dict[x] = reload.n_day_var()
            capital.append(reload.df_pf.value_now.sum())
        var_3d_frame = pd.DataFrame.from_dict(df_dict, orient='index', columns=var_3d_frame.columns)
        fig = go.Figure(data=[go.Surface(z=var_3d_frame.values)])
        fig.update_layout(title='VaR surface', autosize=False, height=800)
        return [var_3d_frame, fig, capital]
def number_of_business_days_without_holidays(date_from: date,
                                             date_to: date) -> int:
    if date_from > date_to:
        raise ValueError('date_from should be earlier than date_to')

    result = 0
    for day in pd.date_range(date_from, date_to):
        if day not in holidays.PL() and not is_weekend(day):
            result += 1
    return result
示例#3
0
 def fit(self):
     start = pd.Timestamp(self.start_day).normalize()
     end = pd.Timestamp(self.end_day).normalize()
     self.df = pd.DataFrame(index=pd.date_range(
         start=start, end=end, freq='1H', normalize=True, closed='left'))
     self.df['holiday'] = self.df.index.to_series().map(
         lambda x: int(x in holidays.PL() or x.weekday() in [5, 6]))
     self.df['peak7'] = self.df.index.to_series().map(
         lambda x: int(x.hour in range(7, 22)))
     self.df['peak5'] = ((self.df['holiday'] == 0) &
                         (self.df['peak7'] == 1)).map(int)
     prediction_day = self.df.index + pd.Timedelta('1 days')
     weekday = prediction_day.weekday
     month = prediction_day.month
     self.df = self.df.assign(weekday=weekday, month=month)
     return self
示例#4
0
 def is_holiday_or_weekend(self):
     return self.date in holidays.PL() or self.is_weekend()
示例#5
0
 def __init__(self) -> None:
     self.holidays_calendar = holidays.PL()
示例#6
0
country_holidays = {
    "CA": holidays.CA(),
    "CO": holidays.CO(),
    "MX": holidays.MX(),
    "US": holidays.US(),
    "NZ": holidays.NZ(),
    "AU": holidays.AU(),
    "DE": holidays.DE(),
    "AT": holidays.AT(),
    "DK": holidays.DK(),
    "UK": holidays.UK(),
    "IE": holidays.IE(),
    "ES": holidays.ES(),
    "CZ": holidays.CZ(),
    "SK": holidays.SK(),
    "PL": holidays.PL(),
    "PT": holidays.PT(),
    "NL": holidays.NL(),
    "NO": holidays.NO(),
    "IT": holidays.IT(),
    "SE": holidays.SE(),
    "JP": holidays.JP(),
    "BE": holidays.BE(),
    "ZA": holidays.ZA(),
    "SI": holidays.SI(),
    "FI": holidays.FI(),
    "CH": holidays.CH()
}


def get_holiday():
示例#7
0
 def setUp(self):
     self.holidays = holidays.PL()
示例#8
0
def pnl_analysis(trade_hist,
                 symbol_tik,
                 start="2020-04-24",
                 end="2020-07-02",
                 show_chart=False,
                 benchmark=False):
    pl_holidays = holidays.PL()
    st = pd.to_datetime(start).date()
    ed = pd.to_datetime(end).date()
    lst_bd = []
    try:
        file_name = 'pf_pnl.csv'
        pkl_check = pd.read_csv(file_name)
        pkl_check['date'] = pd.to_datetime(pkl_check['date'])
        pkl_check['date'] = pkl_check.date.dt.date
        pkl_last_date = pkl_check.date.max()
        if pkl_last_date >= ed:
            start_date_mask = pkl_check.date >= st
            end_date_mask = pkl_check.date <= ed
            df_pnl = pkl_check[start_date_mask & end_date_mask]
            err_param = False
        else:
            err_param = True
    except FileNotFoundError:
        err_param = True
        print(f'No such file, reloading script')

    if err_param:
        for i in range(int((ed - st).days) + 1):
            bd = st + datetime.timedelta(i)
            if bd in pl_holidays or bd.weekday() > 4:
                continue
            lst_bd.append(bd)
        date_lst = []
        pnl_lst = []
        val_open_lst = []
        val_now_lst = []
        for x in lst_bd:
            pf_data = portfolio_preparation(
                data_preparation(trade_hist, symbol_tik, str(x)), symbol_tik,
                str(x))
            pnl_l = pf_data.pnl_live.sum()
            pnl_c = pf_data.pnl_closed.sum()
            val_open = pf_data.value_at_open.sum()
            val_now = pf_data.value_now.sum()
            # print(f'DATE:{x} | PNL TOTAL: {pnl_l + pnl_c:.2f}')
            date_lst.append(pd.to_datetime(x).date())
            pnl_lst.append(pnl_l + pnl_c)
            val_open_lst.append(val_open)
            val_now_lst.append(val_now)
        df_pnl = pd.DataFrame(
            list(zip(date_lst, pnl_lst, val_open_lst, val_now_lst)),
            columns=['date', 'pnl_total', 'val_open_lst', 'val_now_lst'])
        df_pnl.to_csv('pf_pnl.csv', index=False)
    # condition below will modify df_pnl and return dataframe which compare daily return on portfolio and wig20
    if benchmark:
        df_pnl = df_pnl.copy()
        df_pnl['%_change_cumulative'] = ((
            (df_pnl.val_open_lst + df_pnl.pnl_total) / df_pnl.val_open_lst) -
                                         1) * 100
        df_pnl['%_1_day_shift'] = abs(
            df_pnl['%_change_cumulative'].shift(1).fillna(0))
        df_pnl['%_daily_change'] = df_pnl['%_change_cumulative'] - df_pnl[
            '%_1_day_shift']
        benchmark_symbol = 'WIG20'
        benchmark_data = pd.read_csv(f'./mkt_data/{benchmark_symbol}.csv')
        benchmark_data = benchmark_data[['Date', 'Close']]
        # benchmark_data['Date'] = pd.to_datetime(benchmark_data['Date'])
        benchmark_data['Date'] = pd.to_datetime(benchmark_data['Date'])
        benchmark_data['Date'] = benchmark_data.Date.dt.date
        last_date = pd.to_datetime(benchmark_data.iloc[-1, 0])

        if ed > last_date:
            hd.data_download(symbol_tik, end=str(ed))
        benchmark_data = benchmark_data.loc[benchmark_data.Date >= (
            st - datetime.timedelta(1))]
        benchmark_data['1d_shift'] = benchmark_data['Close'].shift(1).fillna(0)
        benchmark_data['%1d_change'] = (
            (benchmark_data['Close'] / benchmark_data['1d_shift']) - 1) * 100
        benchmark_data = benchmark_data.loc[(benchmark_data.Date >= st)
                                            & (benchmark_data.Date <= ed)]
        benchmark_data['%_change_cumulative'] = benchmark_data[
            '%1d_change'].cumsum()
        return [df_pnl, benchmark_data]
    if show_chart:
        plt.plot(df_pnl.date, df_pnl.pnl_total, color='#8f9805')
        plt.show()
    return df_pnl
示例#9
0
 def wrapper():
     date = f()
     pl_holidays = holidays.PL()
     return pl_holidays[
         date] if date in pl_holidays else f"Brak święta w dniu {date}"