Beispiel #1
0
    def test_constructor(self):

        # unit tests for the investment constructor that pass input to
        # arguments positoins and num_trials

        self.assertEqual(investment([1, 10, 100], 1000).positions, [1, 10, 100])
        self.assertEqual(investment([1, 10, 100], 1000).num_trials, 1000)
Beispiel #2
0
    def test_investment(self):
        """
        Tests to make sure that the class investment yields correct output for given input 
        """

        self.assertEqual(investment([1, 10, 100], 100).positions, [1, 10, 100])
        self.assertEqual(investment([1, 10, 100], 100).num_trials, 100)

        self.assertEqual(investment([1, 100], 1000).positions, [1, 100])
        self.assertEqual(investment([1, 100], 1000).num_trials, 1000)
Beispiel #3
0
 def test_investment(self):
     """
     Tests to make sure that the class investment yields correct output for given input 
     """
     
     self.assertEqual(investment([1,10,100], 100).positions, [1,10,100])
     self.assertEqual(investment([1,10,100],100).num_trials, 100)
     
     self.assertEqual(investment([1,100],1000).positions, [1,100])
     self.assertEqual(investment([1,100],1000).num_trials,1000)
Beispiel #4
0
def result_output(positions_set, num_trials):
    '''
    This function outputs daily return performances in both PDF and TXT files.
    '''
    text_file = open('results.txt', 'w')

    for p in positions_set:
        # for each position value, get investment performance result as a numpy array
        daily_ret = investment(int(p), num_trials).daily_returns()

        # plot the histogram of daily return and export PDF file for each position
        fig = plt.figure(figsize=(7, 4))
        plt.hist(daily_ret, 100, range=[-1, 1], alpha=0.5)
        plt.title(
            'The histogram of the result for {}-position of ${:d}'.format(
                p, int(1000 / int(p))))
        plt.xlabel('Regularized Daily Return')
        plt.ylabel('Number of Trials')
        pdf_name = 'histogram_{}_pos.pdf'.format(str(p).zfill(4))
        fig.savefig(pdf_name)

        # write the daily return's mean and standard deviation for each position to a txt file
        mean = np.average(daily_ret)
        std = np.std(daily_ret)
        text_file.write(
            'For position = {}, the mean of daily return is {:f}, and the standard deviation is {:f}.\n'
            .format(p, mean, std))

    text_file.close()
Beispiel #5
0
def result_output(positions_set, num_trials):
    '''
    This function outputs daily return performances in both PDF and TXT files.
    '''
    text_file = open('results.txt', 'w')

    for p in positions_set:
        # for each position value, get investment performance result as a numpy array
        daily_ret = investment(int(p), num_trials).daily_returns()

        # plot the histogram of daily return and export PDF file for each position
        fig = plt.figure(figsize=(7, 4))
        plt.hist(daily_ret, 100, range=[-1, 1], alpha=0.5)
        plt.title('The histogram of the result for {}-position of ${:d}'.format(p, int(1000/int(p))))
        plt.xlabel('Regularized Daily Return')
        plt.ylabel('Number of Trials')
        pdf_name = 'histogram_{}_pos.pdf'.format(str(p).zfill(4))
        fig.savefig(pdf_name)

        # write the daily return's mean and standard deviation for each position to a txt file
        mean = np.average(daily_ret)
        std = np.std(daily_ret)
        text_file.write('For position = {}, the mean of daily return is {:f}, and the standard deviation is {:f}.\n'.format(p, mean, std))

    text_file.close()
Beispiel #6
0
 def test_investment(self):
     inv = list(investment([1], 100000).result()[1].values())
     c = Counter(inv)
     # how many times to get the 2000 (which is 1 as daily_ret)
     pos = c[1]
     # how many times to get the 0 (which is -1 as daily_ret)
     neg = c[-1]
     self.assertAlmostEqual(round(pos / (neg + pos), 3), 0.51, places=2)
Beispiel #7
0
 def test_investment(self):
     inv = list(investment([1], 100000).result()[1].values())
     c = Counter(inv)
     # how many times to get the 2000 (which is 1 as daily_ret)
     pos = c[1]
     # how many times to get the 0 (which is -1 as daily_ret)
     neg = c[-1]
     self.assertAlmostEqual(round(pos/(neg+pos),3), 0.51,places=2)
Beispiel #8
0
def total_gain(sharesNumber, num_trials):
    '''This function gets a position, number of shares in one day, and number of trials or days. 
    It returns the total gain over all the trials.'''
    from numpy import zeros
    daily_ret = zeros((num_trials,1))
    for trial in range(num_trials):
        position_object = investment(sharesNumber) #Create an investment object
        daily_ret[trial,0] = position_object.daily_gain() #find the gain in a single day
    return daily_ret
Beispiel #9
0
def main():
    while True:
        try:
            positions_input = input(
                "Please enter a list of number of shares to buy in parallel:")

            if positions_input == 'quit':
                sys.exit()
## check input
            if positions_input == '':
                raise ValueError("invalid input")

            if positions_input[0] != '[' or positions_input[-1] != ']':
                raise ValueError('input need be a list')

            else:
                positions = positions_input[1:-1].split(',')
                for i, item in enumerate(positions):
                    positions[i] = int(item)
                break

        except KeyboardInterrupt:
            sys.exit()
        except EOFError:
            sys.exit()

    while True:
        try:
            num_trials_input = input(
                'Please input a number of trials you want or enter quit to end:\n'
            )

            if num_trials_input == 'quit':
                sys.exit()


##check input
            if num_trials_input == "":
                raise ValueError('invalid input')

            num_trials = int(num_trials_input)
            if num_trials <= 0:
                raise ValueError('Please enter a positive integer')

            break

        except KeyboardInterrupt:
            sys.exit()
        except EOFError:
            sys.exit()

    for pos in positions:
        inves = investment(pos, num_trials)
        inves.output_histogram()
        inves.print_result()
Beispiel #10
0
def main():
    while True:
        try:
            positions_input = input("Please enter a list of number of shares to buy in parallel:")
            
            if positions_input == 'quit':
                sys.exit()
## check input                
            if positions_input == '':
                raise ValueError("invalid input")
            
            if positions_input[0] != '[' or positions_input[-1] != ']':   
                raise ValueError('input need be a list')  
             
            else:
                positions = positions_input[1:-1].split(',')
                for i, item in enumerate(positions):
                    positions[i] = int(item)
                break    
            
            
        except KeyboardInterrupt:
                sys.exit()
        except EOFError:
                sys.exit()
    
    while True:
        try:
            num_trials_input = input('Please input a number of trials you want or enter quit to end:\n')
            
            if  num_trials_input == 'quit':
                sys.exit()
##check input                
            if num_trials_input == "" :
                raise ValueError('invalid input')  
            
            num_trials = int(num_trials_input)  
            if num_trials <= 0:
                raise ValueError('Please enter a positive integer')
            
            break
        
        except KeyboardInterrupt:
                sys.exit()
        except EOFError:
                sys.exit()
    
    
    for pos in positions: 
        inves = investment(pos,num_trials)
        inves.output_histogram()
        inves.print_result()  
Beispiel #11
0
def main():
    try:
        positions = raw_input("Enter a list of the number of shares to buy in parallel: e.g. 1,10,100,1000 \n")
        positions_split = positions.split(",")
        position_list = [int(position) for position in positions_split]
    except:
        print ("Invalid Input. Please Enter a list of the number of shares, e.g. 1,10,100,1000 \n")

    try:
        num_trials = int(raw_input("How many times to randomly repeat the test?\n"))
    except:
        print ("Invalid Input. Please enter an positive integer")
    outcome = investment(position_list, num_trials)
    outcome.investments()
Beispiel #12
0
def loop():
	positionList = getListPositions()
	num_trials = getNumTrials()	

	clearTextFile(outputFile)
	
	for position in positionList:
		#instantiate investment object for current investment 
		currInvestment = investment(investment_amount,position,pr_lose)

		cumu_ret = np.zeros(num_trials)
		daily_ret = np.zeros(num_trials)
		for trial in range(0, num_trials):
			cumu_ret[trial] = currInvestment.simulate_day()
			daily_ret[trial] = cumu_ret[trial]/investment_amount-1

		printStatistics(outputFile,currInvestment.numShares,daily_ret)
		plotPositionHistogram(currInvestment.numShares,daily_ret)
Beispiel #13
0
def main():
    try:
        positions = raw_input(
            "Enter a list of the number of shares to buy in parallel: e.g. 1,10,100,1000 \n"
        )
        positions_split = positions.split(",")
        position_list = [int(position) for position in positions_split]
    except:
        print(
            "Invalid Input. Please Enter a list of the number of shares, e.g. 1,10,100,1000 \n"
        )

    try:
        num_trials = int(
            raw_input("How many times to randomly repeat the test?\n"))
    except:
        print("Invalid Input. Please enter an positive integer")
    outcome = investment(position_list, num_trials)
    outcome.investments()
Beispiel #14
0
    def test_stimulate(self):

        """unit tests for testing stimulate method.
			We test the each value of the return dictionary 'result' has the same length as
			num_trials, and every element in the value of dictionary 'result' bigger than 
			or equal to -1, and less than or equal to 1 
		"""
        a = investment([1, 10, 100], 1000)
        result = a.stimulate([1000.0, 100.0, 10.0], 1000)

        self.assertEqual(len(result[1]), 1000)
        self.assertEqual(len(result[10]), 1000)
        self.assertEqual(len(result[100]), 1000)

        self.assertTrue(result[1].all() <= 1)
        self.assertTrue(result[1].all() >= -1)

        self.assertTrue(result[10].all() <= 1)
        self.assertTrue(result[10].all() >= -1)

        self.assertTrue(result[100].all() <= 1)
        self.assertTrue(result[100].all() >= -1)
Beispiel #15
0
def main():
	"""
	The main function takes a list of the number of shares to buy in parallel as positions and 
	how many times to randomly repeat the test as num_trials
	"""
	while True:
		try:
			position = input('Please input a list of shares to buy:\n')
			if (position == 'quit'):
				sys.exit()
			position = position.replace(' ', '')
			positions = position[1:-1].split(',')
			for i, item in enumerate(positions):
				positions[i] = int(item)
			break
		except ValueError:
			print('Invalid input!')
		except KeyboardInterrupt:
			sys.exit()
		except EOFError:
			sys.exit()
	while True:
		try:
			num_trials = int(input('Please input how many times you want to repeat the test'))
			break
		except ValueError:
			print('Invalid input!')
		except KeyboardInterrupt:
			sys.exit()
		except EOFError:
			sys.exit()
	#call the class investment constructor to create an object a
	a = investment(positions, num_trials)

	#call the method 'represent_results' in class investment to do the stimulation and represent the result
	a.represent_results(positions, num_trials)
Beispiel #16
0
 def testSimulate(self):
     """Tests for function Simulate"""
     self.assertTrue(len(investment.simulate(investment(100, 10))) == 10)
     self.assertTrue(all(investment.simulate(investment(100, 10))) <= 1)
     self.assertTrue(all(investment.simulate(investment(100, 10))) >= -1)
Beispiel #17
0
 def testInvestment(self):
     """Tests for class Investment"""
     self.assertEqual(investment(100, 10).positions, 100)
     self.assertEqual(investment(100, 10).num_trials, 10)
     self.assertEqual(investment(100, 10).position_value, 10)
Beispiel #18
0
 def test_constructor(self):
     self.assertEqual(investment(10,10000).position, 10)
     self.assertEqual(investment(10,1000).num_trials, 1000)
     self.assertEqual(investment(10,10000).position_value, 100)
Beispiel #19
0
            break

        inv_list = eval(input("Please input a list: "))
        inv_trail = eval(input("How many times to try: "))
        try:
            type(inv_list) is list
        except:
            raise ValueError("The input is not a list")

        try:
            type(inv_trail) is int
        except:
            raise ValueError("The input is not an integer")

        # call the investment function
        inv = investment(inv_list, inv_trail)
        # return the dict from the function
        inv = inv.result()
        txt = open('results.txt', 'w')

        for inv_pos in inv:
            fig = plt.figure()
            plt.hist((list(inv[inv_pos].values())), 100, range=[-1, 1])
            mean = np.mean(list(inv[inv_pos].values()))
            std = np.sqrt(np.var(list(inv[inv_pos].values())))
            title = "The histogram of the result for buying " + str(
                inv_pos) + " share(s) in parallel"
            plt.title(title)
            plt.savefig('histogram_%04d_pos.pdf' % int(inv_pos))
            plt.show()
            txt.write("At the position of: " + str(inv_pos) + "\n")
Beispiel #20
0
 def testInvestment6(self):
     #Test the daily_gain method. Because the outcome of this method is random, we cannot test it directly. So I just test its properties
     self.assertTrue(investment(10).daily_gain() <= 1 and investment(10).daily_gain() >= -1 )   
     self.assertTrue(investment(1000).daily_gain() <= 1 and investment(10).daily_gain() >= -1 )   
Beispiel #21
0
 def testInvestment5(self): 
     #Test the daily_outcome method. Because the outcome of this method is random, we cannot test it directly. So I just test its properties
     self.assertTrue(investment(10).daily_outcome()[5] in [200,0])
     self.assertTrue(investment(1).daily_outcome()[0] in [2000,0])
Beispiel #22
0
 def test_investment(self):
     '''test the method of investment class'''
     self.assertEqual(100, len(investment(10, 100).daily_returns()))
Beispiel #23
0
 def testInvestment3(self):
     #Test the position_value attribute 
     self.assertEqual(investment(1000).position_value, 1)
     self.assertEqual(investment(10).position_value, 100)
Beispiel #24
0
 def testInvestment2(self):
     #Test the position attribute 
     self.assertEqual(investment(10).position, 10 )
     self.assertEqual(investment(1000).position, 1000 )
Beispiel #25
0
 def test_constructor(self):
     self.assertEqual(investment(10, 10000).position, 10)
     self.assertEqual(investment(10, 1000).num_trials, 1000)
     self.assertEqual(investment(10, 10000).position_value, 100)
Beispiel #26
0
 def testInvestment(self):
     """Tests for class Investment"""
     self.assertEqual(investment(100, 10).positions, 100)
     self.assertEqual(investment(100, 10).num_trials, 10)
     self.assertEqual(investment(100, 10).position_value, 10)
Beispiel #27
0
 def testSimulate(self):
     """Tests for function Simulate"""
     self.assertTrue(len(investment.simulate(investment(100, 10))) == 10)
     self.assertTrue(all(investment.simulate(investment(100, 10))) <= 1)
     self.assertTrue(all(investment.simulate(investment(100, 10))) >= -1)
Beispiel #28
0
 def testinvestment(self):
     self.assertEqual(investment([1,10,100,1000],1000).positions, [1,10,100,1000])
     self.assertEqual(investment([1,10,100,1000],1000).num_trials, 1000)
Beispiel #29
0
 def testsimulate(self):
 
     self.assertTrue(len(investment.simulate(investment([1,10,100,1000],1000))[0]) == 1000)
     self.assertTrue(len(investment.simulate(investment([1,10,100,1000],1000))[1]) == 1000)
     self.assertTrue(len(investment.simulate(investment([1,10,100,1000],1000))[2]) == 1000)
     self.assertTrue(len(investment.simulate(investment([1,10,100,1000],1000))[3]) == 1000)
     
     self.assertTrue(all(investment.simulate(investment([1,10,100,1000],1000))[0]) <= 1)
     self.assertTrue(all(investment.simulate(investment([1,10,100,1000],1000))[1]) <= 1)
     self.assertTrue(all(investment.simulate(investment([1,10,100,1000],1000))[2]) <= 1)
     self.assertTrue(all(investment.simulate(investment([1,10,100,1000],1000))[3]) <= 1)
     
     self.assertTrue(all(investment.simulate(investment([1,10,100,1000],1000))[0]) >= -1)
     self.assertTrue(all(investment.simulate(investment([1,10,100,1000],1000))[1]) >= -1)
     self.assertTrue(all(investment.simulate(investment([1,10,100,1000],1000))[2]) >= -1)
     self.assertTrue(all(investment.simulate(investment([1,10,100,1000],1000))[3]) >= -1)
Beispiel #30
0
 def testInvestment4(self):
     #Test the daily_outcome method. Because the outcome of this method is random, we cannot test it directly. So I just test its properties
     self.assertTrue(investment(10).daily_outcome().shape == (10, 1))
     self.assertTrue(investment(100).daily_outcome().shape == (100, 1))
Beispiel #31
0
    """
    This is the main program that runs with positions set to [1, 10, 100, 1000] and num_trials set to 10000.
    It will save four histograms and a results.txt file. 
    """
    while True:
        positions = raw_input('Please enter a list of numbers of shares like [1,10,100,1000] or type "quit" to exit. ')
        #convert an input string [1,10,100,1000] into a list.
        positions = positions.split(',')
        positions[0] = positions[0][1:]
        positions[-1] = positions[-1][:-1]
        positions = [int(i) for i in positions]


        if positions == [1,10,100,1000]:
            num_trials = 10000
            initial_amount = investment(1000)
            result_table = pd.DataFrame(columns = ["position", "mean", "std"])
            n = 0

            for position in positions:
                daily_ret = initial_amount.daily_investment(position, num_trials)
                result_table.loc[n] = [position, np.mean(daily_ret), np.std(daily_ret)]
                n = n + 1
                picture = plt.figure()
                plt.hist(daily_ret, 100, range=[-1,1])    # plot histogram
                plt.title('Histogram of Daily Return for Position {}'.format(position))
                plt.xlabel('Daily Return')
                picture.savefig('histogram_{}_pos.pdf'.format(str(position)))
                result_table.to_csv('results.txt', sep=',')
                print "Histograms have been saved as .pdf at current directory."
            print "Text file has been saved as \"results.txt\" at current directory."
Beispiel #32
0
            break

        inv_list = eval(input("Please input a list: "))
        inv_trail = eval(input("How many times to try: "))
        try:
            type(inv_list) is list
        except:
            raise ValueError("The input is not a list")

        try:
            type(inv_trail) is int
        except:
            raise ValueError("The input is not an integer")

        # call the investment function
        inv = investment(inv_list, inv_trail)
        # return the dict from the function
        inv = inv.result()
        txt = open('results.txt', 'w')

        for inv_pos in inv:
            fig = plt.figure()
            plt.hist((list(inv[inv_pos].values())), 100, range=[-1, 1])
            mean = np.mean(list(inv[inv_pos].values()))
            std = np.sqrt(np.var(list(inv[inv_pos].values())))
            title = "The histogram of the result for buying " + str(inv_pos) + " share(s) in parallel"
            plt.title(title)
            plt.savefig('histogram_%04d_pos.pdf' % int(inv_pos))
            plt.show()
            txt.write("At the position of: " + str(inv_pos) + "\n")
            txt.write("The mean of daily return: " + str(mean) + "\n")