You are on page 1of 15

In 

[39]: !pip install yfinance==0.1.67

!pip install pandas==1.3.3

Requirement already satisfied: yfinance==0.1.67 in c:\users\admin\anacond


a3\lib\site-packages (0.1.67)

Requirement already satisfied: pandas>=0.24 in c:\users\admin\anaconda3\l


ib\site-packages (from yfinance==0.1.67) (1.3.3)

Requirement already satisfied: requests>=2.20 in c:\users\admin\anaconda3


\lib\site-packages (from yfinance==0.1.67) (2.26.0)

Requirement already satisfied: lxml>=4.5.1 in c:\users\admin\anaconda3\li


b\site-packages (from yfinance==0.1.67) (4.6.4)

Requirement already satisfied: numpy>=1.15 in c:\users\admin\anaconda3\li


b\site-packages (from yfinance==0.1.67) (1.20.1)

Requirement already satisfied: multitasking>=0.0.7 in c:\users\admin\anac


onda3\lib\site-packages (from yfinance==0.1.67) (0.0.10)

Requirement already satisfied: pytz>=2017.3 in c:\users\admin\anaconda3\l


ib\site-packages (from pandas>=0.24->yfinance==0.1.67) (2021.1)

Requirement already satisfied: python-dateutil>=2.7.3 in c:\users\admin\a


naconda3\lib\site-packages (from pandas>=0.24->yfinance==0.1.67) (2.8.1)

Requirement already satisfied: six>=1.5 in c:\users\admin\anaconda3\lib\s


ite-packages (from python-dateutil>=2.7.3->pandas>=0.24->yfinance==0.1.6
7) (1.15.0)

Requirement already satisfied: idna<4,>=2.5 in c:\users\admin\anaconda3\l


ib\site-packages (from requests>=2.20->yfinance==0.1.67) (2.10)

Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\users\admin\an


aconda3\lib\site-packages (from requests>=2.20->yfinance==0.1.67) (1.26.
4)

Requirement already satisfied: certifi>=2017.4.17 in c:\users\admin\anaco


nda3\lib\site-packages (from requests>=2.20->yfinance==0.1.67) (2020.12.
5)

Requirement already satisfied: charset-normalizer~=2.0.0 in c:\users\admi


n\anaconda3\lib\site-packages (from requests>=2.20->yfinance==0.1.67) (2.
0.12)
Requirement already satisfied: pandas==1.3.3 in c:\users\admin\anaconda3
\lib\site-packages (1.3.3)

Requirement already satisfied: pytz>=2017.3 in c:\users\admin\anaconda3\l


ib\site-packages (from pandas==1.3.3) (2021.1)

Requirement already satisfied: python-dateutil>=2.7.3 in c:\users\admin\a


naconda3\lib\site-packages (from pandas==1.3.3) (2.8.1)

Requirement already satisfied: numpy>=1.17.3 in c:\users\admin\anaconda3


\lib\site-packages (from pandas==1.3.3) (1.20.1)

Requirement already satisfied: six>=1.5 in c:\users\admin\anaconda3\lib\s


ite-packages (from python-dateutil>=2.7.3->pandas==1.3.3) (1.15.0)

In [40]: import yfinance as yf

import pandas as pd

In [41]: tesla = yf.Ticker("TSLA")

In [42]: tesla_info=tesla.info

tesla_info

Out[42]: {'zip': '78725',

'sector': 'Consumer Cyclical',

'fullTimeEmployees': 99290,

'longBusinessSummary': 'Tesla, Inc. designs, develops, manufactures, lea


ses, and sells electric vehicles, and energy generation and storage syste
ms in the United States, China, and internationally. The company operates
in two segments, Automotive, and Energy Generation and Storage. The Autom
otive segment offers electric vehicles, as well as sells automotive regul
atory credits. It provides sedans and sport utility vehicles through dire
ct and used vehicle sales, a network of Tesla Superchargers, and in-app u
pgrades; and purchase financing and leasing services. This segment is als
o involved in the provision of non-warranty after-sales vehicle services,
sale of used vehicles, retail merchandise, and vehicle insurance, as well
as sale of products to third party customers; services for electric vehic
les through its company-owned service locations, and Tesla mobile service
technicians; and vehicle limited warranties and extended service plans. T
he Energy Generation and Storage segment engages in the design, manufactu
re, installation, sale, and leasing of solar energy generation and energy
storage products, and related services to residential, commercial, and in
dustrial customers and utilities through its website, stores, and galleri
es, as well as through a network of channel partners. This segment also o
ffers service and repairs to its energy product customers, including unde
r warranty; and various financing options to its solar customers. The com
pany was formerly known as Tesla Motors, Inc. and changed its name to Tes
la, Inc. in February 2017. Tesla, Inc. was incorporated in 2003 and is he
adquartered in Austin, Texas.',

'city': 'Austin',

'phone': '(512) 516-8177',

'state': 'TX',

'country': 'United States',

'companyOfficers': [],

'website': 'https://www.tesla.com',

'maxAge': 1,

'address1': '13101 Tesla Road',

'industry': 'Auto Manufacturers',

'ebitdaMargins': 0.1734,

'profitMargins': 0.102539994,

'grossMargins': 0.25279,

'operatingCashflow': 11496999936,

'revenueGrowth': 0.649,

'operatingMargins': 0.121190004,

'ebitda': 9333000192,

'targetLowPrice': 250,

'recommendationKey': 'hold',

'grossProfits': 13606000000,

'freeCashflow': 4628125184,

'targetMedianPrice': 1035,

'currentPrice': 922.43,

'earningsGrowth': 7.538,

'currentRatio': 1.375,

'returnOnAssets': 0.07135,

'numberOfAnalystOpinions': 36,

'targetMeanPrice': 965.99,

'debtToEquity': 28.192,

'returnOnEquity': 0.20426,

'targetHighPrice': 1480,

'totalCash': 17706999808,

'totalDebt': 8903999488,

'totalRevenue': 53823000576,

'totalCashPerShare': 17.133,

'financialCurrency': 'USD',

'revenuePerShare': 54.587,

'quickRatio': 0.999,

'recommendationMean': 2.6,

'exchange': 'NMS',

'shortName': 'Tesla, Inc.',

'longName': 'Tesla, Inc.',

'exchangeTimezoneName': 'America/New_York',

'exchangeTimezoneShortName': 'EST',

'isEsgPopulated': False,

'gmtOffSetMilliseconds': '-18000000',

'quoteType': 'EQUITY',

'symbol': 'TSLA',

'messageBoardId': 'finmb_27444752',

'market': 'us_market',

'annualHoldingsTurnover': None,

'enterpriseToRevenue': 16.679,

'beta3Year': None,

'enterpriseToEbitda': 96.185,

'52WeekChange': 0.09723735,

'morningStarRiskRating': None,

'forwardEps': 12.54,

'revenueQuarterlyGrowth': None,

'sharesOutstanding': 1033510016,

'fundInceptionDate': None,

'annualReportExpenseRatio': None,

'totalAssets': None,

'bookValue': 29.225,

'sharesShort': 24057278,

'sharesPercentSharesOut': 0.0233,

'fundFamily': None,

'lastFiscalYearEnd': 1640908800,

'heldPercentInstitutions': 0.4253,

'netIncomeToCommon': 5523999744,

'trailingEps': 4.901,

'lastDividendValue': None,

'SandP52WeekChange': 0.11963892,

'priceToBook': 31.563046,

'heldPercentInsiders': 0.19393998,

'nextFiscalYearEnd': 1703980800,

'yield': None,

'mostRecentQuarter': 1640908800,

'shortRatio': 0.77,

'sharesShortPreviousMonthDate': 1640908800,

'floatShares': 838195343,

'beta': 2.006464,

'enterpriseValue': 897695612928,

'priceHint': 2,

'threeYearAverageReturn': None,

'lastSplitDate': 1598832000,

'lastSplitFactor': '5:1',

'legalType': None,

'lastDividendDate': None,

'morningStarOverallRating': None,

'earningsQuarterlyGrowth': 7.596,

'priceToSalesTrailing12Months': 17.712515,

'dateShortInterest': 1643587200,

'pegRatio': 3.93,

'ytdReturn': None,

'forwardPE': 73.55901,

'lastCapGain': None,

'shortPercentOfFloat': 0.028399998,

'sharesShortPriorMonth': 22471754,

'impliedSharesOutstanding': 0,

'category': None,

'fiveYearAverageReturn': None,

'previousClose': 875.76,

'regularMarketOpen': 900,

'twoHundredDayAverage': 824.8434,

'trailingAnnualDividendYield': 0,

'payoutRatio': 0,

'volume24Hr': None,

'regularMarketDayHigh': 923,

'navPrice': None,

'averageDailyVolume10Day': 22318300,

'regularMarketPreviousClose': 875.76,

'fiftyDayAverage': 989.8474,

'trailingAnnualDividendRate': 0,

'open': 900,

'toCurrency': None,

'averageVolume10days': 22318300,

'expireDate': None,

'algorithm': None,

'dividendRate': None,

'exDividendDate': None,

'circulatingSupply': None,

'startDate': None,

'regularMarketDayLow': 893.3774,

'currency': 'USD',

'trailingPE': 188.2126,

'regularMarketVolume': 19216514,

'lastMarket': None,

'maxSupply': None,

'openInterest': None,

'marketCap': 953340657664,

'volumeAllCurrencies': None,

'strikePrice': None,

'averageVolume': 26157834,

'dayLow': 893.3774,

'ask': 0,
'askSize': 2200,

'volume': 19216514,

'fiftyTwoWeekHigh': 1243.49,

'fromCurrency': None,

'fiveYearAvgDividendYield': None,

'fiftyTwoWeekLow': 539.49,

'bid': 0,
'tradeable': False,

'dividendYield': None,

'bidSize': 1000,

'dayHigh': 923,

'regularMarketPrice': 922.43,

'preMarketPrice': None,

'logo_url': 'https://logo.clearbit.com/tesla.com'}

In [43]: tesla_data = tesla.history(period="max")

In [45]: tesla_data.reset_index(inplace=True)

In [46]: tesla_data.head()

Out[46]: index Date Open High Low Close Volume Dividends Stock Splits

0 0 2010-06-29 3.800 5.000 3.508 4.778 93831500 0 0.0

1 1 2010-06-30 5.158 6.084 4.660 4.766 85935500 0 0.0

2 2 2010-07-01 5.000 5.184 4.054 4.392 41094000 0 0.0

3 3 2010-07-02 4.600 4.620 3.742 3.840 25699000 0 0.0

4 4 2010-07-06 4.000 4.000 3.166 3.222 34334500 0 0.0

In [47]: tesla_revenue.tail()

Out[47]: Date Revenue

46 2010-03-31 21

47 2009-12-31

48 2009-09-30 46

49 2009-06-30 27

50 2008-12-31
!pip install requests==2.26.0

In [58]:
!mamba install bs4==4.10.0 -y

!mamba install html5lib==1.1 -y

!pip install lxml==4.6.4

!pip install plotly==5.3.1

import plotly.graph_objects as go

from plotly.subplots import make_subplots


#Define Graphing Function

def make_graph(stock_data, revenue_data, stock):

fig = make_subplots(rows=2, cols=1, shared_xaxes=True, subplot_title


fig.add_trace(go.Scatter(x=pd.to_datetime(stock_data.Date, infer_date
fig.add_trace(go.Scatter(x=pd.to_datetime(revenue_data.Date, infer_da
fig.update_xaxes(title_text="Date", row=1, col=1)

fig.update_xaxes(title_text="Date", row=2, col=1)

fig.update_yaxes(title_text="Price ($US)", row=1, col=1)

fig.update_yaxes(title_text="Revenue ($US Millions)", row=2, col=1)

fig.update_layout(showlegend=False,

height=900,

title=stock,

xaxis_rangeslider_visible=True)

fig.show()

Requirement already satisfied: requests==2.26.0 in c:\users\admin\anacond


a3\lib\site-packages (2.26.0)

Requirement already satisfied: certifi>=2017.4.17 in c:\users\admin\anaco


nda3\lib\site-packages (from requests==2.26.0) (2020.12.5)

Requirement already satisfied: charset-normalizer~=2.0.0 in c:\users\admi


n\anaconda3\lib\site-packages (from requests==2.26.0) (2.0.12)

Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\users\admin\an


aconda3\lib\site-packages (from requests==2.26.0) (1.26.4)

Requirement already satisfied: idna<4,>=2.5 in c:\users\admin\anaconda3\l


ib\site-packages (from requests==2.26.0) (2.10)

"mamba" Ґ
­ пў«пҐвбп ў­
гв७Ґ© Ё«Ё ў­
­ Ґи­
Ґ©

Є®¬ ­
¤®©, ЁбЇ®«­
塞®© Їа®Ја ¬¬®© Ё«Ё Ї ЄҐв­
л¬ д ©«®¬.

"mamba" Ґ
­ пў«пҐвбп ў­
гв७Ґ© Ё«Ё ў­
­ Ґи­
Ґ©

Є®¬ ­
¤®©, ЁбЇ®«­
塞®© Їа®Ја ¬¬®© Ё«Ё Ї ЄҐв­
л¬ д ©«®¬.

Requirement already satisfied: lxml==4.6.4 in c:\users\admin\anaconda3\li


b\site-packages (4.6.4)

Requirement already satisfied: plotly==5.3.1 in c:\users\admin\anaconda3


\lib\site-packages (5.3.1)

Requirement already satisfied: tenacity>=6.2.0 in c:\users\admin\anaconda


3\lib\site-packages (from plotly==5.3.1) (8.0.1)

Requirement already satisfied: six in c:\users\admin\anaconda3\lib\site-p


ackages (from plotly==5.3.1) (1.15.0)

In [33]: import pandas as pd

import requests

from bs4 import BeautifulSoup

In [34]: tesla_url = "https://www.macrotrends.net/stocks/charts/TSLA/tesla/revenue


tesla_data = requests.get(tesla_url).text

In [35]: tesla_soup = BeautifulSoup(tesla_data, 'html5lib')

In [36]: tesla_tables = tesla_soup.find_all('table')

for index,table in enumerate(tesla_tables):

if ("Tesla Quarterly Revenue" in str(table)):

tesla_table_index = index

tesla_revenue = pd.DataFrame(columns=["Date", "Revenue"])

for row in tesla_tables[tesla_table_index].tbody.find_all("tr"):

col = row.find_all("td")

if (col !=[]):

date = col[0].text

revenue = col[1].text.replace("$", "").replace(",", "")

tesla_revenue = tesla_revenue.append({"Date" : date, "Revenue" :

In [37]: tesla_revenue.tail()

Out[37]: Date Revenue

46 2010-03-31 21

47 2009-12-31

48 2009-09-30 46

49 2009-06-30 27

50 2008-12-31

In [4]: GameStop = yf.Ticker("GME")

In [5]: GameStop_info=GameStop.info

GameStop_info

Out[5]: {'zip': '76051',

'sector': 'Consumer Cyclical',

'fullTimeEmployees': 12000,

'longBusinessSummary': 'GameStop Corp., a specialty retailer, provides g


ames and entertainment products through its e-commerce properties and var
ious stores in the United States, Canada, Australia, and Europe. The comp
any sells new and pre-owned video game platforms; accessories, such as co
ntrollers, gaming headsets, virtual reality products, and memory cards; n
ew and pre-owned video game software; and in-game digital currency, digit
al downloadable content, and full-game downloads, as well as network poin
ts cards, and prepaid digital and subscription cards. It also sells colle
ctibles comprising licensed merchandise primarily related to the video ga
me, television, and movie industries, as well as pop culture themes. The
company operates its stores and e-commerce sites under the GameStop, EB G
ames, and Micromania brands; and collectibles stores under the Zing Pop C
ulture and ThinkGeek brand, as well as offers Game Informer, a print and
digital video game publication featuring reviews of new title releases, g
ame tips, and news regarding the video game industry. As of January 30, 2
021, it operated 4,816 stores. The company was formerly known as GSC Hold
ings Corp. GameStop Corp. was founded in 1996 and is headquartered in Gra
pevine, Texas.',

'city': 'Grapevine',

'phone': '817 424 2000',

'state': 'TX',

'country': 'United States',

'companyOfficers': [],

'website': 'https://www.gamestop.com',

'maxAge': 1,

'address1': '625 Westport Parkway',

'industry': 'Specialty Retail',

'ebitdaMargins': -0.01626,

'profitMargins': -0.026080001,

'grossMargins': 0.24123,

'operatingCashflow': -159200000,

'revenueGrowth': 0.291,

'operatingMargins': -0.02864,

'ebitda': -95600000,

'targetLowPrice': 23,

'recommendationKey': 'underperform',

'grossProfits': 1259500000,

'freeCashflow': -168137504,

'targetMedianPrice': 45,

'currentPrice': 126.16,

'earningsGrowth': None,

'currentRatio': 1.9,

'returnOnAssets': -0.03308,

'numberOfAnalystOpinions': 3,

'targetMeanPrice': 56,

'debtToEquity': 38.053,

'returnOnEquity': -0.14709,

'targetHighPrice': 100,

'totalCash': 1412999936,

'totalDebt': 667800000,

'totalRevenue': 5878900224,

'totalCashPerShare': 18.604,

'financialCurrency': 'USD',

'revenuePerShare': 84.044,

'quickRatio': 1.079,

'recommendationMean': 4,

'exchange': 'NYQ',

'shortName': 'GameStop Corporation',

'longName': 'GameStop Corp.',

'exchangeTimezoneName': 'America/New_York',

'exchangeTimezoneShortName': 'EST',

'isEsgPopulated': False,

'gmtOffSetMilliseconds': '-18000000',

'quoteType': 'EQUITY',

'symbol': 'GME',

'messageBoardId': 'finmb_1342560',

'market': 'us_market',

'annualHoldingsTurnover': None,

'enterpriseToRevenue': 1.386,

'beta3Year': None,

'enterpriseToEbitda': -85.229,

'52WeekChange': 1.5487592,

'morningStarRiskRating': None,

'forwardEps': -0.8,

'revenueQuarterlyGrowth': None,

'sharesOutstanding': 76350800,

'fundInceptionDate': None,

'annualReportExpenseRatio': None,

'totalAssets': None,

'bookValue': 23.244,

'sharesShort': 10998384,

'sharesPercentSharesOut': 0.1441,

'fundFamily': None,

'lastFiscalYearEnd': 1611964800,

'heldPercentInstitutions': 0.28236,

'netIncomeToCommon': -153500000,

'trailingEps': -2.194,

'lastDividendValue': 0.38,

'SandP52WeekChange': 0.11963892,

'priceToBook': 5.4276376,

'heldPercentInsiders': 0.18014999,

'nextFiscalYearEnd': 1675036800,

'yield': None,

'mostRecentQuarter': 1635552000,

'shortRatio': 2.68,

'sharesShortPreviousMonthDate': 1640908800,

'floatShares': 62843955,

'beta': -1.633018,

'enterpriseValue': 8147876864,

'priceHint': 2,

'threeYearAverageReturn': None,

'lastSplitDate': 1174262400,

'lastSplitFactor': '2:1',

'legalType': None,

'lastDividendDate': 1552521600,

'morningStarOverallRating': None,

'earningsQuarterlyGrowth': None,

'priceToSalesTrailing12Months': 1.6384726,

'dateShortInterest': 1643587200,

'pegRatio': 1.51,

'ytdReturn': None,

'forwardPE': -157.7,

'lastCapGain': None,

'shortPercentOfFloat': 0.23709999,

'sharesShortPriorMonth': 8449995,

'impliedSharesOutstanding': 0,

'category': None,

'fiveYearAverageReturn': None,

'previousClose': 117.09,

'regularMarketOpen': 120.96,

'twoHundredDayAverage': 177.7728,

'trailingAnnualDividendYield': 0,

'payoutRatio': 0,

'volume24Hr': None,

'regularMarketDayHigh': 127.2299,

'navPrice': None,

'averageDailyVolume10Day': 3070940,

'regularMarketPreviousClose': 117.09,

'fiftyDayAverage': 131.8536,

'trailingAnnualDividendRate': 0,

'open': 120.96,

'toCurrency': None,

'averageVolume10days': 3070940,

'expireDate': None,

'algorithm': None,

'dividendRate': None,

'exDividendDate': 1552521600,

'circulatingSupply': None,

'startDate': None,

'regularMarketDayLow': 119.26,

'currency': 'USD',

'regularMarketVolume': 1950844,

'lastMarket': None,

'maxSupply': None,

'openInterest': None,

'marketCap': 9632416768,

'volumeAllCurrencies': None,

'strikePrice': None,

'averageVolume': 3168454,

'dayLow': 119.26,

'ask': 0,
'askSize': 1200,

'volume': 1950844,

'fiftyTwoWeekHigh': 348.5,

'fromCurrency': None,

'fiveYearAvgDividendYield': None,

'fiftyTwoWeekLow': 38.5,

'bid': 0,
'tradeable': False,

'dividendYield': None,

'bidSize': 1100,

'dayHigh': 127.2299,

'regularMarketPrice': 126.16,

'preMarketPrice': None,

'logo_url': 'https://logo.clearbit.com/gamestop.com'}
In [6]: GameStop_data = GameStop.history(period="max")

In [7]: GameStop_data.reset_index(inplace=True)

In [8]: GameStop_data.head()

Out[8]: Date Open High Low Close Volume Dividends


Stock
Splits

2002-02-
0 6.480513 6.773399 6.413183 6.766666 19054000 0.0 0.0
13

2002-02-
1 6.850829 6.864295 6.682504 6.733002 2755400 0.0 0.0
14

2002-02-
2 6.733001 6.749833 6.632006 6.699336 2097400 0.0 0.0
15

2002-02-
3 6.665672 6.665672 6.312190 6.430017 1852600 0.0 0.0
19

2002-02-
4 6.463682 6.648839 6.413184 6.648839 1723200 0.0 0.0
20

In [15]: GameStop_url = "https://www.macrotrends.net/stocks/charts/GME/gamestop/re


GameStop_data = requests.get(GameStop_url).text

In [17]: GameStop_soup = BeautifulSoup(GameStop_data, 'html5lib')

In [19]: GameStop_tables = GameStop_soup.find_all('table')

for index,table in enumerate(GameStop_tables):

if ("GameStop Quarterly Revenue" in str(table)):

GameStop_table_index = index

GameStop_revenue = pd.DataFrame(columns=["Date", "Revenue"])

for row in GameStop_tables[GameStop_table_index].tbody.find_all("tr"):

col = row.find_all("td")

if (col !=[]):

date = col[0].text

revenue = col[1].text.replace("$", "").replace(",", "")

GameStop_revenue = GameStop_revenue.append({"Date" : date, "Reven

In [20]: GameStop_revenue.tail()

Out[20]: Date Revenue

63 2006-01-31 1667

64 2005-10-31 534

65 2005-07-31 416

66 2005-04-30 475

67 2005-01-31 709
In [52]: tesla_url = "https://www.macrotrends.net/stocks/charts/TSLA/tesla/revenue
tesla_data = requests.get(tesla_url).text

In [53]: tesla_soup = BeautifulSoup(tesla_data, 'html5lib')

In [54]: tesla_tables = tesla_soup.find_all('table')

for index,table in enumerate(tesla_tables):

if ("Tesla Quarterly Revenue" in str(table)):

tesla_table_index = index

tesla_revenue = pd.DataFrame(columns=["Date", "Revenue"])

for row in tesla_tables[tesla_table_index].tbody.find_all("tr"):

col = row.find_all("td")

if (col !=[]):

date = col[0].text

revenue = col[1].text.replace("$", "").replace(",", "")

tesla_revenue = tesla_revenue.append({"Date" : date, "Revenue" :

In [55]: tesla_revenue.tail()

Out[55]: Date Revenue

46 2010-03-31 21

47 2009-12-31

48 2009-09-30 46

49 2009-06-30 27

50 2008-12-31

In [72]: import pandas as pd

import requests

from bs4 import BeautifulSoup

import plotly.graph_objects as go

from plotly.subplots import make_subplots

In [61]: tesla_price_data = tesla.history(period="max")

In [62]: tesla_price_data.head()

Out[62]: Open High Low Close Volume Dividends Stock Splits

Date

2010-06-29 3.800 5.000 3.508 4.778 93831500 0 0.0

2010-06-30 5.158 6.084 4.660 4.766 85935500 0 0.0

2010-07-01 5.000 5.184 4.054 4.392 41094000 0 0.0

2010-07-02 4.600 4.620 3.742 3.840 25699000 0 0.0


2010-07-06 4.000 4.000 3.166 3.222 34334500 0 0.0

In [63]: tesla_price_data.reset_index(inplace=True)

In [64]: tesla_price_data.plot(x="Date", y="Open")

Out[64]: <AxesSubplot:xlabel='Date'>

In [77]: tesla_url = "https://www.macrotrends.net/stocks/charts/TSLA/tesla/revenue


tesla_data = requests.get(tesla_url).text

In [78]: tesla_soup = BeautifulSoup(tesla_data, 'html5lib')

In [80]: tesla_tables = tesla_soup.find_all('table')

for index,table in enumerate(tesla_tables):

if ("Tesla Quarterly Revenue" in str(table)):

tesla_table_index = index

tesla_revenue = pd.DataFrame(columns=["Date", "Revenue"])

for row in tesla_tables[tesla_table_index].tbody.find_all("tr"):

col = row.find_all("td")

if (col !=[]):

date = col[0].text

revenue = col[1].text.replace("$", "").replace(",", "")

tesla_revenue = tesla_revenue.append({"Date" : date, "Revenue" :

In [70]: tesla_revenue.tail()

Out[70]: Date Revenue

46 2010-03-31 21

47 2009-12-31

48 2009-09-30 46

49 2009-06-30 27
50 2008-12-31

In [81]: import plotly.graph_objects as go

from plotly.subplots import make_subplots


import yfinance as yf

import pandas as pd

stock_data = yf.download("TSLA", start="2020-01-01", end="2021-09-30", pr


revenue_data = yf.download("TSLA", start="2020-01-01", end="2021-09-30",
stock_data.reset_index(inplace=True)

revenue_data.reset_index(inplace=True)

def make_graph(stock_data, revenue_data, stock):

fig = make_subplots(rows=2, cols=1,

shared_xaxes=True,

subplot_titles=("Historical Share Price", "Histor


vertical_spacing=.3)

stock_data_specific = stock_data[stock_data.Date <= '2021-06-14']

revenue_data_specific = revenue_data[revenue_data.Date <= '2021-04-3


fig.add_trace(go.Scatter(

x=pd.to_datetime(stock_data_specific.Date, infer_datetime_format=
y=stock_data_specific.Close.astype("float"), name="Share Price")

fig.add_trace(go.Scatter(x=pd.to_datetime(revenue_data_specific.Date
y=revenue_data_specific.Volume.astype("float
name="Volume"), row=2, col=1)

fig.update_xaxes(title_text="Date", row=1, col=1)

fig.update_xaxes(title_text="Date", row=2, col=1)

fig.update_yaxes(title_text="Price ($US)", row=1, col=1)

fig.update_yaxes(title_text="Revenue ($US Millions)", row=2, col=1)

fig.update_layout(showlegend=False,

height=900,

title=stock,

xaxis_rangeslider_visible=True)

fig.show()

make_graph(stock_data, revenue_data, 'TSLA')

In [82]: import plotly.graph_objects as go

from plotly.subplots import make_subplots


import yfinance as yf

import pandas as pd

stock_data = yf.download("GME", start="2020-01-01", end="2021-09-30", pro


revenue_data = yf.download("GME", start="2020-01-01", end="2021-09-30", p
stock_data.reset_index(inplace=True)

revenue_data.reset_index(inplace=True)

def make_graph(stock_data, revenue_data, stock):

fig = make_subplots(rows=2, cols=1,

shared_xaxes=True,

subplot_titles=("Historical Share Price", "Histor


vertical_spacing=.3)

stock_data_specific = stock_data[stock_data.Date <= '2021-06-14']

revenue_data_specific = revenue_data[revenue_data.Date <= '2021-04-3


fig.add_trace(go.Scatter(

x=pd.to_datetime(stock_data_specific.Date, infer_datetime_format=
y=stock_data_specific.Close.astype("float"), name="Share Price")

fig.add_trace(go.Scatter(x=pd.to_datetime(revenue_data_specific.Date
y=revenue_data_specific.Volume.astype("float
name="Volume"), row=2, col=1)

fig.update_xaxes(title_text="Date", row=1, col=1)

fig.update_xaxes(title_text="Date", row=2, col=1)

fig.update_yaxes(title_text="Price ($US)", row=1, col=1)

fig.update_yaxes(title_text="Revenue ($US Millions)", row=2, col=1)

fig.update_layout(showlegend=False,

height=900,

title=stock,

xaxis_rangeslider_visible=True)

fig.show()

make_graph(stock_data, revenue_data, 'GME')

In [ ]:

You might also like