I try to get ttm values of the income statement for ticker symbol AAPL by using
from yahoo_fin import stock_info as si
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import pandas_datareader
pd.set_option('display.max_columns', None)
income_statement = si.get_income_statement("aapl")
income_statement
but the result doesn't show the ttm values, only the yearly values are shown
On yahoo finance, we can also see the ttm values:
Anyone who can help?
The reason you don't get the exact same table you see on the website is because of the way yahoo_fin gets data from Yahoo. Rather than getting them from the table you see, they get them from json data that Yahoo provides. In this data, there are both quarterly and yearly income statements. When Yahoo renders the table on their website, they most likely use the yearly data for the yearly columns and then sum the last 4 quarterly results to get the TTM column (as TTM results are nothing else than the sum of the last 4 quarterly results).
If you want to get the TTM data, the best approach would be to do it the same way I assume Yahoo does. Get the quarterly data using yahoo_fin and then sum the quarters to calculate the TTM results. You can do this by setting the optional yearly parameter to False:
quarterly_income_statement = si.get_income_statement("aapl", yearly=False)
You can check out their method _parse_json to better understand how they get and parse data from Yahoo. (Assuming you have some knowledge of requests and json.)
Summing the data
To get the sum of the quarters you can for example do this:
quarterly_income_statement = si.get_income_statement("aapl", yearly=False)
ttm = quarterly_income_statement.sum(axis=1)
This will give you a new Dataframe ttm with the same data fields with values being TTM (You can test it and see if it matches the numbers on the website).
Related
I am new to python and exploring to get data from yahoo fin for dividends but the date on the list is the announcement date not the required payment date. Can the date listed be changed by adding extra days which would be variable for different companies.
import yahoo_fin.stock_info as si
import pandas as pd
si.get_data("WBC.AX",start_date="3/02/1992", end_date="13/10/2022")
si.get_dividends("wbc.ax")
df = pd.DataFrame(div)
df.to_excel('WBC_Div.xlsx', startcol=4, startrow=12)
dividend ticker
1988-06-10 0.124664 WBC.AX
1989-01-01 0.099731 WBC.AX
1989-06-05 0.069522 WBC.AX
1989-12-27 0.274260 WBC.AX
1990-06-07 0.249328 WBC.AX
As I have got this far and have no idea how to make the date change by adding a number of days to the date listed prior sending to excel or do I have to change in excel?
I'm pulling data from google trends ,encountering some issues:
code:
import pandas as pd
from pytrends.request import TrensReq
pytrends=TrendReq()
kw_list= ['Solar power','Starlink']
df1=pytrends.build(kw_list,timeframe='today 100-w',geo='US','UK')
df1=pytrends.interest_by_region(),pytrends.interest_over_time()
df1.to_excel(r'e:\google trends\putout.xlsx')
i want data for 2 regions- US and UK .but it is not working .
also i want data for past 100 weeks from today's date.I checked on google to see what is the syntax
for looking in past weeks but no help.
Also if i use " pytrends.interest_by_region(),pytrends.interest_over_time()", i get data like:
solar power Starlink
date
But country column is not included.I have used pytrends.interest_by_region() but it is not coming in my dataframe.
Expected output:
solar power Starlink
country date
US 2021-05-01 5 4
UK 2021-05-01 4 5
....so on. Let me know how to get both country and date in the dataset.
and
And finally export it to csv or excel file.
Check this code, this will give result in required format:
import pandas as pd
from pytrends.request import TrendReq
kw_list= ['Solar power','Starlink']
l = []
for i in ['US','GB']:
pytrends=TrendReq()
pytrends.build_payload(kw_list,timeframe='today 3-m',geo=i)
df=pytrends.interest_over_time()
df['country']=i
l.append(df.reset_index())
df1 = pd.concat(l)
df1.to_excel(r'e:\google trends\putout.xlsx')
Following changes I did in your current code:
For timeframe, pytrends provide only few options and "today 100-w" is not one of them
Current Time Minus Time Pattern:
By Month: 'today #-m' where # is the number of months from that date to pull data for, only work for 1, 2, 3 months
Daily: 'now #-d' where # is the number of days from that date to pull data for,
only work for 1, 7 days
Hourly: 'now #-H' where # is the number of hours from that date to pull data for, only work for 1, 4 hours
I suggest for specific dates, use 'YYYY-MM-DD YYYY-MM-DD' example '2016-12-14 2017-01-25'
You can not provide list to geo parameter, it should be string of country code, For United kingdom the code is 'GB'(Refer this link: Country json, This will give you the json of all google trends supported countries and its respective codes)
I am using yahooquery to download historical data for APPL
When I print the results I can see there is the Date alongside the price. However when I download the result in a csv file the date is no longer available.
As I would need to also have the date for the price I am wondering if I am doing anything wrong and if so how can I fix it
from yahooquery import Ticker
import numpy as np
aapl = Ticker('APPL')
price = aapl.history(period='max')
np.savetxt('C:\APPL.csv', price)
Yahooquery uses multiple index, so you should reset it to single index.
Use
price = price.reset_index(level=[0,1])
This will tranform the symbol column into index and the date column into first column
I am trying to download data from Yahoo Finance and I have the following code to accomplish this; the code works well.
import pandas as pd
from pandas_datareader import data as pdr
ticker=['CBRL','DRI','MSFT']
start_date = '2015-01-01'
end_date = '2016-06-30'
data=pd.DataFrame()
for x in ticker:
panel_data = pdr.DataReader(x, 'yahoo', start_date, end_date)
data = data.append(panel_data)
My only problem is that the above doesn't retain the stock identifiers, ie once I have all data in one dataframe, I can't which ticker symbol each series corresponds to. I have tried using panel_data.to_frame() after running all of the above, but nothing changes. I am still stuck with all the data, but no ticker identifiers for each of my rows. Can I please have someone's thoughts?
I want to use look ups for any online index, including those with digits. A random example is:
https://uk.finance.yahoo.com/quote/YSM6.AX/futures?p=YSM6.AX
A naive method is to use pandas-datareader:
from pandas_datareader import data as datareader
online_data = datareader.DataReader('YSM6.AX', 'yahoo', start, end)
However, this doesn't work. I think the digits in the ticker aren't handled properly. This command works fine with e.g. "AAPL".
How do I get this to work for any index?
The YSM6.AX link shows that there is no data for this stock.
If you want to grab multiple stock, and get specifically the adjusted close, you can use this code. It takes into account any funny stock tickers that have either a "-", or in the case of YSM6.AX, a "." inside the ticker.
import pandas as pd
import datetime
from pandas_datareader import data, wb
tickers = ["BRK.B", "AAPL", "MSFT", "YHOO", "JPM"]
series_list = []
start = datetime.datetime(2012, 4, 5)
end = datetime.datetime(2017, 3, 28)
for security in tickers:
s = data.DataReader(security.replace(".","-"),"yahoo",start, end )["Adj Close"]
s.name = security
series_list.append(s)
df = pd.concat(series_list, axis=1)
stocks= pd.DataFrame(df)
stocks
If you look at the link you have provided, YSM6 is a futures contract on ASX. Specifically it is the M6 expiry, meaning 2016-06. And Yahoo has no data for this contract on their site anymore--perhaps because it is expired, or perhaps because there was never any data available for it. Furthermore, this product (3 year AU interest rate swap futures) seems to have been discontinued by the exchange.
Your question says you want "stock" data. Here's an example of an actual stock with a numeric symbol:
https://uk.finance.yahoo.com/quote/7203.KL/?p=7203.KL