def submit(): form = SubmitQuoteForm() #when you submitted the form# if form.validate_on_submit(): #tries to retrieve the basic data, on errors it reloads itself# try: quote = form.quote.data episode = form.source_episode.data person = form.source_person.data except: return render_template(pagenames["form"], form=form) #checks if the person has been set to 'Other'(if the textbox isn't empty), #if that is the case, change the person propertie to it's value specific_person = request.form["source_person_other"] if specific_person != "": person = specific_person #make a new quote object, not giving it a parameter and letting it know it's a new quote. #then save the quote in the json file# quote = Quote(quote, Source(person, episode)) quote.Save() return redirect('/quotes') return render_template(pagenames["form"], form=form)
def insert_quote(url): response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # Extract quote from website. quote_content = soup.findAll('strong') for i in range(len(quote_content)-1): # print(quote_content[i].get_text()) new_quote = Quote(quote=quote_content[i].get_text()) new_quote.insert()
def specificQuote(id): quotes_list = Quote.GetQuotes() #loop through all the quotes that have been found# for quote in quotes_list: #bascially checks if the quote is the one with the parameter id# if quote.Id == id: #create a new quote object, and give it to the view# quote = Quote(quote.Quote, quote.Source, quote.Id) return render_template(pagenames["quote"], quote=quote) #when the parameter id is not being used, return to the list# return redirect(f'/quotes/')
def index(): #gets a list of all quotes found, and selected a random one# quotes_list = Quote.GetQuotes() random_quote = quotes_list[random.randint(0, len(quotes_list) - 1)] #returns the standard view with the random quote as data# return render_template(pagenames["random"], quote=random_quote)
def addQuote(self, quote): value = quote.split(" - ")[0] user = quote.split(" - ")[1] quote_id = len(self.quotes) + 1 add_to_file = str(quote_id) + "=\"" + value + "\"=" + user self.quotes.append(Quote(value, user)) add_to_quote_file(add_to_file)
def step(self, quote: Quote): """ Calculates the indicator and performs update/open/close action on the TradeSituation class (representing investment position) :param quote: float; the price of the invested stock :return: no return """ # Update values (prices) in the fifo_lists (with put method) self.__ma_slow_fifo_list.put(quote.price()) self.__ma_fast_fifo_list.put(quote.price()) # Update position with arrived quote if self.__open_position != None: self.__open_position.update_on_order(quote) # We closed the position (returns true if the position is closed) # The fifo_list(s) are filled? if self.__is_filled_start_data: # Calculate fast and slow lists means pass # If MA short > MA long => BUY # If MA long > MA short => SELL # You must not reopen the position if the trading direction (__current_trading_way) has not changed. if self.__ma_fast_fifo_list.get_mean() > self.__ma_slow_fifo_list.get_mean()\ and self.__current_trading_way is False: # Buy: open position if there is none; close the position if it's hanging in the other way; append the # positions history (to save how much it gained); save the new __current_trading_way if self.__open_position is not None and not self.__open_position.is_closed( ): self.__open_position.close_position(quote) self.__open_position = TradeSituation(quote, True, self.__target_profit) self.__positions_history.append(self.__open_position) self.__current_trading_way = True elif self.__ma_fast_fifo_list.get_mean() < self.__ma_slow_fifo_list.get_mean()\ and self.__current_trading_way is True: # Sell (repeat for SELL) if self.__open_position is not None and not self.__open_position.is_closed( ): self.__open_position.close_position(quote) self.__open_position = TradeSituation(quote, False, self.__target_profit) self.__positions_history.append(self.__open_position) self.__current_trading_way = False else: # Else: the fifo lists are note filled self.__filled_data_points += 1 if self.__filled_data_points > self.__ma_slow_fifo_list: # The fifo_list(s) are not yet filled. Do the necessary updates and checks self.__is_filled_start_data = True
def calculate_pnl_and_dd(self, quote_arg: Quote) -> float: """ Calculates (and updates) the PnL and draw down for the position :param quote_arg: the current quote :return: current pnl """ # In case the position is not opened (not alive) return the value stored in __pnl_bps if self.__is_closed: return self.__pnl_bps # Calculate pnl (different for LONG and SHORT) if self.__is_long_trade: self.__pnl_bps = -self.__transaction_price +\ quote_arg.price() - self.__executed_open_quote.price() else: self.__pnl_bps = -self.__transaction_price - \ quote_arg.price() + self.__executed_open_quote.price() # Calculate draw down self.__max_dd_in_bps = max(self.__max_dd_in_bps, -self.__pnl_bps) # return __pnl_bps return self.__pnl_bps
def quotify(self, original_tweet, mention): author = f'@{original_tweet.user.screen_name}' is_author_named = False if 'by' in mention.text.lower(): quoted = re.search('(?<= by )["\'”](.*?)["\'”]', mention.text, re.IGNORECASE) if quoted: author = quoted.group(1) is_author_named = True value = re.search('(?<= by )(\w+)', mention.text, re.IGNORECASE) if value: author = value.group(1) is_author_named = True quote = Quote(original_tweet.id_str, self.clean_text(original_tweet.text), author.strip()) bg = None if '--bg' in mention.text.lower(): id = re.search('(?<=--bg )(\w+)', mention.text, re.IGNORECASE) if id: bg = self.get_image_by_id(id.group(1)) if not bg and is_author_named: bg = self.get_background_image_for_author(author) if not bg: bg = self.get_background_image() DETACHED_FLAGS = ['--detached', '-D'] if any(flag in mention.text for flag in DETACHED_FLAGS): if mention.user.screen_name.lower() == USERNAME: self.api.destroy_status(mention.id) mention = original_tweet image_file = self.get_quote_image(quote, bg) self.reply_with_image(image_file, mention) self.quotes.append(quote.id)
def emplace(self, *largs, **kwargs): self.add(Quote.new(*largs, **kwargs))
def view_quote(): quote = Quote.select_random_quote() return jsonify({"quote": quote})
greeting = Greeting(name) greeting_message = greeting.message + "\n" brief_pause = "<break time=\"300ms\"/>" pause = "<break time=\"1000ms\"/>" # print(greeting_message) # Message from todoClass todo = Todo() todo_message = todo.message+ "\n" # print(todo_message) # Message from weather class weather = Weather() weather_message = weather.message + "\n" # print(weather_message) # Message from News class news = News() news_message = news.message+ "\n" # Message from Quote Class quote = Quote() quote_message = quote.message close_message = user.name + brief_pause + "is there anything I can help you with?" message = "<speak>" + greeting_message + brief_pause + todo_message + pause + weather_message + pause + news_message + brief_pause + quote_message + brief_pause + close_message + "</speak>" audio = Audio(message) playsound(audio.audio)
def __init__(self, quotesList): self.quoteObjList = [] for quotes in quotesList: self.quoteObjList.append(Quote(quotes))
# Dump the data into a file # pickle.dump(google_data, open(dump_file_name, 'wb')) # Read the file from dump file google_data_loaded = pickle.load(open(dump_file_name, 'rb')) # Create an instance of MomentumStrategy class with arbitrary parameters strategy = MomentumStrategy(150, 290, 1) # FOR loop on quotes: create the Quote instance objects (one per quote line) and feed it (step()) to the strategy object # google_data_loaded.index[quote_line] is the time assosciated with the quote at index quote_line all_quotes = [None] * len(google_data_loaded) for quote_line in range(0, len(google_data_loaded)): all_quotes[quote_line] = Quote( 1, google_data_loaded['Adj Closed'][quote_line], google_data_loaded.index[quote_line]) for quote_line in range(0, len(google_data_loaded)): strategy.step(all_quotes[quote_line]) # Close remaining position to output trade statistics strategy.close_pending_position(all_quotes[len(google_data_loaded)]) print("Total {0} positions opened.".format(len(strategy.all_positions()))) # Calculate pnl total_pnl = 0 for position in strategy.all_positions(): total_pnl += position.return_current_pnl() print("Position {0}: profit {1:2.2f}, draw down {2:2.2f}".format(
def simulate(config, quotes): print("\n---------- SIMULATION ----------\n") indx = 0 verticalMarkers = [] newQuotes = quotes[-config['nQuotes']:] totalProfit = 1 partialProfit = 1 while indx < len(newQuotes): if newQuotes[ indx].dividend > 0: # Dividend date => buy (at closing price) partialProfit = 1 #Initialization buyQuote = newQuotes[indx] # buy (at closing price) print("Buying at " + buyQuote.printRealQuote()) verticalMarkers.append({ "date": buyQuote.timestamp, "color": "y", "label": "Buy" }) indx2 = indx + 1 while indx2 < len(newQuotes): priceChange = newQuotes[indx2].realClose - newQuotes[ indx2 - 1].realClose changePercentage = (priceChange / newQuotes[indx2].realClose) * 100 print("Price change %.2f -> %.2f%%" % (priceChange, changePercentage)) if newQuotes[ indx2].close > buyQuote.close: #Recovered => sell verticalMarkers.append({ "date": newQuotes[indx2].timestamp, "color": "c", "label": "Sell" }) print("Selling at " + newQuotes[indx2].printRealQuote()) break if indx2 - indx > config['recoverAfter']: # Didn't recover verticalMarkers.append({ "date": newQuotes[indx2].timestamp, "color": "r", "label": "Late recovery" }) print('LATE RECOVERY -> ' + str(buyQuote)) break indx2 = indx2 + 1 partialProfit = ( (newQuotes[indx2].realClose - buyQuote.realClose) / buyQuote.realClose) * 100 totalProfit = totalProfit + partialProfit print("Partial profit %.2f%%\tTotal profit: %.2f%%\n" % (partialProfit, totalProfit)) # indx2 = indx # recovered = None # while indx2 < len(newQuotes): # Let's find when it recovers # if newQuotes[indx2].close > buyQuote.close: #Recovered # recovered = newQuotes[indx2] # break # if indx2 - indx > config['recoverAfter']: #Didn't recover in time # break # indx2 = indx2 + 1 # verticalMarkers.append({"date": buyQuote.timestamp, "color": "y", "label":"Buy"}) # if recovered is None: # Didn't recover # print("Didn't recover") # else: # print("Recovered -> " + str(buyQuote) + " " + str(recovered)) # verticalMarkers.append({"date": recovered.timestamp, "color": "c", "label":"Sell"}) indx = indx + 1 config = { "dividendMarker": False, "plotOpen": True, "plotClose": True, "verticalMarkers": verticalMarkers } Quote.plotQuotes(config, newQuotes)
def __init__(self): Gtk.Window.__init__(self, title="Magic Mirror") self.state_list = [ "HOME", "WEATHER", "TIME", "QUOTE", "CALENDAR", "HELP", "INFO", "MIRROR" ] self.state = "" # Data classes which update from subscriber input_data = InputData() weather_data = WeatherData() quote_data = QuoteData() calendar_data = EventData() message_data = MessageData() home_data = HomeData() self.auth_data = AuthData() pin_data = PinData() # Screen objects that are cycled in the window self.home_screen = Home(weather_data, calendar_data, home_data, self.auth_data) self.auth_screen = Auth(self.auth_data, pin_data) self.weather_screen = Weather(weather_data) self.time_screen = TimeDate() self.message_screen = Messages(message_data) self.quote_screen = Quote(quote_data) self.calendar_screen = Calendar(calendar_data) self.help_screen = Help() self.info_screen = Info() self.mirror_screen = Mirror() # Starts the MQTT subscriber self.data_thread = threading.Thread(target=subscriber.run, args=([ input_data, weather_data, quote_data, calendar_data, home_data, self.auth_data, pin_data ], )) self.data_thread.daemon = True self.data_thread.start() # Updates the value on the screens in separate threads GObject.timeout_add(1000, self.auth_screen.update) GObject.timeout_add(1000, self.weather_screen.update_weather) GObject.timeout_add(1000, self.time_screen.update_clock) GObject.timeout_add(1000, self.quote_screen.update) GObject.timeout_add(1000, self.calendar_screen.update_events) GObject.timeout_add(1000, self.message_screen.update_screen) GObject.timeout_add(1000, self.home_screen.update_home) self.app_stack = Gtk.Stack() self.app_stack.set_transition_type( Gtk.StackTransitionType.SLIDE_LEFT_RIGHT) self.app_stack.set_transition_duration(500) self.app_stack.add_named(self.auth_screen, "Auth") self.app_stack.add_named(self.home_screen, "Home") self.app_stack.add_named(self.weather_screen, "Weather") self.app_stack.add_named(self.time_screen, "Time") self.app_stack.add_named(self.message_screen, "Message") self.app_stack.add_named(self.quote_screen, "Quote") self.app_stack.add_named(self.calendar_screen, "Calendar") self.app_stack.add_named(self.help_screen, "Help") self.app_stack.add_named(self.info_screen, "Info") self.app_stack.add_named(self.mirror_screen, "Mirror") # Meant to add the default screen self.add(self.app_stack) self.fullscreen() self.modify_bg(Gtk.StateType.NORMAL, Gdk.Color(255, 0, 255)) self.set_icon(IMG.iconpix)
from Quote import Quote from Analyzer import Analyzer MSFTQuotes = Quote.fullCSVParse("./data/daily_adjusted_MSFT.csv") VZQuotes = Quote.fullCSVParse("./data/daily_adjusted_VZ.csv") config = {"dividendMarker": True, "plotOpen": True, "plotClose": True} #Quote.plotQuotes(config, MSFTQuotes) #Quote.plotMultipleQuotes(config, MSFTQuotes, VZQuotes) config2 = {"daysBefore": 10, "daysAfter": 10, "dividendsNumber": 8} Quote.plotDividendDates(config2, MSFTQuotes) #Analyzer.analyze(MSFTQuotes) config3 = { "nQuotes": 500, "recoverAfter": 10, } # Analyzer.simulate(config3, MSFTQuotes) # ToDo: Plot recovery days in istogram chart and calculate mean and standard deviation (of all the stocks not just one)
def quotes(): #gets a list of all quotes, and return the list with the view# quotes_list = Quote.GetQuotes() return render_template(pagenames["list"], quotes=quotes_list)