def equal_rebalancing(self): self.invest_amount_calculation() self.equal_df = pd.DataFrame() number_of_stocks = len(self.new_df.index) invest_amount_per_stock = self.invest_amount/number_of_stocks for i, price in enumerate(self.new_df['Current Price']): temp_series = pd.Series([invest_amount_per_stock/price], index=['Equal Rebalance']) temp_series = self.new_df.iloc[i].append(temp_series) self.equal_df = self.equal_df.append(temp_series, ignore_index=True) self.equal_df = self.equal_df[['Symbol', 'Description', 'Sector', 'Quantity', 'Equal Rebalance', 'Cost Basis Per Share', 'Market Cap', 'Current Price', 'P/E Ratio(PER)', 'P/B Ratio(PBR)']] # self.pt.clearData() self.pt = Table(self.display, dataframe=self.equal_df, showtoolbar=False, showstatusbar=False, editable=False, enable_menus=False) options = config.load_options() options = {'rowselectedcolor':None} config.apply_options(options, self.pt) self.pt.show() # Add color to indicate 'add' or 'sub' quantity to user. Green color for add. Red color for Sub. add_mask = self.equal_df['Quantity'] < self.equal_df['Equal Rebalance'] self.pt.setColorByMask('Equal Rebalance', add_mask, '#7FFF00') sub_mask = self.equal_df['Quantity'] > self.equal_df['Equal Rebalance'] self.pt.setColorByMask('Equal Rebalance', sub_mask, '#FF6EB4') # self.pt.redraw() self.pt.autoResizeColumns()
def __init__(self, master, controller): tk.Frame.__init__(self, master, borderwidth=10, bg="#363636") self.table = pandastable.Table(self, dataframe=df, height=550, columns=4) self.table.grid() options = {'align': 'c', 'cellbackgr': '#303030', 'cellwidth': 200, 'colheadercolor': '#393939', 'entrybackgr': '#393939', 'floatprecision': 6, 'font': 'Consolas', 'fontsize': 12, 'grid_color': '#ABB1AD', 'linewidth': 1, 'rowheight': 22, 'rowselectedcolor': '#555555', 'textcolor': '#AAAAAA' } config.apply_options(options, self.table) # self.table.autoResizeColumns() self.table.show() button_table_graph = tk.Button(self, text="Grafički prikaz", font=MED_FONT, bg="#363636", fg="#18d9cc", command=lambda: controller.show_frame(GraphPage)) button_table_graph.grid(row=3, column=0, ipadx=10, ipady=5, padx=50, pady=20) button_table_convert = tk.Button(self, text="Konverter valuta", font=MED_FONT, bg="#363636", fg="#18d9cc", command=lambda: controller.show_frame(ConvertPage)) button_table_convert.grid(row=3, column=3, ipadx=10, ipady=5, padx=50, pady=20) self.grid_rowconfigure(3, weight=1) self.listenerT = self.after(refresh_rate, self.update_after)
def allYearsGDPPrediction(countries, predictionYear): df = pd.DataFrame(columns=[ 'Countries', 'GDP in 2015', 'Predicted GDP in ' + str(predictionYear) ]) for i in countries: if dataframeCreation(i) is False: print(i + "'s dataframe is empty!") df = df.append(pd.Series([i, 'No Data To Make Prediction'], index=df.columns), ignore_index=True) else: pred1 = linearReg2(i, 2015, dataframeCreation(i))[1][0][0] pred2 = linearReg2(i, predictionYear, dataframeCreation(i))[1][0][0] df = df.append(pd.Series([i, pred1, pred2], index=df.columns), ignore_index=True) df.index += 1 window = tk.Toplevel() window.title("All Countries' GDP Prediction in the year: %s" % predictionYear) f = Frame(window) f.pack(fill=BOTH, expand=1) pt = Table(f, dataframe=df, showstatusbar=True, width=200, height=300) options = {'cellwidth': 150, 'floatprecision': 4, 'align': 'center'} config.apply_options(options, pt) pt.showIndex() pt.show() return df
def __init__(self, master): super(DTable, self).__init__(master) self.mystyle = ttk.Style() self.mystyle.configure("Vertical.TScrollbar", troughcolor='black', background='black', bordercolor="black") self.mystyle.configure("Horizontal.TScrollbar", troughcolor='black', background='black', bordercolor="black") apply_options(options, self)
def displayCorrTable(dict, userSelection): corrDict = dict df = pd.DataFrame(data=corrDict, index=[0]).T df.columns = ['Correlation Value'] window = tk.Toplevel() window.title('%s - GDP Factors correlation values' % userSelection) f = Frame(window) f.pack(fill=BOTH, expand=1) pt = Table(f, dataframe=df, showstatusbar=True, width=200, height=300) options = {'cellwidth': 150, 'floatprecision': 4, 'align': 'center'} config.apply_options(options, pt) pt.showIndex() pt.show()
def update_data(self): self.load_market_data() for i, symbol in enumerate(self.df['Symbol']): # Variable for display status of Progressive Bar self.p_var.set(100/len(self.df.index)*(i+1)) self.progressbar.update() if symbol in self.tickers['Symbol'].values: # Loading live market data from yahoo finance data_from_yahoo = get_quote_data(symbol) # print(data_from_yahoo.keys()) temp = pd.Series( {'Symbol': symbol, 'Description': self.tickers.loc[self.tickers['Symbol'] == symbol]['Security'].item().strip(), 'Sector': self.tickers.loc[self.tickers['Symbol'] == symbol]['GICS Sector'].item().strip(), 'Cost Basis Per Share': self.df.loc[self.df['Symbol'] == symbol]['Cost Basis Per Share'].item().strip(), 'Quantity': self.df.loc[self.df['Symbol'] == symbol]['Quantity'].item(), 'Market Cap': data_from_yahoo['marketCap'], 'Current Price': data_from_yahoo['regularMarketPrice'], 'P/E Ratio(PER)': data_from_yahoo['trailingPE'] if 'trailingPE' in data_from_yahoo.keys() else None, 'P/B Ratio(PBR)': data_from_yahoo['priceToBook'] if 'priceToBook' in data_from_yahoo.keys() else None} ) self.new_df = self.new_df.append(temp, ignore_index=True) # print("Loading is completed") # Reorder Columns self.new_df = self.new_df[['Symbol', 'Description', 'Sector', 'Quantity', 'Cost Basis Per Share', 'Market Cap', 'Current Price', 'P/E Ratio(PER)', 'P/B Ratio(PBR)']] # first_column = self.new_df.pop('Symbol') # self.new_df.insert(0, 'Symbol', first_column) # self.pt.destroy() # self.pt.clearData() self.invested_temp_sum = 0 for i in range(len(self.new_df)): self.invested_temp_sum += self.new_df['Quantity'][i] * self.new_df['Current Price'][i] self.invested_temp_sum = round(self.invested_temp_sum, 3) self.invested_value.set(str(self.invested_temp_sum)) self.pt = Table(self.display, dataframe=self.new_df, showtoolbar=False, showstatusbar=False, editable=False, enable_menus=False) options = config.load_options() options = {'rowselectedcolor':None} config.apply_options(options, self.pt) self.pt.show() self.pt.autoResizeColumns() # self.pt.redraw() # Update menu status self.menu.entryconfig("Strategies", state="normal") # self.menu_file.entryconfig("Save to Excel", state="normal") self.button_rebalancing.config(state="normal")
def displayFactor(country, dataframe, factor): countryName = country df = dataframe if df is False: tk.messagebox.showinfo("Error", "Insufficient data") else: dfFactor = df[factor] df = pd.concat([dfFactor], axis=1) window = tk.Toplevel() window.title(countryName + " - " + factor + ' Data') f = Frame(window) f.pack(fill=BOTH, expand=1) pt = Table(f, dataframe=df, showstatusbar=True, width=200, height=300) options = {'cellwidth': 150, 'floatprecision': 4, 'align': 'center'} config.apply_options(options, pt) pt.showIndex() pt.show()
def display_all(user_input): """ :param user_input: Fetch year value from user input Generate DataFrame based on factor value and plot accordingly """ new_df = trim_column(df, user_input) new_df.drop(['Series Name', 'Series Code', 'Country Code'], axis=1, inplace=True) new_df.reset_index(drop=True, inplace=True) window = tk.Toplevel() window.title('GPD For All Countries In ' + user_input) window.geometry("500x700") f = Frame(window) f.pack(fill=BOTH, expand=1) pt = Table(f, dataframe=new_df, showstatusbar=True, width=200, height=300) options = {'cellwidth': 150, 'floatprecision': 4, 'align': 'center'} config.apply_options(options, pt) pt.showIndex() pt.show()
def load_user_data(self): _file = filedialog.askopenfilename(title="Choose csv file...", \ filetypes=(("csv", "*.csv"),("All", "*.*")), initialdir=r"C:\Users\baekh\OneDrive\Desktop\Python") try: self.df = pd.read_csv(_file, index_col=False) self.df = self.df.drop(columns=['Account Name/Number']) self.df = self.df.rename(columns={"Current Value":"Current Price"}) # Keep only first row if there is duplications # self.df.drop_duplicates(subset=['Symbol'], inplace=True) # self.df = self.df.head() self.pt = Table(self.display, dataframe=self.df, showtoolbar=False, showstatusbar=False, editable=False, enable_menus=False) options = config.load_options() options = {'rowselectedcolor':None} config.apply_options(options, self.pt) self.pt.show() self.pt.autoResizeColumns() # self.pt.redraw() # Update Menu status self.menu_file.entryconfig("Update Market Values", state="normal") except: pass
def market_cap_rebalancing(self): self.invest_amount_calculation() self.cap_df = pd.DataFrame() total_market_cap = self.new_df['Market Cap'].sum() for i, cap in enumerate(self.new_df['Market Cap']): temp_series = pd.Series([self.invest_amount*cap/total_market_cap/self.new_df['Current Price'][i]], index=['Cap Rebalance']) temp_series = self.new_df.iloc[i].append(temp_series) self.cap_df = self.cap_df.append(temp_series, ignore_index=True) self.cap_df = self.cap_df[['Symbol', 'Description', 'Sector', 'Quantity', 'Cap Rebalance', 'Cost Basis Per Share', 'Market Cap', 'Current Price', 'P/E Ratio(PER)', 'P/B Ratio(PBR)']] self.pt = Table(self.display, dataframe=self.cap_df, showtoolbar=False, showstatusbar=False, editable=False, enable_menus=False) options = config.load_options() options = {'rowselectedcolor':None} config.apply_options(options, self.pt) self.pt.show() # Add color to indicate 'add' or 'sub' quantity to user. Green color for add. Red color for Sub. add_mask = self.cap_df['Quantity'] < self.cap_df['Cap Rebalance'] self.pt.setColorByMask('Cap Rebalance', add_mask, '#7FFF00') sub_mask = self.cap_df['Quantity'] > self.cap_df['Cap Rebalance'] self.pt.setColorByMask('Cap Rebalance', sub_mask, '#FF6EB4') # print(total_market_cap) self.pt.autoResizeColumns()
def readData_createWindow(self): try: filename = filedialog.askopenfilename() f = open(filename, "rb") self.set_header(self.header_bool) # f = 'http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' header = self.header_bool.get() == 1 self.data = pd.read_csv(f, header=0 if header else None, sep=',') if not header: self.data.columns = [ 'var' + str(i) for i in range(len(self.data.columns)) ] except AttributeError: pass except Exception as e: return showerror("Error", "Data could not be loaded! Make sure the data is " \ + "formated in a similar way as the sample data: {}.".format(e)) self.cols = self.data.columns self.setUpData() self.bools = [ ] # variables for columns: first axis: which col; second axis: what type height = min(5, self.data.shape[0]) width = len(self.cols) # data frame data_frame = LabelFrame(self.master, text="Data Summary", relief=RIDGE) data_frame.grid(row=0, column=0, columnspan=5, sticky="EWNS", padx=15, pady=7.5) data_size = "Data size is {} kilobytes. " \ .format(np.round(self.data.memory_usage(deep=False).sum() / 1000, 2)) cols_rows = "The number of columns is {} and the number of rows is {}. " \ .format(self.data.shape[1], self.data.shape[0]) miss_data = "The data does have missing values." if self.data.isnull().values.any() \ else "The data does not have missing values." Message(data_frame, text=data_size + cols_rows + miss_data, width=335) \ .grid(row=0, column=0, columnspan=width-1, rowspan=3, sticky='NW') Button(data_frame, text="Data", width=13, command=self.show_data) \ .grid(row=0, column=4, columnspan=1, padx=4, pady=4) Button(data_frame, text="Description", width=13, command=self.show_description) \ .grid(row=1, column=4, columnspan=1, padx=4, pady=0) Button(data_frame, text="Pair Plot", width=13, command=self.pair_plot) \ .grid(row=2, column=4, columnspan=1, padx=4, pady=4) # head frame head_frame = LabelFrame(self.master, text="Head of data", relief=RIDGE) head_frame.grid(row=5, column=0, columnspan=5, sticky="EWNS", padx=15, pady=7.5) for i in range(len(self.cols)): self.bools.append( self.initBools(5, trues=[0, 3] if i < width - 1 else [1, 3])) table = CustomTable(main_window=self, parent=head_frame, dataframe=self.data.head(), editable=False, width=1, height=120) config.apply_options({'fontsize': 10}, table) table.show() # modeling frame model_frame = LabelFrame(self.master, text="Modeling", relief=RIDGE) model_frame.grid(row=height + 11, column=0, columnspan=5, sticky="EWNS", padx=15, pady=7.5) # train / test ratio self.train_test_ratio = 1 / 3 self.train_test_ratio_str = StringVar( self.master, value=str(np.round(self.train_test_ratio, 2))) Button(model_frame, text="Shuffle Data", width=13, command=self.shuffle_data) \ .grid(row=0, column=0, columnspan=1) Button(model_frame, text="TrainTest Ratio", width=13, command=self.set_traintest) \ .grid(row=0, column=2, columnspan=1) Label(model_frame, textvariable=self.train_test_ratio_str) \ .grid(row=0, column=3, columnspan=1, sticky="E") # model selection ttk.Style().configure("TMenubutton", background="#E1E1E1") self.model_btn = Menubutton(model_frame, text="Model", width=9) self.set_model(self.model_btn) self.model_btn.grid(row=1, column=0, columnspan=1, padx=0, pady=4) Button(model_frame, text="Parameters", width=13, command=self.set_model_parameters) \ .grid(row=1, column=1, columnspan=1, padx=0, pady=4) self.metric_btn = Menubutton(model_frame, text="Metric", width=9) self.set_metric(self.metric_btn) self.metric_btn.grid(row=1, column=2, columnspan=1, padx=0, pady=4) # model training self.score = -1 self.score_str = StringVar(self.master, value="") Button(model_frame, text="Train Model", width=13, command=self.startModel) \ .grid(row=1, column=3, columnspan=width-1) Label(model_frame, textvariable=self.score_str) \ .grid(row=3, columnspan=width, sticky='W') # Export Frame export_frame = LabelFrame(self.master, text="Save", relief=RIDGE) export_frame.grid(row=height + 15, column=0, columnspan=5, sticky="EWNS", padx=15, pady=7.5) Button(export_frame, text="Export Data", width=13, command=self.export_data) \ .grid(row=0, column=0, columnspan=1, padx=4, pady=4) Button(export_frame, text="Export Model", width=13, command=self.export_model) \ .grid(row=0, column=1, columnspan=1, padx=0, pady=4)