def inciso3v(self): codigo = int( input("Ingrese codigo del producto que desea cambiar stock: ")) cantid = int(input("Ingrese la cantidad: ")) stock1 = Stock(codigo, cantid) for i in range(len(self.__listaStock)): if self.__listaStock[i].getCodigoProducto() == codigo: stock2 = Stock(codigo, self.__listaStock[i].getCantidad()) restar = stock1 - stock2 self.inciso3a(codigo, restar)
def main(): chef = LineChef('BTC-USD', 20, 8, [1, 2, 3, 4]) startDate = datetime.datetime(2018, 2, 4, 8) endDate = startDate + datetime.timedelta(days=60) chef.train(startDate, endDate) strongCount = 0 for pat in chef.patterns: if (pat.isStrong()): strongCount += 1 print("# Matches: ", pat.numMatches) print(pat.changes) print(pat) print("STRONG COUNT: ", strongCount) testStartDate = endDate testEndDate = testStartDate + datetime.timedelta(days=14) predictionDelta = 4 simBoi = RepeatPredictor(5, Stock('BTC-USD'), 1000, 20, testStartDate, datetime.timedelta(hours=predictionDelta)) chef.test(testStartDate, testEndDate, predictionDelta, simBoi)
def loadValuesIntoOneStock(self): testStock = Stock('TEST', 'testValues.txt') testStock.record = { "2019-03-18": { "06:00:00": (0.5, 45.10), "06:15:00": (73, 12) }, "2019-03-19": { "06:15:00": (83, 12) }, "2019-03-20": { "06:30:00": (14, -6.0), "06:31:00": (18, 9) } } return testStock
def manejadorArchiStock(self): archi = open("Stock.csv") reader = csv.reader(archi, delimiter=';') next(reader) for i in reader: codP = int(i[0]) cant = int(i[1]) objeto = Stock(codP, cant) self.agregadorStock(objeto) archi.close()
class TestStock(TestCase): def setUp(self): self.TEA = Stock("TEA", "Common", last_dividend=0, par_value=100) self.POP = Stock("POP", "Common", last_dividend=8, par_value=100) self.ALE = Stock("ALE", "Common", last_dividend=23, par_value=60) self.GIN_PRE = Stock("GIN", "Preferred", last_dividend=8, par_value=100, fixed_dividend=0.02) self.GIN_COM = Stock("GIN", "Common", last_dividend=8, par_value=100) # if last_dividend 0, we expect a dividend yield of 0. def test_dividend_yield_1(self): self.assertEqual(self.TEA.dividend_yield(35), 0) def test_dividend_yield_2(self): self.assertEqual(self.POP.dividend_yield(55), 8/55) def test_dividend_yield_3(self): self.assertEqual(self.GIN_PRE.dividend_yield(89), (0.02*100)/89) def test_dividend_yield_4(self): self.assertEqual(self.GIN_COM.dividend_yield(89), 8/89) # if last dividend of a stock is 0, we set its P/E ratio to 0. def test_p_e_ratio_1(self): self.assertEqual(self.TEA.p_e_ratio(50), 0) def test_p_e_ratio_2(self): self.assertEqual(self.GIN_PRE.p_e_ratio(92), 92/8)
def main(transaction_history): # this method assumes the transaction history is sent in the form of a dictionary. # It processes the transaction history of each instrument and creates a portfolio based on it. for key, value in transaction_history.iteritems(): for all_bonds, tran_history in value.iteritems(): transaction = get_current_quantity(tran_history) if key == 'Stock': instrument = Stock(all_bonds, transaction) elif key == 'Bonds': instrument = Bonds(all_bonds, transaction) elif key == 'Cash': instrument = Cash(all_bonds, transaction) else: raise ValueError('Instrument not defined') all_instrument[all_bonds] = instrument return create_portfolio()
def main(): # ts = TimeSeries(key=API_KEY) # for key, stock in ALL_STOCKS.items(): # data, metaData = ts.get_intraday(symbol=stock.symbol, interval="5min", outputsize="full") # for dataKey, item in data.items(): # stock.addValue(dataKey.split(" ")[1], item["4. close"], item["5. volume"], dataKey.split(" ")[0]) # stock.saveValues() # startDate = datetime.datetime(2018, 2, 4, 8) # bull? # startDate = datetime.datetime(2018, 2, 17, 8) # ? startDate = datetime.datetime(2018, 3, 6, 8) # bear endDate = startDate + datetime.timedelta(hours=100) testStartDate = datetime.datetime(2018, 5, 12, 8) testEndDate = testStartDate + datetime.timedelta(hours=168) ratBoi = RatBoi(Stock("BTC-USD")) ratBoi.train(startDate, endDate, iterations=3, learningRate=0.9) # ratBoi.test(testStartDate, testEndDate) ratBoi.simulate(testStartDate, testEndDate, 0) return
def loadValsForSkewKurtosis(self): testStock = Stock('TEST', 'testValues.txt') #3 days, 32 mins span testStock.record = { "2019-03-18": { "06:00:00": (61, 0), "06:01:00": (61, 0), "06:02:00": (61, 0), "06:03:00": (61, 0), "06:04:00": (61, 0), "06:05:00": (64, 0), "06:06:00": (64, 0), "06:07:00": (64, 0), "06:08:00": (64, 0), "06:09:00": (64, 0), "06:10:00": (64, 0), "06:11:00": (64, 0), "06:12:00": (64, 0), "06:13:00": (64, 0), "06:14:00": (64, 0), "06:15:00": (64, 0), "06:16:00": (64, 0), "06:17:00": (64, 0), "06:18:00": (64, 0), "06:19:00": (64, 0), "06:20:00": (64, 0), "06:21:00": (64, 0), "06:22:00": (64, 0), "06:23:00": (67, 0), "06:24:00": (67, 0), "06:25:00": (67, 0), "06:26:00": (67, 0), "06:27:00": (67, 0), "06:28:00": (67, 0), "06:29:00": (67, 0), "06:30:00": (67, 0), "06:31:00": (67, 0), "06:32:00": (67, 0), "06:33:00": (67, 0), "06:34:00": (67, 0), "06:35:00": (67, 0), "06:36:00": (67, 0), "06:37:00": (67, 0), "06:38:00": (67, 0), "06:39:00": (67, 0), "06:40:00": (67, 0), "06:41:00": (67, 0), "06:42:00": (67, 0), "06:43:00": (67, 0), "06:44:00": (67, 0), "06:45:00": (67, 0), "06:46:00": (67, 0), "06:47:00": (67, 0), "06:48:00": (67, 0), "06:49:00": (67, 0), "06:50:00": (67, 0), "06:51:00": (67, 0), "06:52:00": (67, 0), "06:53:00": (67, 0), "06:54:00": (67, 0), "06:55:00": (67, 0), "06:56:00": (67, 0), "06:57:00": (67, 0), "06:58:00": (67, 0), "06:59:00": (67, 0), }, "2019-03-19": { "06:15:00": (73, 0), "06:16:00": (73, 0), "06:17:00": (73, 0), "06:18:00": (73, 0), "06:19:00": (73, 0), "06:20:00": (73, 0), "06:21:00": (73, 0), "06:22:00": (73, 0) }, "2019-03-21": { "06:01:00": (67, 0), "06:02:00": (67, 0), "06:03:00": (67, 0), "06:04:00": (67, 0), "06:05:00": (67, 0), "06:06:00": (70, 0), "06:07:00": (70, 0), "06:08:00": (70, 0), "06:09:00": (70, 0), "06:10:00": (70, 0), "06:11:00": (70, 0), "06:12:00": (70, 0), "06:13:00": (70, 0), "06:14:00": (70, 0), "06:15:00": (70, 0), "06:16:00": (70, 0), "06:17:00": (70, 0), "06:18:00": (70, 0), "06:19:00": (70, 0), "06:20:00": (70, 0), "06:21:00": (70, 0), "06:22:00": (70, 0), "06:23:00": (70, 0), "06:24:00": (70, 0), "06:25:00": (70, 0), "06:26:00": (70, 0), "06:27:00": (70, 0), "06:28:00": (70, 0), "06:29:00": (70, 0), "06:30:00": (70, 0), "06:31:00": (70, 0), "06:32:00": (70, 0) } } return testStock
d_bar = 5 interest_rate = 0.02 init_holding = 1 initialcash = 20000 theta = 75 gene_length = 64 risk_coef = 0.5 num_strategies = 80 max_stockprice = 200 min_stockprice = 0.01 min_excess = 0.005 eta = 0.005 specialist_iterations = 10 the_market = Stock(num_shares, init_price, dividend_startvalue, rho, noise_sd, d_bar, interest_rate) agents = [ Agent(init_holding, initialcash, num_strategies, theta, gene_length, risk_coef, num_shares, init_price, dividend_startvalue, rho, noise_sd, d_bar, interest_rate) for _ in range(100) ] the_specialist = Specialist(max_stockprice, min_stockprice, min_excess, eta, specialist_iterations, num_shares, init_price, dividend_startvalue, rho, noise_sd, d_bar, interest_rate) for t in range(1000): the_market.advance_arprocess() the_specialist.clear_market(agents) ma = the_market.calculate_ma(query='dividend', period=50)
def TestCaseWithFit(): from AprFit import AprFit from winsound import Beep # Pull the stock data into memory. stocks = [] for symbol in symbols: stock = Stock.ShyRetrieve(symbol=symbol, minDate=(datetime.datetime.now() - datetime.timedelta(days=5))) if len(stock._history) > 0: stocks.append(stock) else: print(f"{stock.symbol} no history") Beep(300, 500) # Let the user know it's done importing today = datetime.datetime.now() # In a loop so data stays in memory if the user wants to change parameters. while True: yearsToConsider = AskYears() if yearsToConsider == "break": break scores = [] startDate = today - datetime.timedelta(seconds = 366 * yearsToConsider * 60 * 60 * 24) for stock in stocks: if stock.history[0].date > startDate: continue # Only plot stocks which have enough history. try: apr_fit = stock.get_apr_fit(years=yearsToConsider) except Exception as ex: # Looks like I need to do some sanitizing of the data from yFinance. BEP hits a math domain error here and previously gave strange results in other tests. print(f"Failed to fit curve onto data from {stock.symbol}: {ex}") continue # Determine how much this stock is currently overvalued/undervalued total_dividends_since_t_0 = 0. index = len(stock.history) - 1 while (stock.history[index].date - today).total_seconds() >= apr_fit.t_0 * 31557600.: total_dividends_since_t_0 += stock.history[index].dividend if index == 0: break index -= 1 undervalue = apr_fit.y_0 * (1 + apr_fit.rate) ** (0. - apr_fit.t_0) - (stock.history[-1].price + total_dividends_since_t_0) undervalue /= stock.history[-1].price + total_dividends_since_t_0 N_STDEVS = 2. # Number of standard deviations to use for fitness if apr_fit.stdev * N_STDEVS > 1.: score = Score(stock, 0.) else: score = Score(stock, (apr_fit.rate + undervalue / 4.) * (1. - N_STDEVS * apr_fit.stdev) + 1. / stock.pe_ratio) # stdev applies as both uncertainty in the fit and as potential loss if math.isnan(score.score): print(f"Failed to calculate score for {stock.symbol}") continue # Boost the investments we want to bias towards if stock.symbol in boost: score.score *= 1.5 # Nerf the stocks we don't like if stock.symbol in nerf: score.score *= 0.5 # Attach metadata to the score so we can print it. score.rate = 100. * apr_fit.rate score.undervalue = 100. * undervalue score.uncertainty = 100. * apr_fit.stdev scores.append(score) scores.sort(key=lambda x:x.score) scores.reverse() # Recommend how much would have been good to allocated to each number_of_recommendations = 0 sum = 0 for candidate in scores: if math.isnan(candidate.score): continue if candidate.score <= 0.: continue sum += candidate.score if candidate.score / sum < 0.05: sum -= candidate.score break number_of_recommendations += 1 # Don't recommend >25% in any one asset LIMIT = 0.25 if scores[0].score > sum * LIMIT: redistribution = (scores[0].score - sum * LIMIT) / (number_of_recommendations - 1) for score in scores: score.score += redistribution if scores[1].score > sum * LIMIT: redistribution = (scores[1].score - sum * LIMIT) / (number_of_recommendations - 2) for score in scores: score.score += redistribution scores[1].score = sum * LIMIT scores[0].score = sum * LIMIT print("Recommended distribution:") for i in range(number_of_recommendations): stock = scores[i].stock recommended_percent = 100 * scores[i].score / sum print(f"{recommended_percent:.2f}% in {stock.symbol} Score: {scores[i].score:.2f} P/E: {stock.pe_ratio:.2f} <APR>: {scores[i].rate:.2f} undervalued by {scores[i].undervalue:.2f}% uncertainty: {scores[i].uncertainty:.2f}%") if plot: stock.get_apr_fit(years=yearsToConsider, plot=True) Beep(300, 500)
def OriginalTestCase(): # Import the modules now so it will crash before doing work if a module is missing. import matplotlib.pyplot as plt from dateutil.parser import parse # Pull the stock data into memory. stocks = [] for symbol in symbols: stock = Stock.ShyRetrieve(symbol=symbol, minDate=(datetime.datetime.now() - datetime.timedelta(days=5))) if len(stock._history) > 0: stocks.append(stock) today = datetime.datetime.now() # Let the user know import is complete import winsound winsound.Beep(600, 100) # In a loop so data stays in memory if the user wants to change parameters. while True: yearsToConsider = AskYears() minimumYield = AskMinYield() if yearsToConsider == "break": break if minimumYield == "break": break startDate = today - datetime.timedelta(days = 365 * yearsToConsider) if plot: print("Plotting...") fig, subplots = plt.subplots(nrows=2, ncols=1) dividend_plot = subplots[0] #growth_plot = subplots[1] total_yield_plot = subplots[1] dividend_plot.set_ylabel("Dividend (%/yr)") dividend_plot.set_xlim(left=startDate, right=today) max_dividend = 0. min_dividend = 0. #growth_plot.set_ylabel("Growth Since (%/yr inflation adjusted)") #growth_plot.set_xlim(left=startDate, right=today) max_growth = 0. min_growth = 0. total_yield_plot.set_ylabel("Total Yield (%/yr)") total_yield_plot.set_xlim(left=startDate, right=today) max_total = 0. min_total = 0. annual_yields = [] scores = [] for stock in stocks: if stock.history[0].date > startDate: continue # Only plot stocks which have enough history. filteredGrowth, growthUncertainty = stock.GrowthAPRWithUncertainty(yearsToConsider) dividendYield = stock.AverageDividendPercent(yearsToConsider) dividendUncertainty = stock.DividendPercentUncertainty(yearsToConsider) if dividendUncertainty > dividendYield: dividendUncertainty = dividendYield # Never apply a penalty for dividends annualYield = dividendYield + filteredGrowth if annualYield < minimumYield: continue # Only plot stocks with combined margin better than 10% per year over the past 10 years. print(f"{stock.symbol} {annualYield:.1f} ± {growthUncertainty + dividendUncertainty:.1f}% average annual yield over the past {yearsToConsider} years.") print(f"{filteredGrowth:.2f}% from growth and {stock.AverageDividendPercent(yearsToConsider):.2f}% from dividends.") annual_yields.append((stock.symbol, annualYield)) score = annualYield - 0.431 * (growthUncertainty + dividendUncertainty) # 33rd percentile scores.append((stock.symbol, score)) if plot: dates = [] relGrowth = [] divYieldPercent = [] latest = stock.history[-1] for snapshot in stock.history: if snapshot.date < startDate: continue if snapshot.price == 0.0: continue if (latest.date - snapshot.date).days == 0.0: continue annual_growth = 100. * (latest.price / snapshot.price - 1.) * 1.02 ** ((snapshot.date - latest.date).days / 365.25) / \ ((latest.date - snapshot.date).days / 365.25) if annual_growth > 1. * (latest.date - snapshot.date).days: annual_growth = 1. * (latest.date - snapshot.date).days if annual_growth < -1. * (latest.date - snapshot.date).days: annual_growth = -1. * (latest.date - snapshot.date).days dates.append(snapshot.date) relGrowth.append(annual_growth) divYieldPercent.append(100. * snapshot.annualDividend / snapshot.price) if relGrowth[-1] > max_growth: max_growth = relGrowth[-1] elif relGrowth[-1] < min_growth: min_growth = relGrowth[-1] if divYieldPercent[-1] > 100.: print(f"{dates[-1]}: {stock.symbol} has {divYieldPercent[-1]}% dividend?") print("You may not want to trust this data...") if divYieldPercent[-1] > max_dividend: max_dividend = divYieldPercent[-1] elif divYieldPercent[-1] < min_dividend: min_dividend = divYieldPercent[-1] dividend_plot.plot(dates, divYieldPercent, label=stock.symbol) #growth_plot.plot(dates, relGrowth, label=stock.symbol) annualYield = [] yDates = [] for index in range(200, len(stock.history)): snapshot = stock.history[index] if snapshot.date < startDate: continue priceLastYear = stock.history[index - 200].price if priceLastYear == 0.0: continue yDates.append(snapshot.date) annualYield.append(100. * ((snapshot.price - priceLastYear) + snapshot.annualDividend) / priceLastYear) if annualYield[-1] > max_total: max_total = annualYield[-1] elif annualYield[-1] < min_total: min_total = annualYield[-1] if plot: total_yield_plot.plot(yDates, annualYield, label=stock.symbol) annual_yields.sort(key=lambda x:x[1]) annual_yields.reverse() scores.sort(key=lambda x:x[1]) scores.reverse() # Recommend how much would have been good to allocated to each number_of_recommendations = 0 sum = 0 for candidate in scores: if not math.isnan(candidate[1]): sum += candidate[1] if sum > 0.: if candidate[1] / sum < 0.05: sum -= candidate[1] break if sum < 0.: sum -= candidate[1] break number_of_recommendations += 1 print("Recommended distribution:") recommendations = [] for i in range(number_of_recommendations): symbol = scores[i][0] recommended_percent = 100 * scores[i][1] / sum recommendations.append((symbol, recommended_percent)) print(f"{recommended_percent:.2f}% in {symbol} Score: {scores[i][1]:.2f}") winsound.Beep(300, 500) if plot: fig.tight_layout() fig.autofmt_xdate() #growth_plot.plot([parse("1/1/2000"), today], [0, 0], label='Zero') total_yield_plot.plot([parse("1/1/2000"), today], [0, 0], label='Zero') dividend_plot.set_ylim(bottom=min_dividend, top=max_dividend) #growth_plot.set_ylim(bottom=min_growth, top=max_growth) total_yield_plot.set_ylim(bottom=min_total, top=max_total) dividend_plot.tick_params(labelleft=True, left=True, right=True, bottom=True) #growth_plot.tick_params(labelleft=True, left=True, right=True, bottom=True) total_yield_plot.tick_params(labelleft=True, left=True, right=True, bottom=True, labelbottom=True) dividend_plot.legend() #growth_plot.legend() #total_yield_plot.legend() plt.show()
def setUp(self): self.TEA = Stock("TEA", "Common", last_dividend=0, par_value=100) self.POP = Stock("POP", "Common", last_dividend=8, par_value=100) self.ALE = Stock("ALE", "Common", last_dividend=23, par_value=60) self.GIN_PRE = Stock("GIN", "Preferred", last_dividend=8, par_value=100, fixed_dividend=0.02) self.GIN_COM = Stock("GIN", "Common", last_dividend=8, par_value=100)
from Stocks import Stock ALL_STOCKS = { 'amazon': Stock('AMZN', 'amazonValues.txt'), 'walmart': Stock('WMT', 'walmartValues.txt'), 'generalElectric': Stock('GE', 'generalElectricValues.txt'), 'cocaCola': Stock('KO', 'cocaColaValues.txt'), 'google': Stock('GOOGL', 'googleValues.txt'), 'microsoft': Stock('MSFT', 'microsoftValues.txt'), 'tesla': Stock('TSLA', 'teslaValues.txt'), 'apple': Stock('AAPL', 'appleValues.txt'), 'facebook': Stock('FB', 'facebookValues.txt'), }