Ejemplo n.º 1
0
    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
Ejemplo n.º 2
0
    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
Ejemplo n.º 3
0
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.')
Ejemplo n.º 4
0
 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]))
Ejemplo n.º 5
0
 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
Ejemplo n.º 6
0
 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]))
Ejemplo n.º 7
0
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()
Ejemplo n.º 8
0
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
Ejemplo n.º 9
0
    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)
Ejemplo n.º 10
0
 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]))