Giter Club home page Giter Club logo

financetoolkit's People

Contributors

alberthaoh avatar dependabot[bot] avatar jerbouma avatar kianmeng avatar northern-64bit avatar sword134 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

financetoolkit's Issues

earnings_calendar doesn't work

Hi, how do I access earnings_calendar?

AttributeError: module 'FundamentalAnalysis' has no attribute 'earnings_calendar'

problem when fetching DCF with certain companies

Hi,

In FundamentalAnalysis\fundamentalanalysis\details.py, in function discounted_cash_flow(), we first try to fetch the data by calling
data_json = data[0]['historicalDCF'].
If a keyError is raised because 'historicalDCF' doesn't exist, we retry again by calling
data_json = data[0].
This is where the error is, we should instead just call data_json = data.

A test case is with the company ticker "BESI.AS".

Best regards

Bug DCF

Hey guys,

thanks for this neat package! Srly tho, I have to report a bug.
Not sure if it only affects me, however I checked with the API and it works.
So i figured it has to be some bug in the package:

If I do

dcf_annually = fa.discounted_cash_flow("XXX", api_key, period="annual")

i get:

KeyError                                  
discounted_cash_flow(ticker, api_key, period, limit)
    246 if 'Error Message' in data:
    247     raise ValueError(data['Error Message'])
--> 249 data_json = data[0]['historicalDCF']
    251 data_formatted = {}
    253 if period == "quarter":

KeyError: 'historicalDCF'

This occurred for many companies. Could you fix it, if it is related to the package or
otherwise give me some hints, what might have caused this error?

Best regards
Chris

the calculation of quarterly evToSales

Hello, I found a mistake in the formula of quarterly evToSales. It seems that you directly use EV/quarterly revenue, which makes the ratio about 4 times larger because the denominator should be an annual term. Usually we use LTM (last twelve months) revenue.

[IMPROVE] get_income_statement returns inaccurate results

Hi! I have been validating get_free_cash_flow_yield ratio and can see that for some tickers it is not accurate.

Example:

If i try to get ratio for HYMTF in the following way:

companies = Toolkit(
	tickers=tickers, 
	api_key=FMP_KEY, 
	start_date="2019-12-21",
	quarterly=False,
	# historical_source='YahooFinance',
)
print(companies.ratios.get_free_cash_flow_yield())

the result is:

date       2019      2020      2021     2022
HYMTF -294.1981 -298.0033 -330.6268 411.7727

but it cannot be larger than 1, right?

looking at the income statements, the Weighted Average Shares seems to be incorrect:

date                                                  2019          2020          2021           2022
Revenue                                      95171779800.0 93597840900.0 94088500800.0 114022028000.0
Cost of Goods Sold                           79282268100.0 76964337900.0 76544104800.0  91367586400.0
Gross Profit                                 15889511700.0 16633503000.0 17544396000.0  22654441600.0
Gross Profit Ratio                                  0.0002        0.0002        0.0001         0.0002
Research and Development Expenses             1160743500.0  1204084800.0  1227994400.0   1410199200.0
General and Administrative Expenses           1350061200.0  1304637300.0  1212272800.0   1663864800.0
Selling and Marketing Expenses                7141083300.0  8966731500.0  6915793600.0   8532795200.0
Selling, General and Administrative Expenses  8491144500.0 10271368800.0  8128066400.0  10196660000.0
Other Expenses                                2992669200.0  3002845500.0  2845176000.0   3191767200.0
Operating Expenses                           12644557200.0 14478299100.0 12201236800.0  14798626400.0
Cost and Expenses                            91926825300.0 91442637000.0 88745341600.0 106166212800.0
Interest Income                                461336400.0   361212300.0   278890400.0    511373600.0
Interest Expense                               285281100.0   326139300.0   243633600.0    428868800.0
Depreciation and Amortization                 4357631700.0  3975313500.0  4926842400.0   5547491200.0
EBITDA                                        7602586200.0  6130517400.0 10270001600.0  13403306400.0
EBITDA Ratio                                        0.0001        0.0001        0.0001         0.0001
Operating Income                              3244954500.0  2155203900.0  5343159200.0   7855815200.0
Operating Income Ratio                                 0.0           0.0           0.0         0.0001
Total Other Income                             502434900.0  -271273500.0  1024490400.0    902539200.0
Income Before Tax                             3747389400.0  1883930400.0  6367649600.0   8758354400.0
Income Before Tax Ratio                                0.0           0.0        0.0001         0.0001
Income Tax Expense                             880308000.0   151832700.0  1813188000.0   2371463200.0
Net Income                                    2682044100.0  1732097700.0  3953884800.0   5891491200.0
Net Income Ratio                                       0.0           0.0           0.0            0.0
EPS                                                 5.0895         3.316        7.5916        11.4084
EPS Diluted                                         5.0895         3.316        7.5916        11.4084
Weighted Average Shares                         474278.355   470110.8915   416658.9176    319576.4128
Weighted Average Shares Diluted                 474278.355   470110.8915   416658.9176    319576.4128

while directly querying FMP endpoint https://financialmodelingprep.com/api/v3/income-statement/HYMTF gives more reasonable results at least for share count:

  {
    "date": "2022-12-31",
    "symbol": "HYMTF",
    "reportedCurrency": "KRW",
    "cik": "0000000000",
    "fillingDate": "2022-12-31",
    "acceptedDate": "2022-12-31 00:00:00",
    "calendarYear": "2022",
    "period": "FY",
    "revenue": 142527535000000,
    "costOfRevenue": 114209483000000,
    "grossProfit": 28318052000000,
    "grossProfitRatio": 0.1986847805,
    "researchAndDevelopmentExpenses": 1762749000000,
    "generalAndAdministrativeExpenses": 2079831000000,
    "sellingAndMarketingExpenses": 10665994000000,
    "sellingGeneralAndAdministrativeExpenses": 12745825000000,
    "otherExpenses": 3989709000000,
    "operatingExpenses": 18498283000000,
    "costAndExpenses": 132707766000000,
    "interestIncome": 639217000000,
    "interestExpense": 536086000000,
    "depreciationAndAmortization": 6934364000000,
    "ebitda": 16754133000000,
    "ebitdaratio": 0.1175501492,
    "operatingIncome": 9819769000000,
    "operatingIncomeRatio": 0.0688973467,
    "totalOtherIncomeExpensesNet": 1128174000000,
    "incomeBeforeTax": 10947943000000,
    "incomeBeforeTaxRatio": 0.0768128278,
    "incomeTaxExpense": 2964329000000,
    "netIncome": 7364364000000,
    "netIncomeRatio": 0.0516697633,
    "eps": 14260.5,
    "epsdiluted": 14260.5,
    "weightedAverageShsOut": 399470516,
    "weightedAverageShsOutDil": 399470516,
    "link": null,
    "finalLink": null
  },

do you have any ideas what's the issue here?

Thanks!

[IMPROVE]List of all the available names that can be used in a custom ratio

What's the feature that should be improved?

All the valid names that can be used in a custom ratio.

Describe how you would like the feature improved
Include a list of all the valid names that can be used in a custom ratio.

Possibly describe the ideal way to improve this
Using pandas should be easy to get the column names.

Additional information
At this point in the code you already have all the data available.

total_financials = pd.concat(

need api key?

when I first use it, code as below:

import FundamentalAnalysis as fa

    ticker = "AAPL"
    # Show the available companies
    companies = fa.available_companies()

erros:
{"Error Message" : "Invalid API KEY. Please retry or visit our documentation to create one FREE https://financialmodelingprep.com/developer/docs"} Traceback (most recent call last): File "C:/Users/ron/Documents/us-stocks/spider.py", line 240, in <module> companies = fa.available_companies() File "C:\Users\ron\anaconda3\envs\py37\lib\site-packages\FundamentalAnalysis\details.py", line 23, in available_companies data_json = json.loads(data)['symbolsList'] KeyError: 'symbolsList'
SO, I need a API key? and where I can set?

TypeError: unsupported operand type(s) for |: 'type' and 'types.GenericAlias'

What's the feature that should be improved?
example 1: TypeError: unsupported operand type(s) for |: 'type' and 'types.GenericAlias'

Describe how you would like the feature improved
image

Possibly describe the ideal way to improve this
If you have thought about how you would do it, add it here.

Additional information
pip list
asttokens 2.2.1
backcall 0.2.0
colorama 0.4.6
comm 0.1.3
debugpy 1.6.7
decorator 5.1.1
executing 1.2.0
financedatabase 2.1.0
financetoolkit 1.0.0
importlib-metadata 6.6.0
ipykernel 6.23.1
ipython 8.14.0
jedi 0.18.2
jupyter_client 8.2.0
jupyter_core 5.3.0
matplotlib-inline 0.1.6
nest-asyncio 1.5.6
numpy 1.24.3
packaging 23.1
pandas 2.0.2
parso 0.8.3
pickleshare 0.7.5
pip 23.1.2
platformdirs 3.5.1
prompt-toolkit 3.0.38
psutil 5.9.5
pure-eval 0.2.2
Pygments 2.15.1
python-dateutil 2.8.2
pytz 2023.3
pywin32 306
pyzmq 25.1.0
setuptools 49.2.1
six 1.16.0
stack-data 0.6.2
tornado 6.3.2
traitlets 5.9.0
typing_extensions 4.6.3
tzdata 2023.3
wcwidth 0.2.6
zipp 3.15.0

Class based approach

Currently for every function, you need to pass api key as arguement which is not a sound approach. By looking into the code, I found that functions are classified as details, financial statements, and so on. Creating class for every component (details, financial_statements, ratios,..) will avoid us to pass api keys for every method / function and just need the instance of the class with api key as arguement.

Example:

ratios = Ratios(api_key)
ratios.financial_ratios(ticker)

How to resume a download?

Hello everyone!

I don't have the most stable network connection, and I was wondering if it was possible to resume a data download for a large dataset if the connection is interrupted.

If not, do you have any tips to minimise losses (like downloading in stages or creating some sort of checkpoint system?)

Thanks!

[IMPROVE] Add FinancialModelPrep's Stock Data

FinancialModelingPrep supplies historical data with a rich history. Given that a user has a key, it makes sense to get historical data from this source as an alternative to Yahoo Finance. This also prevents rate limits that Yahoo Finance imposes.

image

The idea would be to make this the default if the user has an API key set with the ability to change the source if desired. Could also make it not the default in all cases. Feel free to let me know what you think.

See: https://financialmodelingprep.com/api/v3/historical-price-full/AAPL?apikey=FMP_KEY&from=1980-01-01

Issues with KeyError

Traceback (most recent call last):

File "", line 1, in
income_statement_annually = fa.income_statement(ticker, period="annual")

File "C:\Users\Bob\Anaconda3\lib\site-packages\FundamentalAnalysis\financial_statements.py", line 28, in income_statement
data_json = json.loads(data)['financials']
data_json = json.loads(data)['financials']

KeyError: 'financials'

[IMPROVE] get_historical_data call fails with `No data found for the following tickers: ^TNX`

hello! Thank you for such a great project!

I have been experimenting on Google Colab with some API calls and everything works okay, so I decided to move locally to my MacBook, however, I encounter issues with the historical data (which is required for the ratios module), financial statements WAI.

from financetoolkit import Toolkit
companies = Toolkit(tickers=['GOOG'], api_key='KEY', start_date="2018-12-31")
companies.get_historical_data()

fails with:

No data found for the following tickers: ^TNX @ financetoolkit/toolkit_controller.py", line 2187, in get_treasury_data ...

I use financetoolkit==1.6.1 and Python 3.10.11. I tried new API key, different IP addresses (within same country), clean virtualenv but no luck. This call works in the Google Colab without issues with the same API key.

Any ideas?

thank you!

Is possible to get the Intrinsic Value ?

Hi,

I try your wonderful package. I can get the discount cash flow of a stock/ticker. I see you use the financialmodelingprep.com to get the discount cash flow. But by financialmodelingprep.com there is Intrinsic Value. I wonder if one can get this via your package?

Regards

Thomas

Line 22 in Available Companies Code Error?

Describe the bug
A clear and concise description of what the bug is.
Hello, Im afraid that im new to programming but i had this code running perfectly fine but for whatever reason it seems to stop working properly few days later. Im not to sure but it has something to do with line 22 in available companies file.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.
image

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Can I use your package in Jupyter notebook?

jupyter

Hi,

I installed FunamentalAnalysis within a conda environment. I can run it in a python script but I cannot use it in Jupyter notebook. Can you please guide if it is possible to use here? Please see the image for reference.

Thanks,
Niranjan

Calendar years instead of "year ended"

The column names in the annual financial statements (the years) are occasionally off. For example, ticker DPZ filed their 10K for fiscal year 2020 on Jan 3, 2021 (see here; their fiscal year end is the Sunday closest to Dec 31). This results in 2020 data being reported as 2021. Same thing for the following year.

In financial_statements.py, date = value['date'][:4] could be replaced with date = value['calendarYear'] in all three functions, and this would solve the issue. In this case I would also recommend not deleting date — del value['date'] — since the user might also be interested in the fiscal year end date.

Lastly, and maybe this should be a separate issue, it seems unintuitive to have the year columns represented as a string instead of an integer. Wrapping the suggestion above in int() is an easy fix.

Figured I would mention these here in case I am missing something, but I'm happy to create a pull request if there are no objections.

[BUG] Financial Ratios - Zero Division Error

I encountered a "Zero Division Error" when seeking financial ratios for a particular company.

The company in question was 'TNE.AX' - Technology One (ASX company). I have checked my FMP API and it now works (e.g. the income statement populates correctly).

I plugged the error into Chat GPT (of course) and it came back saying that this could happen when COGS wasn't provided - which is perhaps true. As an ASX listed company, TNE.AX's financial information may not tranfer across into FMP 100% accurately.

In any case, Chat GPT suggests an alteration to the profitability.py file. Have attached its suggestion - I'm still very new to this so will leave in your capable hands!

ZeroDivisionError.txt
Chat GPT Suggestion.docx

list index out of range

Running the exemple on readme.md file I receive following error:

\lib\site-packages\FundamentalAnalysis\balance_sheet.py", line 55, in balance_sheet
data = pd.read_html(lxml.etree.tostring(table[0], method='html'))[0].set_index(0).transpose()
IndexError: list index out of range

pip library broken

Pip library seems to be broken, receiving this error:
ERROR: Could not find a version that satisfies the requirement FundamentalAnalysis (from versions: none)
ERROR: No matching distribution found for FundamentalAnalysis

[IMPROVE] Period columns are not aligned with fiscal year reporting

Hello!

For some companies (such as Apple) fiscal year does not align with the calendar year. This is a common practice among many retail and technology companies, as it allows for a more consistent comparison of year-over-year performance, particularly in industries where sales can be highly seasonal.

I believe we should use fiscal year periods for fetching the reports instead of calendar year, what do you think?

Example:

companies = Toolkit(
    tickers=['AAPL'], 
    api_key=FMP_KEY, 
    start_date="2023-01-01",
    quarterly=True,
)

print(companies.get_statistics_statement())

returns:

date                                                          2023Q1                                             2023Q2                                             2023Q3
Reported Currency                                                USD                                                USD                                                USD
CIK ID                                                        320193                                             320193                                             320193
Filling Date                                              2023-05-05                                         2023-08-04                                         2023-11-03
Accepted Date                                    2023-05-04 18:03:52                                2023-08-03 18:04:43                                2023-11-02 18:08:27
Calendar Year                                                   2023                                               2023                                               2023
Period                                                            Q2                                                 Q3                                                 Q4
SEC Link           https://www.sec.gov/Archives/edgar/data/320193...  https://www.sec.gov/Archives/edgar/data/320193...  https://www.sec.gov/Archives/edgar/data/320193...
Document Link      https://www.sec.gov/Archives/edgar/data/320193...  https://www.sec.gov/Archives/edgar/data/320193...  https://www.sec.gov/Archives/edgar/data/320193...

the documents and periods would not align with the date columns.

Thanks a lot!

Significant time delays in get_historical_data()

Hi,

I am having significant speed issues when running the get_historical_data() function.
The Toolkit works fine but running the above even for three stocks, takes ~135 seconds. Running for 100 takes 200 seconds. If I run for a large amount of stocks (say the 9500 or so of the large, mid and small cap stocks in the financedatabase module) the code always crashes and I get a long list of exception errors in multiple threads.

I ran CProfile, and no specific line of code seems to cause the backlog (tottime all < 0.001).

Does anyone have any idea on how to what could be the cause of this and stop errors from occurring when running for large numbers of stocks? Code snippet below:

`companies = Toolkit(
tickers=ticker_list,
start_date = date,
api_key="xxxxxx",
)

hist_data = companies.get_historical_data()`

RatioAnalysis() doesn't appear to exist

Traceback (most recent call last):
File "C:/Python/StocksLoader/yFinance_Fundamentals.py", line 10, in
print(fa.ratio_analysis(symbol))
AttributeError: module 'FundamentalAnalysis' has no attribute 'ratio_analysis'

[IMPROVE] Calculate bulk financial ratios without using toolkit

I've created a stock universe consisting of 1000 different stocks from which I in a for loop fetch the income statement, balance sheet and cash flow using Yahoo finance. However currently there doesnt seem to be functionality to use the collect_all_ratios() function on such a dataset. Each loop generates 3 datasets for income statement, balance sheet and cash flow for each ticker in the universe. The idea is then to apply bulk ratio calculations and save those files.

I've tried adjusting the input parameters for the Toolkit() class as follows:

companies = Toolkit(tickers=ticker, balance=balance, income=income, cash=cash_flow, format_location=dir_path + "\\normalization_files")

However this yields an IndexError: Too many levels: Index has only 1 level, not 2

So I try to mitigate this error using:

balance.index = pd.MultiIndex.from_product([[ticker], balance.index])
    income.index = pd.MultiIndex.from_product([[ticker], income.index])
    cash_flow.index = pd.MultiIndex.from_product([[ticker], cash_flow.index])

However that then throws a ValueError: No axis named columns for object type Series

What can I do?

[BUG] Reindexing only valid with uniquely valued Index objects

Using the new v1.1.1 version I get the following error when passing a list of symbols of approximately 50 different tickers. The issue doesnt happen when I try other tickers, so I assume that it is because 1 ticker is causing a problem here:

companies = Toolkit(symbols, api_key="XXX")

df_total = companies.ratios.collect_all_ratios()

df_total.to_excel(dir_path + "\\df_total.xlsx")

Yields:

Traceback (most recent call last):
  File "c:\Desktop\Proj1\\data_fetch_fmp.py", line 73, in <module>
    df_total = companies.ratios.collect_all_ratios()
  File "C:\Users\Tomas\anaconda3\envs\Toolkit\lib\site-packages\financetoolkit\base\toolkit_controller.py", line 156, in ratios
    self.get_balance_sheet_statement()
  File "C:\Users\Tomas\anaconda3\envs\Toolkit\lib\site-packages\financetoolkit\base\toolkit_controller.py", line 542, in get_balance_sheet_statement
    ) = _get_financial_statements(
  File "C:\Users\Tomas\anaconda3\envs\Toolkit\lib\site-packages\financetoolkit\base\models\fundamentals_model.py", line 111, in get_financial_statements
    financial_statement_total = pd.concat(financial_statement_dict, axis=0)
  File "C:\Users\Tomas\anaconda3\envs\Toolkit\lib\site-packages\pandas\core\reshape\concat.py", line 385, in concat
    return op.get_result()
  File "C:\Users\Tomas\anaconda3\envs\Toolkit\lib\site-packages\pandas\core\reshape\concat.py", line 612, in get_result
    indexers[ax] = obj_labels.get_indexer(new_labels)
  File "C:\Users\Tomas\anaconda3\envs\Toolkit\lib\site-packages\pandas\core\indexes\base.py", line 3732, in get_indexer
    raise InvalidIndexError(self._requires_unique_msg)
pandas.errors.InvalidIndexError: Reindexing only valid with uniquely valued Index objects

Ticker list in question:
['AIR', 'AJRD', 'AVAV', 'AXON', 'BA', 'BWXT', 'CUB', 'HEI', 'HEI-A', 'HII', 'JOBY', 'LHX', 'LMT', 'MOG-A', 'MOG-B', 'MRCY', 'NOC', 'POWWP', 'RKLB', 'RTX', 'SPR', 'TDG', 'TXT', 'WWD', 'AAWW', 'CHRW', 'EXPD', 'FDX', 'FWRD', 'HUBG', 'JBHT', 'MIC', 'UPS', 'XPO', 'AAL', 'ALGT', 'ALK', 'DAL', 'JBLU', 'LUV', 'SAVE', 'SKYW', 'UAL', 'ULCC', 'ALSN', 'BWA', 'CTB', 'DAN', 'DORM', 'GNTX']

[IMPROVE] ratios.collect_all_ratios() misses current year's first quarter

When I calculate all ratios from 2018-01-01 until todays date (2023-11-03), I don't get data for 2023 Q1.

Printing the DataFrame returned by collect_all_ratios show date for these quarters - as you can see, 2023Q1 is missing:

2018Q1         2018Q2  
2018Q3         2018Q4  
2019Q1         2019Q2  
2019Q3         2019Q4  
2020Q1         2020Q2  
2020Q3         2020Q4  
2021Q1         2021Q2  
2021Q3         2021Q4  
2022Q1         2022Q2  
2022Q3         2022Q4  
2023Q2         2023Q3
companies = Toolkit(["AAPL"], api_key=API_KEY, start_date="2018-01-01", quarterly=True)

all_ratios = companies.ratios.collect_all_ratios()

pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)

print(all_ratios)

Using version 1.5.0

KeyError: 'financials'

When attempting to access a financial statement, I receive the following error:

data_json = json.loads(data)['financials']
KeyError: 'financials'

fa.stock_data Not Retrieving Data

Describe the bug
Unable to use fa.stock_data

To Reproduce
Call function directly, unable to retrieve data.

Expected behavior
List of stocks with Start, Close, Etc

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):
Error:

JSONDecodeError Traceback (most recent call last)
in
----> 1 GSPC = fa.stock_data('AAPL', start = date_start, end = end_date )['close']

~/opt/anaconda3/lib/python3.8/site-packages/FundamentalAnalysis/stock_data.py in stock_data(ticker, period, interval, start, end)
51 try:
52 data = requests.get(url=url, params=parameters)
---> 53 data_json = data.json()['chart']['result'][0]
54 except TypeError:
55 raise TypeError("No data available. Please check if you have a valid period and/or interval. \n"

~/opt/anaconda3/lib/python3.8/site-packages/requests/models.py in json(self, **kwargs)
896 # used.
897 pass
--> 898 return complexjson.loads(self.text, **kwargs)
899
900 @Property

~/opt/anaconda3/lib/python3.8/json/init.py in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
355 parse_int is None and parse_float is None and
356 parse_constant is None and object_pairs_hook is None and not kw):
--> 357 return _default_decoder.decode(s)
358 if cls is None:
359 cls = JSONDecoder

~/opt/anaconda3/lib/python3.8/json/decoder.py in decode(self, s, _w)
335
336 """
--> 337 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
338 end = _w(s, end).end()
339 if end != len(s):

~/opt/anaconda3/lib/python3.8/json/decoder.py in raw_decode(self, s, idx)
353 obj, end = self.scan_once(s, idx)
354 except StopIteration as err:
--> 355 raise JSONDecodeError("Expecting value", s, err.value) from None
356 return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

[SSL: CERTIFICATE_VERIFY_FAILED] for stock_data_detailed

Hi, we are executing the function like this:
stock_data = fa.stock_data_detailed(ticker, api_key, begin=begin, end=end)

And met the following error:
Exception has occurred: URLError
<urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1131)>

I just renewed my yearly subscription this July so I do not think it would be related to the subscription. Can you help check if this is an internal issue and provide the fix ETA if so?

get_historical_data fail

Here is my code.

companies = Toolkit(["MSFT"], api_key=API_KEY, start_date="2020-12-31", quarterly=True)
historical_data = companies.get_historical_data()

It failed with the following error displayed.

Obtaining historical data: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 2/2 [00:00<00:00,  9.20it/s]
Exception in thread Thread-120 (worker):
Traceback (most recent call last):
  File "/Users/tommy/miniforge3/envs/jupyter-ai/lib/python3.11/threading.py", line 1045, in _bootstrap_inner
    self.run()
  File "/Users/tommy/miniforge3/envs/jupyter-ai/lib/python3.11/threading.py", line 982, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/tommy/miniforge3/envs/jupyter-ai/lib/python3.11/site-packages/financetoolkit/historical_model.py", line 95, in worker
    historical_data = get_historical_data_from_financial_modeling_prep(
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tommy/miniforge3/envs/jupyter-ai/lib/python3.11/site-packages/financetoolkit/historical_model.py", line 329, in get_historical_data_from_financial_modeling_prep
    dividends_df.index = pd.to_datetime(dividends_df.index)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tommy/miniforge3/envs/jupyter-ai/lib/python3.11/site-packages/pandas/core/tools/datetimes.py", line 1121, in to_datetime
    result = convert_listlike(arg, format, name=arg.name)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tommy/miniforge3/envs/jupyter-ai/lib/python3.11/site-packages/pandas/core/tools/datetimes.py", line 488, in _convert_listlike_datetimes
    return _array_strptime_with_fallback(arg, name, utc, format, exact, errors)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tommy/miniforge3/envs/jupyter-ai/lib/python3.11/site-packages/pandas/core/tools/datetimes.py", line 519, in _array_strptime_with_fallback
    result, timezones = array_strptime(arg, fmt, exact=exact, errors=errors, utc=utc)
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "strptime.pyx", line 534, in pandas._libs.tslibs.strptime.array_strptime
  File "strptime.pyx", line 355, in pandas._libs.tslibs.strptime.array_strptime
ValueError: time data "2023-08-16" doesn't match format "%Y-%b-%d", at position 1. You might want to try:
    - passing `format` if your strings have a consistent format;
    - passing `format='ISO8601'` if your strings are all ISO8601 but not necessarily in exactly the same format;
    - passing `format='mixed'`, and the format will be inferred for each element individually. You might want to use `dayfirst` alongside this.

Quarterly reports

Looks like the quarterly reports may have recently broken. Attempted to pull income and cash flow on a quarterly basis, and was returned a "HTTP Error 403:"

Appears to be new as I was able to pull quarterly financials previously without issue. Maybe an update to the "Period" field?

[IMPROVE] .get_historical_ratios() HTTP error 404 on invalid tickers

In the current version calling .get_historical_ratios() or collect_all_ratios() on a list of symbols in which 1 ticker is invalid (delisted or otherwise not on yahoo finance) will result in the following error: urllib.error.HTTPError: HTTP Error 404: Not Found

The solution is to add an except to catch these tickers. Ideally they should be removed from the symbol list so as to not pollute the dataset. Perhaps a boolean for the user in Toolkit() to determine if the script should automatically drop or keep "corrupt" symbols.

Financial Statement calls broke

I keep getting the following error, when trying to pull financial statements:
"IndexError: list index out of range"

Here"s the full error for cashflows:

Traceback (most recent call last):
File "C:/Python/StocksLoader/yFinance_Fundamentals.py", line 10, in
print(fa.cashflows(symbol))
File "C:\ProgramData\Anaconda3\envs\StocksLoader\lib\site-packages\FundamentalAnalysis\cashflows.py", line 55, in cashflows
data = pd.read_html(lxml.etree.tostring(table[0], method='html'))[0].set_index(0).transpose()
IndexError: list index out of range

Ratios, summary, etc... still appear to work. Any ideas?
Thanks for making this, BTW.

TypeError: 'type' object is not subscriptable

I encountered the following error report, how to do:
'''
Traceback (most recent call last):
File "fmp.py", line 2, in
from financetoolkit import Toolkit
File "/Users/lijun/anaconda3/envs/test/lib/python3.8/site-packages/financetoolkit/init.py", line 5, in
from .base.toolkit_controller import Toolkit
File "/Users/lijun/anaconda3/envs/test/lib/python3.8/site-packages/financetoolkit/base/toolkit_controller.py", line 7, in
from financetoolkit.base.models.fundamentals_model import (
File "/Users/lijun/anaconda3/envs/test/lib/python3.8/site-packages/financetoolkit/base/models/fundamentals_model.py", line 15, in
tickers: str | list[str],
TypeError: 'type' object is not subscriptable
'''

conda list:

Name Version Build Channel

ca-certificates 2023.05.30 hecd8cb5_0
financetoolkit 1.0.0 pypi_0 pypi
libcxx 14.0.6 h9765a3e_0
libffi 3.4.4 hecd8cb5_0
ncurses 6.4 hcec6c5f_0
numpy 1.24.3 pypi_0 pypi
openssl 1.1.1t hca72f7f_0
pandas 2.0.1 pypi_0 pypi
pip 23.0.1 py38hecd8cb5_0
python 3.8.16 h218abb5_3
python-dateutil 2.8.2 pypi_0 pypi
pytz 2023.3 pypi_0 pypi
readline 8.2 hca72f7f_0
setuptools 67.8.0 py38hecd8cb5_0
six 1.16.0 pypi_0 pypi
sqlite 3.41.2 h6c40b1e_0
tk 8.6.12 h5d9f67b_0
tzdata 2023.3 pypi_0 pypi
wheel 0.38.4 py38hecd8cb5_0
xz 5.4.2 h6c40b1e_0
zlib 1.2.13 h4dc903c_0

20230609-212147

Date format

Hi and thank you for your work,

In FundamentalAnalysis\fundamentalanalysis\financial_statements.py, in functions income_statement(), balance_sheet_statement() and cash_flow_statement(), the date column header in the returned dataframes should be a string (e.g. '2019') and not converted to integer (e.g. int('2019'), as done by date = int( value['calendarYear'] ).

This is to stay coherent with the dataframes returned by the functions implemented in FundamentalAnalysis\fundamentalanalysis\details.py, where the data column header is a string (e.g. '2019')

Best regards

[FR] API Call sleeper/limiter

When users pass in a large list of symbols this can result in the api call limit being violated. Add functionality to set a time.sleep(60) for every x api calls (x being dependant on the subscription plan). This will allow for downloading of large lists of symbols without breaking the API limit.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.