def getGoogleValues(url): response = requests.get(url) response.raise_for_status() strResponse = response.text if strResponse.startswith("\n// "): strResponse = strResponse[3:] jsonResp = json.loads(strResponse) return (jsonResp[0]["l"]).replace(',', '') return 0
def getAvantageValues(url): response = requests.get(url) response.raise_for_status() strResponse = response.text jsonResp = json.loads(strResponse) jsonTimeSeries = jsonResp["Time Series (Daily)"] maxdatetime = datetime.strptime("1977-01-01", '%Y-%m-%d') value = 0 for elem in jsonTimeSeries: elemdatetime = datetime.strptime(elem, '%Y-%m-%d') if elemdatetime > maxdatetime: maxdatetime = elemdatetime value = jsonTimeSeries[elem]["4. close"] return [value, maxdatetime]
def start_conspiracy(): members = request.json # validate the members! valid_members = True if not members or not isinstance(members, list): valid_members = False for member in members: if not (isinstance(member, dict) and member.get('name') and member.get('email')): valid_members = False if len(members) > MAX_MEMBERS: valid_members = False if not valid_members: response.status = 403 return { 'success': False, 'errors': ['Provide some JSON like [{"name": "Joe", "email": "*****@*****.**"}]!'] } MAILGUN_ENDPOINT = '{}/{}/messages'.format(MAILGUN_BASE, MAILGUN_DOMAIN) # now email the members! for member in members: pruned = [m for m in members if m != member] to = u','.join([m['email'] for m in pruned]) subject = SUBJECT_TEMPLATE.format(**member) body = BODY_TEMPLATE.format(**member) html = misaka.html(body) payload = { 'from': 'Conspiracy Santa <{}>'.format(MAILGUN_FROM), 'to': to, 'subject': subject, 'html': html } response = requests.post(MAILGUN_ENDPOINT, data=payload, auth=('api', MAILGUN_API_KEY)) response.raise_for_status() return { 'success': True }
def send_email(self): # now email the members! for group in self.members: for member in group: pruned = [m for m in group if m != member] to = u','.join([m['email'] for m in pruned]) subject = self.subject_template.format(**member) body = self.body_template.format(**member) html = misaka.html(body) payload = { 'from': 'Conspiracy Gifting HQ <{}>'.format(self.mailgun_from), 'to': to, 'subject': subject, 'html': html } # print payload response = requests.post(self.mailgun_endpoint, data=payload, auth=('api', self.mailgun_api_key)) response.raise_for_status()
def getFinectV4(url, datetime_now): timeDelta = timedelta(days=7) values = [] timeNow = datetime_now while values == [] and (datetime_now - timeNow) < timedelta(days=45): timeBefore = timeNow - timeDelta myUrl = url + "&start=" + str(timeBefore.year) + "-" + str( timeBefore.month) + "-" + str(timeBefore.day) + "&end=" + str( timeNow.year) + "-" + str(timeNow.month) + "-" + str( timeNow.day) # print myUrl response = requests.get(myUrl) response.raise_for_status() values = response.json()['data'] timeNow = timeBefore if values != []: datetime_value = datetime.strptime("1977-01-01", '%Y-%m-%d') theValue = 0 for value in values: # print value new_datetime_value = datetime.strptime( value['datetime'].split('T')[0], '%Y-%m-%d') new_value = value['price'] if new_datetime_value > datetime_value: datetime_value = new_datetime_value theValue = new_value # print theValue # print datetime_value return [str(theValue), datetime_value]
def getStockValues(): timeDelta = timedelta(days=7) historyPath = path + "stockHistory/" if not os.path.exists(historyPath): os.makedirs(historyPath) templateText = "{0:20}|{1:12}|{2:12}|{3:12}" print(templateText.format("Name", " Paid", " Value", " Difference")) line = "-------------------------------------------------------------" print(line) template = "{0:20}|{1:12.2f}|{2:12.2f}|{3:12.2f}" templatePerc = "{0:20}|{1:12.2f}|{2:12.2f}|{3:11.2f}%" paidTotal = 0 valueTotal = 0 diffTotal = 0 elemCnt = 0 elements = len(data['stocks']) datetime_now = datetime.now() for elem in data['stocks']: stockValuesJson = {} url = elem['url'] urlGoogle = "" datetime_value = datetime.strptime("1977-01-01", '%Y-%m-%d') theValue = 0 try: urlv4 = elem['urlv4'] [theValue, datetime_value] = getFinectV4(urlv4, datetime_now) except KeyError as error: pass if theValue == 0: for x in range(0, 5): try: urlAvantage = elem['urlAvantage'] [theValue, datetime_value] = getAvantageValues(urlAvantage) break except KeyError as error: pass time.sleep(10) if theValue == 0: try: urlGoogle = elem['urlGoogle'] theValue = getGoogleValues(urlGoogle) datetime_value = datetime_now except KeyError as error: pass statusJson['status'] = str(elemCnt) + " of " + str(elements) elemCnt = elemCnt + 1 try: if theValue == 0: values = [] timeNow = datetime_now while values == [] and (datetime_now - timeNow) < timedelta(days=45): timeBefore = timeNow - timeDelta myUrl = url + "?startDate=" + str( timeBefore.year) + "-" + str( timeBefore.month) + "-" + str( timeBefore.day) + "&endDate=" + str( timeNow.year) + "-" + str( timeNow.month) + "-" + str(timeNow.day) response = requests.get(myUrl) response.raise_for_status() values = response.json() timeNow = timeBefore if values != []: datetime_value = datetime.strptime("1977-01-01", '%Y-%m-%d') theValue = 0 for value in response.json(): new_datetime_value = datetime.strptime( value['date'], '%Y-%m-%d') new_value = value['value'] if new_datetime_value > datetime_value: datetime_value = new_datetime_value theValue = new_value if theValue != 0: currentInvestmentValue = float(theValue) * elem['titles'] gain = float(theValue) * elem['titles'] - elem['paid'] stockPaidPrice = (elem['paid'] / elem['titles']) gainPerc = (gain * 100) / elem['paid'] color = bcolors.RED if gain > 0: color = bcolors.GREEN print(color + template.format(elem['stock'], elem['paid'], currentInvestmentValue, gain)) print(color + templatePerc.format( datetime_value.strftime("%Y-%m-%d"), stockPaidPrice, float(theValue), gainPerc)) stockValuesJson['stock'] = elem['stock'] stockValuesJson['paidTotal'] = elem['paid'] stockValuesJson['investmentValue'] = currentInvestmentValue stockValuesJson['gain'] = gain stockValuesJson['date'] = datetime_value.strftime("%Y-%m-%d") stockValuesJson['paidPerStock'] = stockPaidPrice stockValuesJson['currValue'] = float(theValue) stockValuesJson['gainPerc'] = gainPerc stockValuesArrayJson.append(stockValuesJson) paidTotal = paidTotal + elem['paid'] valueTotal = valueTotal + float(theValue) * elem['titles'] diffTotal = diffTotal + float( theValue) * elem['titles'] - elem['paid'] print(bcolors.ENDC + line) with open( historyPath + elem['stock'].replace(" ", "_") + ".csv", 'ab') as file: file.write((datetime_value.strftime("%Y-%m-%d") + "," + theValue + '\n').encode()) else: color = bcolors.YELLOW print(color + elem['stock']) print(color + "Unable to retrieve values") print(bcolors.ENDC + line) except requests.exceptions.HTTPError as error: stockValuesJson['stock'] = elem['stock'] stockValuesJson['paidTotal'] = elem['paid'] stockValuesJson['investmentValue'] = 0 stockValuesJson['gain'] = 0 stockValuesJson['date'] = "1970-1-1" stockValuesJson['paidPerStock'] = 0 stockValuesJson['currValue'] = 0 stockValuesJson['gainPerc'] = 0 stockValuesArrayJson.append(stockValuesJson) print(error.response.status_code, error.response.text) color = bcolors.RED if diffTotal > 0: color = bcolors.GREEN print(color + template.format("TOTAL:", paidTotal, valueTotal, diffTotal)) templateSummary = "{0:46}|{1:11.2f}%" print( templateSummary.format(" ", float((diffTotal * 100) / paidTotal)) + bcolors.ENDC) totalsJson['paidTotal'] = paidTotal totalsJson['valueTotal'] = valueTotal totalsJson['gain'] = diffTotal totalsJson['gainPerc'] = float((diffTotal * 100) / paidTotal) for elem in data['stocks']: # remove duplicated prevLine = "" fileName = historyPath + elem['stock'].replace(" ", "_") + ".csv" origFileName = fileName + ".orig" shutil.move(fileName, origFileName) firstLine = 1 with open(origFileName, 'rb') as fileRead: with open(fileName, 'wb') as fileWrite: for line in fileRead: if firstLine == 1: if line != "Date,Value\n": fileWrite.write(("Date,Value\n").encode()) firstLine = 0 if line != prevLine: fileWrite.write(line) prevLine = line stocks_json.append("" + elem['stock'].replace(" ", "_")) paidVal_json.append(elem['paid'] / elem['titles']) os.remove(origFileName) statusJson['status'] = "Done" return