def get(self): lastRunDateObj = ScheduledInvestRunDate.all().get(); if (lastRunDateObj == None): lastRunDate = date.today() - timedelta(days=20); lastRunDateObj = ScheduledInvestRunDate(lastRunDate=lastRunDate, key_name="last_run_date"); lastRunDateObj.put(); lastRunDate = lastRunDateObj.lastRunDate; startDate = lastRunDate + timedelta(days=1); endDate = date.today() - timedelta(days=3); currDate = startDate; scheduleQuery = ScheduledInvestment.all(); for scheduledInvest in scheduleQuery: while (True): if currDate.day == scheduledInvest.dayOfMonth: sharePrice = self.get_share_price(currDate, scheduledInvest.ticker); invest = Investment(ticker=scheduledInvest.ticker, amount=scheduledInvest.amount, date=currDate, sharePrice=sharePrice, shares=self.num_shares(scheduledInvest.amount, sharePrice)); invest.put(); currDate = currDate + timedelta(days=1); if currDate > endDate: break; lastRunDateObj.lastRunDate = endDate; lastRunDateObj.put(); self.response.out.write("scheduled");
def getInvestments(self, investmentId, startDate, endDate, active): investmentList = [] # if no period is informed, find the second max date in such a way to allow evaluate the evolution # TODO: figure out a better way to do this # TODO: after inserting an operation with bigger date than the end date of balance, the same is not returned in the result: this must be fixed somehow if startDate is None and endDate is None: for investment in self.investment: if active == True and investment.balance[0].amount == 0: continue if len(investment.balance) > 1 and ( startDate is None or investment.balance[1].date < startDate): startDate = investment.balance[1].date if endDate is None or investment.balance[0].date > endDate: endDate = investment.balance[0].date print(f'[debug] get investment: {startDate} - {endDate}') # trasverse the investments list to fetch those that satisfy all search criteria for investment in self.investment: if active == True and investment.balance[0].amount == 0: continue if investmentId is not None and investmentId != str(investment.id): continue balance = [] for balanceItem in investment.balance: if startDate <= balanceItem.date and endDate >= balanceItem.date: balance.append(balanceItem) operation = [] for operationItem in investment.operation: if startDate <= operationItem.date and endDate >= operationItem.date: operation.append(operationItem) revenue = [] for revenueItem in investment.revenue: if startDate <= revenueItem.date and endDate >= revenueItem.date: revenue.append(revenueItem) if len(balance) > 0: investmentAux = Investment() investmentAux.id = investment.id investmentAux.name = investment.name investmentAux.type = investment.type investmentAux.bank = investment.bank investmentAux.operation = operation investmentAux.balance = balance investmentAux.revenue = revenue investmentList.append(investmentAux.to_json()) return investmentList
def test_results_file(self): try: os.remove('results.txt') except IOError: pass positions = [1, 10, 100, 1000] no_trials = 1000 Investment.calculate_for_positions(positions, no_trials) self.assertTrue(os.path.isfile('results.txt'))
def visit_investment(self, investment: Investment): print('visit investment') if investment.getBalance() >= 500: return investment else: return None pass
def add_investment(self, id, cur_value, marketItem, amount=None): """ Create an investment object or add value to an existing one :param id: The ID of the post to invest in :param cur_value: The current value of the post :param marketItem: The post object :param amount: The amount to invest in the post :return: The success of the action (boolean) """ from investment import Investment if amount is None: amount = self.default_invest # Check if the user has enough to invest if self.balance <= 0: return None elif self.balance < amount: amount = self.balance self.balance -= amount investmnt = Investment(amount, int(id), cur_value + amount, marketItem) self.investments.append(investmnt) marketItem.value += amount # return True if an investment was successfully added return True
def load(self): with open(self.dataFileName, 'r') as fileHandler: fileData = json.load(fileHandler) for investmentAttributes in fileData['investments']: self.investment.append( Investment.unserialize(investmentAttributes))
def save(self): investmentList = [] for investment in self.investment: investmentList.append(Investment.serialize(investment)) with open(self.dataFileName, 'w') as fileHandler: json.dump({'investments': investmentList}, fileHandler)
def test_plots_files(self): try: os.remove('histogram_0001_pos.pdf') os.remove('histogram_0010_pos.pdf') os.remove('histogram_0100_pos.pdf') os.remove('histogram_1000_pos.pdf') except IOError: pass positions = [1, 10, 100, 1000] no_trials = 1000 Investment.calculate_for_positions(positions, no_trials) self.assertTrue(os.path.isfile('histogram_0001_pos.pdf')) self.assertTrue(os.path.isfile('histogram_0010_pos.pdf')) self.assertTrue(os.path.isfile('histogram_0100_pos.pdf')) self.assertTrue(os.path.isfile('histogram_1000_pos.pdf'))
def makeInvestment(self, date, amount, account, interest, userId, productId): if amount <= 0: raise ValueError("Investment value must be greater than zero!") investment = Investment(date, amount, account, interest, userId, productId) self.products.append(investment) self.invest(account, amount) return investment
def solve(positions, num_trials): """ For a given position list and number of trials, run the experiments and draw the plots. """ for position in positions: # create a new class investment = Investment(position) daily_ret = [] for trial in range(num_trials): # do a invest each time investment.invest() # calculate the corresponding daily_ret, using double daily_ret.append(investment.ret * 1.0 / 1000.0 - 1.0) print("The mean of position", position, "is", mean(daily_ret)) print("The standard deviation of position", position, "is", stdev(daily_ret)) plt.hist(daily_ret, 100, range=[-1, 1]) plt.show()
def run_process(): """.""" try: Organization.run() Fund.run() Person.run() FundingRound.run() HasAcquired.run() Funding.run() HasFund.run() Investment.run() HasAffiliation.run() HasStudiedat.run() except Exception as e: logger = Logger() logger.logg(debug_msg='Error while running cron job.', info_msg='Function = run_process()', warning_msg='Error in executing scheduled job', error_msg='Module = ' + log_file, critical_msg=str(e))
def getSummData(self, ticker): invs = Investment.all().filter("ticker", ticker); data = SummaryData(); data.ticker = ticker; for inv in invs: data.amount = data.amount + inv.amount; data.shares = data.shares + inv.shares; latestPriceQ = stockPrice.all().filter("ticker", ticker).order("-date"); latestPrice = latestPriceQ.get().price; data.currPrice = latestPrice; data.value = data.currPrice * data.shares; if data.amount > 0: data.percentage = data.value / Decimal(data.amount) - Decimal("1.0"); return data;
def find_worth(submissions, my_investments, score=0, age=10): limit = 0 print(YELLOW) print("\tSearching for:\t" + "at least " + str(score) + " upvotes") print("\t\t\t" + "and less than " + str(age) + " hours") investments = [] for submission in submissions: sub_age = (datetime.now() - datetime.fromtimestamp( submission.created_utc)).total_seconds() / (60 * 60) if submission.subreddit == "MemeEconomy": if sub_age <= age and submission.score >= score: no_double = 1 for investment in my_investments: if (investment.submission.permalink == submission.permalink ): no_double = 0 if no_double: mine_soon = Investment(submission) print_investment(mine_soon) investments.append(mine_soon) print(RESET) return investments
def setUp(self): self.bank_id = 1 self.bank = Bank(bank_id=self.bank_id) self.products = [] self.accounts = [] self.credits = [] self.investments = [] # Prepare products for i in range(1, 11): # accounts account = BankAccount(bank_id=self.bank_id, user_id=1, product_id=i * 10) self.bank.deposit(account, i * 300) self.accounts.append(account) # credits credit = Credit(product_id=i * 20, account=account, end_date=date.today, money=100 * i, user_id=1, number_of_installment=12, bank_id=self.bank_id) self.credits.append(credit) # investment investment = Investment(endDate=date.today, amount=100 * i + 1, interest=InvestmentInterest, product_id=i * 30, account=account, user_id=1, bank_id=self.bank_id) self.investments.append(investment) # prepare one collection with all products self.products.append(account) self.products.append(credit) self.products.append(investment)
def calcPositionValue(self): inv = Investment('[1, 10, 100, 1000]', 100, 17) inv.setSeed() inv.calcPositionValue() self.assertEqual(inv.position_value, np.array([1000, 100, 10, 1]))
def insertNewInvestment(self, investmentData): investmentAux = Investment.unserialize(investmentData) self.investment.append(investmentAux) return investmentAux.to_json()
def calcCumulativeReturn(self): inv = Investment('[1, 10, 100, 1000]', 100, 17) inv.setSeed() inv.calcPositionValue() inv.calcCumulativeReturn() inv.calcDailyReturn() inv.calcDailyReturnMean() self.assertEqual(np.round(inv.daily_mean, 4), np.array([0.1, 0.024, 0.0212, 0.0177]))
def main(): inputPositions = input('Please give a list of shares that you would like to buy. The input can be something like [1, 10, 100, 1000]. Type in \'quit\' to quit the program.\n') if inputPositions == 'quit': return # check 1st input string checkInput(inputPositions) # convert 1st input string to a list inputStrSplit = inputPositions[1:-1].strip().split(',') shares_list = [] for share in inputStrSplit: shares_list.append(int(share)) # check 2nd input string num_trails = input('Please give a number of trails that you would like to simulate. For example, 10000.Type in \'quit\' to quit the program.\n') if num_trails == 'quit': return # run Investment class print('Calculating...') inv = Investment(shares_list, int(num_trails)) inv.calcPositionValue() inv.calcCumulativeReturn() inv.calcDailyReturn() inv.calcDailyReturnMean() inv.calcDailyReturnStd() inv.saveResults() print('Done. Results are saved.')
def calcCumulativeReturn(self): inv = Investment('[1, 10, 100, 1000]', 100, 17) inv.setSeed() inv.calcPositionValue() inv.calcCumulativeReturn() inv.calcDailyReturn() inv.calcDailyReturnMean() inv.calcDailyReturnStd() self.assertEqual(inv.daily_std, np.array([0.995 , 0.3829, 0.1005, 0.0346]))
def calcCumulativeReturn(self): inv = Investment('[1, 10, 100, 1000]', 100, 17) inv.setSeed() inv.calcPositionValue() inv.calcCumulativeReturn() inv.calcDailyReturn() inv.calcDailyReturnMean() inv.calcDailyReturnStd() self.assertEqual(inv.daily_std, np.array([0.995, 0.3829, 0.1005, 0.0346]))