def build(length, correlation_length=400, base=10): correlations = [] table = {} for curSymbol in list_of_files: curStk = stk.Stock() curStk.init_from_symbol(curSymbol, base=base) table[curStk.name.split('\\')[1]] = {} for corSymbol in list_of_files: corStk = stk.Stock() corStk.init_from_symbol(corSymbol, base=base) #correlation,lag = curStk.get_correlation_and_lag(corStk,correlationLength= correlation_length) print("Inside build: correlation length = ", correlation_length) correlation, lag = SP.get_correlation_and_lag( curStk, corStk, correlationLength=correlation_length) table[curStk.name.split('\\')[1]][corStk.name.split('\\')[1]] = [ "{0:.2f}".format(correlation), lag ] #correlations = curStk.get_correlated_symbols(correlation_length,) #correlationsValue = [corr[0] for corr in correlations.values()] df = pd.DataFrame() #for symbol in correlations.keys(): # for corr_symbol in correlations[symbol]: # table[corr_symbol.split('\\')[1]] = {'coreelation value': correlations[symbol][corr_symbol][0], # 'correlation lag': correlations[symbol][corr_symbol][1]} #(pd.DataFrame.from_dict(data=df, orient='index').to_csv('correlations.csv', header=True)) df = (pd.DataFrame.from_dict(data=table, orient='index')) #df.append(pd.DataFrame.from_dict([{'coreelation value': 123,'correlation lag': 333}])) df.to_csv('correlations.csv', header=True)
def purchase_stock(self): self.result_screen.deiconify() try: pur_stock = stock.Stock(self.port_entry_str.get().upper()) print(pur_stock.get_name() + str(pur_stock.get_price())) try: self.port_numerical_amount = float( pur_stock.get_price()) * float(self.port_amount_str.get()) print(str(self.port_numerical_amount)) if float(self.current_funds) >= self.port_numerical_amount: self.result_screen.title("Confirmation") self.result_screen.geometry("500x250") Label( self.result_screen, text="Do you want to complete the following transaction?" ).pack() Label(self.result_screen, text="Current Funds: " + self.current_funds).pack() Label(self.result_screen, text=pur_stock.get_name() + " Price: $ " + str( float(pur_stock.get_price()) * float(self.port_amount_str.get()))).pack() Button(self.result_screen, text="YES", command=self.confirm_purchase).pack() Button(self.result_screen, text="NO").pack() except ValueError: Label(self.result_screen, text="Invalid Amount, must be a float", fg="red") except (AttributeError, IndexError): Label(self.result_screen, text="Invalid Ticker", fg="red").pack()
def __init__(self): # 创建股票对象 self.sa = stock.Stock() # 获取数据库对象 self.dba = database.Database() # 获取股票列表 self.get_stock_list()
def test(saveDB=True, saveFile=False, benchmark=False): s = stock.Stock('000725') mock = { 'file': setting.PATH + 'im_out-adjust-000725(12).xlsx', 'zgb': 33862290000, } s.load(mock=mock) df = s.data # df = df.loc[:, [KN['date'], KN['zgb'], KN['jbmgsy']]] bdf = df.copy() oneLoop = loop.AdjustLoop() oneLoop.addOP(marketValue.GenMarketValue(s)) oneLoop.addOP(marketValue.GenZGB(s)) oneLoop.addOP(marketValue.GenIndustry(s)) oneLoop.addOP(marketValue.GenLastPrice(s)) oneLoop.addOP(marketValue.GenCodeAndName(s)) oneLoop.addOP(forecastProfit.GenForecastProfit(s)) oneLoop.addOP(quarterProfit.GenQuarterProfit(s)) oneLoop.addOP(quarterProfitRatio.GenQuarterProfitRatio(s)) oneLoop.addOP(forecastQuarterProfit.GenForecastProfit(s)) oneLoop.addOP(lastYearProfit.GenLastYearProfit(s)) oneLoop.addOP(forecastMidGrowthRate.GenForecastMidGrowthRate(s)) oneLoop.addOP(forecastFinalGrowthRate.GenForecastFinalGrowthRate(s)) oneLoop.addOP(peMinMax.GenPEMinMax(s)) oneLoop.addOP(forecastPerShareProfit.GenForecastPerShareProfit(s)) oneLoop.addOP(forecastPE.GenForecastPE(s)) oneLoop.addOP(valueMinMax.GenValueMinMax(s)) oneLoop.addOP(distanceMinMax.GenDistanceMinMax(s)) dfOut = oneLoop.verify(df, bdf)
def read_portfolio(filename): ''' Read a stock portfolio file into a list of Stock instances. ''' with open(filename) as lines: portdicts = fileparse.parse_csv(lines, select=['name','shares','price'], types=[str,int,float]) return [stock.Stock(d['name'],d['shares'],d['price']) for d in portdicts]
def test(saveDB=True, saveFile=False, benchmark=False): s = stock.Stock('000725') mock = { 'file': 'd:/stock_python/out/im_out-adjust-000725(12).xlsx', 'zgb': 33862290000, } s.load(mock=mock) # s = stock.Stock(code) # s.load(cwsj=True, yjyg=['2018-09-30', '2018-06-30', '2018-03-31']) # if benchmark: # s.loadBenchmark(file='d:/stock_python/out/out-adjust-' + code + '.xlsx') df = s.data # df = df.loc[:, [KN['date'], KN['zgb'], KN['jbmgsy']]] bdf = df.copy() oneLoop = loop.AdjustLoop() oneLoop.addOP(marketValue.GenMarketValue(s)) oneLoop.addOP(marketValue.GenZGB(s)) oneLoop.addOP(marketValue.GenIndustry(s)) oneLoop.addOP(marketValue.GenLastPrice(s)) oneLoop.addOP(marketValue.GenCodeAndName(s)) oneLoop.addOP(forecastProfit.GenForecastProfit(s)) oneLoop.addOP(quarterProfit.GenQuarterProfit(s)) oneLoop.addOP(quarterProfitRatio.GenQuarterProfitRatio(s)) oneLoop.addOP(forecastQuarterProfit.GenForecastProfit(s)) oneLoop.addOP(lastYearProfit.GenLastYearProfit(s)) oneLoop.addOP(forecastMidGrowthRate.GenForecastMidGrowthRate(s)) oneLoop.addOP(forecastFinalGrowthRate.GenForecastFinalGrowthRate(s)) oneLoop.addOP(peMinMax.GenPEMinMax(s)) oneLoop.addOP(forecastPerShareProfit.GenForecastPerShareProfit(s)) oneLoop.addOP(forecastPE.GenForecastPE(s)) oneLoop.addOP(valueMinMax.GenValueMinMax(s)) oneLoop.addOP(distanceMinMax.GenDistanceMinMax(s)) dfOut = oneLoop.verify(df, bdf)
def sell_stock(self, ticker, amount): for idx, (port_name, port_ticker, stock_amount) in enumerate(self.port): if port_ticker == ticker: if amount > stock_amount: print( "The amount you are trying to sell is more than the portfolio amount." ) return else: temp_stock = stock.Stock(port_ticker) if amount == stock_amount: self.port.remove( (port_name, port_ticker, stock_amount)) self.money.deposit(temp_stock.get_price() * float(amount)) print("You sold " + str(amount) + " shares of " + ticker + ". " + str(temp_stock.get_price() * float(amount)) + " was added to your current funds.") return else: temp_list = list(self.port[idx]) temp_list[2] = str(int(stock_amount) - int(amount)) self.port[idx] = temp_list self.money.deposit(temp_stock.get_price() * float(amount)) print("You sold " + str(amount) + " shares of " + ticker + ". " + str(temp_stock.get_price() * float(amount)) + " was added to your current funds.") return print("The given ticker symbol (" + ticker + ") was not found in the current portfolio.")
def reply(): body = request.values.get('Body', None) number = request.values.get('From', None) print("Sender Number: " + number) command = base_command.Command(body).command return_text = '' print("Command: " + command) if command == "help": response = helps.Help(body) return_text = response.exec() elif command == "stock": response = stock.Stock(body) return_text = response.exec() elif command == "mail": response = mail.Mail(body) return_text = response.exec() elif command == "weather": response = weather.Weather(body) return_text = response.exec() elif command == "translate": response = translate.Translate(body) return_text = response.exec() elif command == "movie": response = movies.Movie(body) return_text = response.exec() if return_text == '': send_message("please type !help for response", number) else: print("RETURN MESSAGE:", return_text) send_message(return_text, number) return str(return_text)
def get_saxo_stocks(): # Saxo stocks = [] stock_amount = saxo.get_stock_amount() names = saxo.get_names() symbols = saxo.get_symbols() shares = saxo.get_share_amounts() costs = saxo.get_costs() market_values = saxo.get_market_prices() currencies = saxo.get_currencies() conversion_rates = saxo.get_conversion_rates() ids = saxo.get_uics() broker = 'saxo' sectors = [] is_index_fond = [False] * stock_amount for i in range(stock_amount): sectors.append(saxo.get_sector(ids[i])) dividends = load_dividends(stock_amount, symbols, names, is_index_fond) frequencies = load_frequencies(stock_amount, currencies, symbols) payout_dates = load_payout_dates(stock_amount, currencies, symbols) for i in range(stock_amount): stocks.append(stock.Stock(names[i], symbols[i], shares[i], costs[i], market_values[i], dividends[i], frequencies[i], payout_dates[i], sectors[i], currencies[i], conversion_rates[i], ids[i], broker)) return stocks
def purchase_stock(self, ticker, amount): current_funds = self.money.get_funds() try: s = stock.Stock(ticker) if (s.get_price() * float(amount)) <= float(current_funds): option = input( "\nThe total amount will be " + str(s.get_price() * float(amount)) + " and your current funds are " + str(current_funds) + "\nAre you sure you want to continue with your purchase?\nType (Y/N) - " ).upper() if option == 'Y': self.money.deposit(-(s.get_price() * float(amount))) self.port.append( (str(s.get_name()).upper(), ticker, amount)) elif option == 'N': print("You did NOT complete the transaction.") else: print("Invalid input...\n") else: print( "\n!!!Current funds will not allow you to purchase this stock.!!!" "\nThe total amount will be " + str(s.get_price() * float(amount)) + " and your current funds are " + str(current_funds)) except (AttributeError, IndexError) as e: print("\n!!!Invalid Stock!!!")
def test_PeriodHigh(self): stk = stock.Stock(TEST_CODE, updater.FromBigCharts) sig = signals.Signals() high = sig.PeriodHigh(stk, 100) assert (high == False)
def get_nordnet_stocks(): # Nordnet stocks = [] stock_amount = nordnet.get_stock_amount() temp_names = nordnet.get_names() names = fix_names(temp_names) symbols = nordnet.get_symbols() shares = nordnet.get_share_amounts() costs = nordnet.get_costs() market_values = nordnet.get_market_prices() currencies = nordnet.get_currencies() conversion_rates = nordnet.get_conversion_rates() ids = nordnet.get_ids() sectors = nordnet.get_sectors() broker = 'nordnet' is_index_fond = nordnet.get_if_indexfond() dividends = load_dividends(stock_amount, symbols, names, is_index_fond) frequencies = load_frequencies(stock_amount, currencies, symbols) payout_dates = load_payout_dates(stock_amount, currencies, symbols) for i in range(stock_amount): stocks.append(stock.Stock(names[i], symbols[i], shares[i], costs[i], market_values[i], dividends[i], frequencies[i], payout_dates[i], sectors[i], currencies[i], conversion_rates[i], ids[i], broker)) return stocks
def add_segment(self, seg: stock.Segment): if seg.ticker not in self.stock_ids: new_stock = stock.Stock(seg) if new_stock.start < self.start: self.start = new_stock.start if new_stock.end > self.end: self.end = new_stock.end
def test_PeriodLow(self): stk = stock.Stock(TEST_CODE, updater.FromBigCharts) sig = signals.Signals() Low = sig.PeriodLow(stk, 100) assert (Low == False)
def testStockClassCreation(self): # Test Stock class creation and getter methods classObj = stock.Stock('SPY', 'Long', 250) # Test that the underlying ticket, direction, and underlying price are populated correctly. self.assertEqual(classObj.getUnderlyingTicker(), 'SPY') self.assertEqual(classObj.getLongOrShort(), 'Long') self.assertEqual(classObj.getUnderlyingPrice(), 250)
def print_wl(self): if not self.stocks: print("--The current watch list is empty--") else: for (ticker, short_name) in self.stocks: temp_stock = stock.Stock(ticker) print(temp_stock.get_name() + " (" + ticker + ")\nMarket Price: " + str(temp_stock.get_price()))
def test_bad_shares(self): s = stock.Stock('GM', 235, 32.56) self.assertEqual(s.name, 'GM') self.assertEqual(s.shares, 235) self.assertEqual(s.price, 32.56) self.assertEqual(s.cost, 7651.6) self.assertEqual(s.sell(35), 200) test_bad_shares(self)
def test_sell(self): s = stock.Stock('GOOG', 100, 490.1) s.sell(50) self.assertEqual(s.shares, 50) s.sell(50) self.assertEqual(s.shares, 0) with self.assertRaises(RuntimeError): s.sell(50)
def from_csv(cls, lines, **opts): self = cls() portdicts = fileparse.parse_csv(lines, select=['name', 'shares', 'price'], types=[str, int, float], **opts) for d in portdicts: self.append(stock.Stock(**d)) return self
def buy_stock(self, ticker, bank_account, quantity=1): if ticker not in self.__portfolio: self.__portfolio[ticker] = {} if 'buy' not in self.__portfolio[ticker]: self.__portfolio[ticker]['buy'] = [] new_stock = stock.Stock(ticker) for i in range(quantity): self.__portfolio[ticker]['buy'].append(new_stock) bank_account.take_funds((new_stock.get_purchase_cost()))
def xtest_FindNewData(self): ##============================================================ ## Check that update works, and GetLastDate returns the correct date ## Only works on trading day after GMT -6 st = stock.Stock(TEST_CODE, updater.FromBigCharts) st.FindNewData() last_date = st.GetLastDate() today = dt.date.today().strftime ("%Y%m%d") assert last_date == today
def read_portfolio(filename): with open(filename, "rt") as infile: portfolios = fileparse.parse_csv(infile, select=["name", "shares", "price"], types=[str, int, float]) portfolios = [ stock.Stock(d["name"], d["shares"], d["price"]) for d in portfolios ] return portfolio.Portfolio(portfolios)
def add_stock(self): stock_ipt = input("Type in a ticker symbol: ").upper() try: temp_stock = stock.Stock(stock_ipt) short_name = temp_stock.get_name() print(short_name + " (" + stock_ipt + ") was added to the watch list.") self.stocks.append((stock_ipt, short_name)) except (AttributeError, IndexError) as e: print("\nAn error occurred when trying to add " + stock_ipt)
def read_portfolio(filename: str) -> list: ''' Read a stock portfolio file into a list of dictionaries with keys name, shares and prices.[] ''' with open(filename) as lines: pdict = fileparse.parse_csv(lines,select=['name','shares','price'], types=[str,int,float]) portfolio = [ stock.Stock(d['name'], d['shares'], d['price']) for d in pdict ] return Portfolio(portfolio)
def stock_finder(stock_name): print("-----searching-----") s = stock.Stock(stock_name) s.update_info() print("success!") print_stock_info(s) if input("Is the info correct? Y/N ").capitalize() == "Y": return s else: stock_finder(input("\nEnter a new search name: "))
def read_portfolio(filename): ''' Read a stock portfolio file into a list of dictionaries with keys name, shares, and price. return them a stock Objects ''' with open(filename) as lines: portdicts = fileparse.parse_csv(lines, select=['name','shares','price'], types=[str,int,float]) portfolio = [stock.Stock(d['name'], d['shares'], d['price']) for d in portdicts] return portfolio
def read_portfolio(filename): '''Opens a given portfolio and reads it into a list of tuples''' with open(filename) as lines: portdict = parse_csv(lines, select=['name', 'shares', 'price'], types=(str, int, float)) portfolio = [ stock.Stock(d['name'], d['shares'], d['price']) for d in portdict ] return portfolio
def read_portfolio(filename): ''' Read a stock portfolio file into a list of dictionaries with keys name, shares, and price. ''' with open(filename) as lines: portdict = fileparse.parse_csv(lines, select=['name', 'shares', 'price'], types=[str, int, float]) return portfolio.Portfolio([stock.Stock(**port) for port in portdict])
def test_FindOldData(self): ## Check that it grabs old data correctly os.system('rm ' + TEST_TIME_SERIES_FILE) fake_today = '20181012' fake_yesterday = '20181011' st = stock.Stock(TEST_CODE, updater.FromBigCharts) st.FindOldData(fake_today) last_date = st.GetLastDate() today = dt.date.today().strftime ("%Y%m%d") assert last_date == fake_yesterday
def load_stock_list(self, tickers): stock_list = [] for ticker in tickers: try: self.alpaca.get_barset(ticker, 'minute', limit=1000)[ticker] stock_list.append(stock.Stock(ticker, self.alpaca)) except Exception as e: print("Caught Exception:", e) return stock_list