Created
December 13, 2020 09:49
-
-
Save audhiaprilliant/430b4061290e4132bb1bc49496082589 to your computer and use it in GitHub Desktop.
Concave Function to Interpolate Stocks Data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Function to input NA in column date | |
| def imput_date(df:pd.DataFrame,col:'Date'): | |
| start = datetime.datetime.strptime(df.loc[0,col],'%Y-%m-%d') | |
| end = datetime.datetime.strptime(df.loc[df.shape[0] - 1,col],'%Y-%m-%d') | |
| list_date = pd.date_range(start,end).strftime('%Y-%m-%d').tolist() | |
| pd_date = pd.DataFrame(df,list_date) | |
| pd_date[col] = pd_date.index.astype(object) | |
| pd_date = pd_date.reset_index(drop=True) | |
| df_date = pd.merge(pd_date[col],df,on=col,how='left') | |
| return df_date | |
| # Function to calculate return of stocks | |
| def return_stocks(df:pd.DataFrame,col:'Adj Close',date:'Date'): | |
| df_no_na = df.dropna().reset_index(drop=True) | |
| return_data = [0] | |
| index_data = list(df_no_na.index) | |
| for i in range(1,len(index_data)): | |
| return_i = (df_no_na[col][index_data[i]] - | |
| df_no_na[col][index_data[i-1]])/df_no_na[col][index_data[i]] | |
| return_data.append(return_i) | |
| df_no_na = pd.concat([df_no_na[date],pd.DataFrame(return_data)],axis=1) | |
| df_full = pd.merge(df,df_no_na,on=date,how='left') | |
| df_full = df_full.rename(columns = {0:'Return'}) | |
| return df_full | |
| # Curve function | |
| def curve_function(df): | |
| for i in df.columns: | |
| while df[i].isna().sum() > 0: | |
| for j in range(df.shape[0]): | |
| if pd.isnull(df.loc[j,i]): | |
| seq_k = [j] | |
| k = j | |
| while pd.isnull(df.loc[k,i]): | |
| k = k + 1 | |
| seq_k.append(k) | |
| if len(seq_k) % 2 == 0: | |
| df.loc[seq_k[int((len(seq_k) - 1)/2)],i] = (df.loc[j - 1,i] + df.loc[seq_k[len(seq_k) - 1],i])/2 | |
| else: | |
| df.loc[seq_k[int((len(seq_k) - 1)/2)],i] = (df.loc[j - 1,i] + df.loc[seq_k[len(seq_k) - 1],i])/2 | |
| else: | |
| df.loc[j,i] = df.loc[j,i] | |
| return(df) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment