make this code more readable and better overall def dataframetolist(dataframe):…
- User
make this code more readable and better overall
def dataframe_to_list(dataframe): price_data = [] for price, timestamp in zip(dataframe.open, dataframe.index): year = timestamp.year month = timestamp.month price_data.append({'price':price,'time':{'year':year,'month':month}}) return price_data
tv = TvDatafeed()
def get_stock_prices(ticker, exchange='MOEX'): while True: try: stock_prices = tv.get_hist(symbol=ticker,exchange=exchange,interval=Interval.in_monthly,n_bars=1000) stock_prices = dataframe_to_list(stock_prices) return stock_prices except: Print("Failed getting stock prices. Trying again", 'red') wait(2)
def get_yearly_prices(stock_prices):
stock_yearly_prices = {} for price in stock_prices: stock_yearly_prices[str(price['time']['year'])] = price['price'] # print(stock_yearly_prices) # input() return stock_yearly_pricesdef get_prices_with_div_reinvested(stock_prices, dividends):
# Start tracking the investment initial_investment = 1 # Assumes a $1 initial investment for simplicity initial_price = list(stock_prices.values())[0] total_shares = initial_investment / initial_price # Process each years dividends and compute reinvestment from the start year of dividends prices_with_div_reinvested = {} for year, price in stock_prices.items(): # Look for a dividend in that year and convert to USD try: dividend = float(dividends[year])/USDRUB_prices[year] except: dividend = 0 Print(str(dividend), 'yellow') # If there's a dividend, reinvest it if dividend: reinvested_shares = (dividend * total_shares) / price print(f"total shares: {total_shares}") print(f"Shares bougth: {reinvested_shares}") total_shares += reinvested_shares prices_with_div_reinvested[year] = total_shares * price return prices_with_div_reinvestedget top 50 tickers by market cap
response = requests.get('https://smart-lab.ru/q/shares/order_by_issue_capitalization/desc/') soup = BeautifulSoup(response.text, "html.parser") tickers = [td.text for td in soup.findAll(class_='trades-table__ticker')[2:52]]
tickers = ['SBERP', 'SNGSP', 'SIBN']
tickers = ['YNDX']
USDRUB_prices = get_stock_prices('USDRUB','FX_IDC') USDRUB_prices = get_yearly_prices(USDRUB_prices)
returns = {}
for ticker in tickers: Print(ticker, 'yellow')
stock_prices = get_stock_prices(f'{ticker}/USDRUB') stock_prices = get_yearly_prices(stock_prices) dividends = get_dividends(ticker) returns[ticker] = get_prices_with_div_reinvested(stock_prices, dividends)print(returns)
- Assistant