def __init__(self, username): self.username = username self.watchlist = Watchlist() with open("database/" + username + ".txt", "r") as f: for stock_on_line in f: self.watchlist.addToWatchlist(stock_on_line.strip()) f.close()
def __init__(self): super().__init__() self.build() self.my_watchlist = Watchlist() self.my_watchlist_name = "default_watchlist" self.update_timer = Timer(20, self.timer_cb) self.add_code_input = TextInput() self.add_watchlist_input = TextInput()
def load_watchlist(self, this_watchlist): self.my_watchlist.save_watchlist('{}.csv'.format(self.my_watchlist_name)) self.my_watchlist = Watchlist() try: self.my_watchlist.load_watchlist('{}.csv'.format(this_watchlist.text)) self.my_watchlist_name = this_watchlist.text self.update_list() self.update_statusbar('{} successfully loaded'.format(self.my_watchlist_name)) self.update_timer = Timer(20, self.timer_cb) self.update_timer.start() except: self.update_statusbar('{} failed to load'.format(this_watchlist.text))
def loadSaved(file): lines = file.readlines() if lines != "": wlists = [] wlistnames = [] for line in lines: dict1 = json.loads(line) wlist = Watchlist(dict1['name']) for ticker in dict1['tickers']: wlist.addSavedTicker(ticker['name'], ticker['bought'], ticker['boughtPrice']) wlists.append(wlist) wlistnames.append(dict1['name']) return wlists, wlistnames print("file reading failed")
class Profile: def __init__(self, username): self.username = username self.watchlist = Watchlist() with open("database/" + username + ".txt", "r") as f: for stock_on_line in f: self.watchlist.addToWatchlist(stock_on_line.strip()) f.close() def save(self): f = open("database/" + self.username + ".txt", "w") data = "" for stock in self.watchlist.watchlist: data += stock.ticker + "\n" f.write(data) f.close()
def getStrategy(self, name, settings): """ Get and initialize a strategy given by name. This pulls out a strategy based on the name given or the contents of the settings. It first looks for a \"class\" setting and checks the registry, then uses the \"name\" setting. It initializes the strategy by passing in the settings. It also creates the watchlist to run against based on the \"watchlist\" setting. """ try: strategyClass = settings.get("Strategy", "class") except NoOptionError: strategyClass = None strategyName = settings.get("Strategy", "name") watchlistName = None try: watchlistName = settings.get("Strategy", "watchlist") except NoOptionError: pass print "Strategy Name: %s" % strategyName if watchlistName != None: try: watchlist = watchlistRegistry.get(watchlistName, settings) except KeyError: # list of tickers? symbols = split(watchlistName, ",") watchlist = Watchlist() watchlist.setTickers(symbols) else: watchlist = None tradeManager = TradeManager() strategy = strategyRegistry.get(strategyName, strategyClass, settings, watchlist, tradeManager) fromdatestr = settings.get("Backtest", "fromdate") todatestr = settings.get("Backtest", "todate") fromdt = datetime.datetime.strptime(fromdatestr, '%Y-%m-%d') todt = datetime.datetime.strptime(todatestr, '%Y-%m-%d') stats = strategy.findsetups(fromdt, todt) print stats try: if settings.getboolean("Backtest", "printTrades"): for trade in tradeManager.trades: print trade except NoOptionError: pass return (tradeManager.trades, stats)
portfolioCmd() # graph elif user_input == "4": graphCmd() # login elif user_input == "5": if not logged_in: login() else: logout() # create account elif user_input == "6": createAccount() # exit elif user_input == "exit": exit() # bad input else: print("That is an invalid command.") # This will be edited when profiles are included. user_watchlist = Watchlist() # start application start()
class Stocks(App): def __init__(self): super().__init__() self.build() self.my_watchlist = Watchlist() self.my_watchlist_name = "default_watchlist" self.update_timer = Timer(20, self.timer_cb) self.add_code_input = TextInput() self.add_watchlist_input = TextInput() def build(self): self.title = 'Stock Watcher' self.root = Builder.load_file('app.kv') return self.root def stop(self): self.my_watchlist.save_watchlist('{}.csv'.format(self.my_watchlist_name)) # noinspection PyBroadException def load_watchlist(self, this_watchlist): self.my_watchlist.save_watchlist('{}.csv'.format(self.my_watchlist_name)) self.my_watchlist = Watchlist() try: self.my_watchlist.load_watchlist('{}.csv'.format(this_watchlist.text)) self.my_watchlist_name = this_watchlist.text self.update_list() self.update_statusbar('{} successfully loaded'.format(self.my_watchlist_name)) self.update_timer = Timer(20, self.timer_cb) self.update_timer.start() except: self.update_statusbar('{} failed to load'.format(this_watchlist.text)) def update_list(self): self.root.ids.watchlist.clear_widgets() for share in self.my_watchlist.shares_dict: # Create button based on current share iteration price = self.my_watchlist.shares_dict[share].last_price try: temp_label = Label(text=share + '\n$' + price, font_size=24) self.root.ids.watchlist.add_widget(temp_label) except TypeError: pass def add_to_list(self, this_btn): ticker = self.add_code_input.text.upper() self.root.ids.statusbar.text = 'Added {} to list'.format(ticker) self.my_watchlist.add_share(ticker) self.update_list() self.add_code_input.text = "" def update_prices(self): self.root.ids.add_share_btn.state = 'down' self.my_watchlist.update_prices() self.update_list() self.update_statusbar('Prices successfully updated!') self.root.ids.add_share_btn.state = 'normal' def update_statusbar(self, message): self.root.ids.statusbar.text = message # noinspection PyBroadException def timer_cb(self): self.update_timer.cancel() self.update_statusbar('Updating current stock prices...') try: self.update_prices() except: pass self.update_timer = Timer(20, self.timer_cb) self.update_timer.start() def add_to_watchlist_menu(self): self.root.ids.menu.clear_widgets() self.root.ids.menu.add_widget(Label(text='Add share to\nwatchlist', color=(1, 0, 0, 1))) self.root.ids.menu.add_widget(self.add_code_input) temp_button = Button(text='Add to list') temp_button.bind(on_release=self.add_to_list) self.root.ids.menu.add_widget(temp_button) def choose_watchlist_menu(self): self.root.ids.menu.clear_widgets() self.root.ids.menu.add_widget(Label(text='Add\nwatchlist')) self.root.ids.menu.add_widget(self.add_watchlist_input) self.root.ids.menu.add_widget(Button(text='Add watchlist')) self.root.ids.menu.add_widget(Label(text='Choose\nwatchlist')) with open('watchlists.txt') as fileID: saved_watchlists = fileID.read().split('\n') for wl in saved_watchlists: temp_btn = Button(text=wl) temp_btn.bind(on_release=self.load_watchlist) self.root.ids.menu.add_widget(temp_btn)
def main(): wListNames = [] wListObjs = [] try: with open("saved.txt", 'r+') as f: print("found file") # do some readign of the file here wListObjs, wListNames = loadSaved(f) print(wListNames) f.close() except IOError: f = open("saved.txt", 'x') # just create the file then close it print("No saved watchlists found") sg.theme('Dark Blue 3') layout1 = [[sg.Text("Watchlists")], toolbar(True), [ sg.Listbox(values=wListNames, enable_events=True, size=(40, 20), key="-LIST-", bind_return_key=True) ]] layout2 = [[sg.Text(size=(20, 1), key="-WLIST-")], toolbar(False), [ sg.Table(values=[], headings=[ "Ticker", "Price", "Change", "%", "Value", "P/L", "P/L %" ], num_rows=15, def_col_width=7, auto_size_columns=False, key="-TABLE-", alternating_row_color="#708090", enable_events=True) ]] layout = [[ sg.Column(layout1, key='-COL1-'), sg.Column(layout2, visible=False, key='-COL2-') ]] window = sg.Window("StockTracker", layout).finalize() if wListNames != []: window.Element("-LIST-").Update(values=wListNames) wListObj = None signal = threading.Event() t = threading.Thread(target=update_watchlists, args=(wListObjs, window, signal)) t.start() selectedRow = None selectedWlist = "" while True: event, values = window.read() if event == "-UPDATE-" and wListObj != None: window["-TABLE-"].Update(values=to_table_data(wListObj.tickers)) if event == "-TABLE-": selectedRow = values["-TABLE-"][0] if event == "Quit" or event == sg.WIN_CLOSED: signal.set() break if event == "-ADDWLIST-": event, values = inputPrompt("Add watchlist").read(close=True) if event == "Ok": wListObjs.append(Watchlist(values[0])) wListNames.append(values[0]) window.Element("-LIST-").Update(values=wListNames) window.write_event_value('-SAVEUPDATE-', None) if event == "-LIST-": if values["-LIST-"][0] == selectedWlist: # double click window.write_event_value('-ENTERWLIST-', None) else: selectedWlist = values["-LIST-"][0] if event == "-ENTERWLIST-" and selectedWlist != "": window[f'-COL1-'].update(visible=False) window[f'-COL2-'].update(visible=True) index = wListNames.index(values["-LIST-"][0]) wListObj = wListObjs[index] window["-WLIST-"].Update(wListObj.name) window["-TABLE-"].Update(values=to_table_data(wListObj.tickers)) if event == "-ADDTICKER-": event, values = tickerPrompt("Add ticker").read(close=True) if event == "Ok": if values[1] != "" and values[2] != "": wListObj.addTicker(values[0], float(values[1]), float(values[2])) else: wListObj.addTicker(values[0]) window["-TABLE-"].Update( values=to_table_data(wListObj.tickers)) window.write_event_value('-SAVEUPDATE-', None) if event == "⏰" and selectedRow != None: index = wListObj.tickers print("alarms not implemented yet!") if event == "←": wListObj = None window[f'-COL1-'].update(visible=True) window[f'-COL2-'].update(visible=False) selectedRow = None if event == "-DELETE1-" and selectedWlist != "": confirm = sg.popup_yes_no("Are you sure you want to delete " + selectedWlist + "?") if confirm == "Yes": print("entered ok") index = wListNames.index(selectedWlist) wListNames.pop(index) wListObjs.pop(index) window.Element("-LIST-").Update(values=wListNames) window.write_event_value('-SAVEUPDATE-', None) if event == "-DELETE2-" and selectedRow != None: wListObj.deleteTicker(window, selectedRow) if event == "-SAVEUPDATE-": saveAll(wListObjs, "saved.txt") t.join() window.close() print("Successfully closed the window and thread") exit()
# https://codeburst.io/indian-stock-market-price-notifier-bot-telegram-92e376b0c33a from stockinformation import Stockinformation from bot import Bot from watchlist import Watchlist import time import sys TOKEN = '../Token/Token_Liga_bot.txt' BOT_NAME = 'stocks_bot' WATCHLIST_FILE = 'watchlist.json' # db = DBHelper() # bot = Bot(TOKEN, BOT_NAME) stock = Stockinformation() w = Watchlist(WATCHLIST_FILE) def main(): # watchlist = w.watchlist_load(WATCHLIST_FILE) # test = w.add('LIN.DE', 3) # print(test) # test1 = w.add('D7G.F', 6) # print(test1) # test1 = w.add('LIN.DE', 6) # test1 = w.add('LIN.DE', 6) # w.save(w.add('LIN.DE', 3)) # w.save(w.add('D7G.F', 3)) # w.save(w.add('D7G.F', 6)) # w.save(w.add('LIN.DE', 6)) w.add('LIN.DE', 3)
# -*- coding: utf-8 -*- # Imports from os import path from flask import Flask, jsonify, render_template, send_file from watchlist import Watchlist # from logger import logger from config import APP_HOST, APP_PORT, BACKDROPS_PATH # App app = Flask(__name__, template_folder='assets', static_folder='assets') app.debug = True wl = Watchlist() # Route: Index @app.route('/') def index(): return render_template('index.html', **{ 'watchlist_size': wl.size, 'providers': wl.providers().get('result', {}), 'genres': wl.genres().get('result', {}), }) # JSON: Watchlist @app.route('/json/watchlist/')
"2y": 0.5, "1y": 1, "6mo": 2, "3mo": 3 } yd = yearly_divisor[tf] if tf in yearly_divisor.keys() else 0 return int(ta.TRADING_DAYS_PER_YEAR / yd) if yd > 0 else df.shape[0] # ## Collect some Data # In[7]: tf = "D" tickers = ["SPY", "QQQ", "AAPL", "TSLA"] watch = Watchlist(tickers, tf=tf) watch.strategy = ta.CommonStrategy watch.load(tickers, timed=True, analyze=True, verbose=False) # # Select an Asset # In[ ]: ticker = tickers[2] # watch.data[ticker].ta.constants(True, [0, 0, 0]) print( f"{ticker} {watch.data[ticker].shape}\nColumns: {', '.join(list(watch.data[ticker].columns))}" ) # ### Trim it