Issue with "algorithmic-trading-python" course

Hey guys, this is what I am running into a little issue. Im running on python 3.8.13. Im currently doing “algorithmic-trading-python” course. I have setup the env as specified.

"

Equal-Weight S&P 500 Index Fund
Introduction & Library Imports
The S&P 500 is the world's most popular stock market index. The largest fund that is benchmarked to this index is the SPDR® S&P 500® ETF Trust. It has more than US$250 billion of assets under management.
The goal of this section of the course is to create a Python script that will accept the value of your portfolio and tell you how many shares of each S&P 500 constituent you should purchase to get an equal-weight version of the index fund.
Library Imports
The first thing we need to do is import the open-source software libraries that we'll be using in this tutorial.
In [1]:

import numpy as np
import pandas as pd
import requests
import xlsxwriter
import math
Importing Our List of Stocks
The next thing we need to do is import the constituents of the S&P 500.
These constituents change over time, so in an ideal world you would connect directly to the index provider (Standard & Poor's) and pull their real-time constituents on a regular basis.
Paying for access to the index provider's API is outside of the scope of this course.
There's a static version of the S&P 500 constituents available here. Click this link to download them now. Move this file into the starter-files folder so it can be accessed by other files in that directory.
Now it's time to import these stocks to our Jupyter Notebook file.
In [2]:

stocks = pd.read_csv('sp_500_stocks.csv')
#type()
stocks
Out[2]:
Ticker
0	A
1	AAL
2	AAP
3	AAPL
4	ABBV
...	...
500	YUM
501	ZBH
502	ZBRA
503	ZION
504	ZTS
505 rows × 1 columns
Acquiring an API Token
Now it's time to import our IEX Cloud API token. This is the data provider that we will be using throughout this course.
API tokens (and other sensitive information) should be stored in a secrets.py file that doesn't get pushed to your local Git repository. We'll be using a sandbox API token in this course, which means that the data we'll use is randomly-generated and (more importantly) has no cost associated with it.
Click here to download your secrets.py file. Move the file into the same directory as this Jupyter Notebook before proceeding.
In [6]:

from secrets import IEX_CLOUD_API_TOKEN
Making Our First API Call
Now it's time to structure our API calls to IEX cloud.
We need the following information from the API:
Market capitalization for each stock
Price of each stock
In [7]:

symbol='AAPL'
api_url = f'https://sandbox.iexapis.com/stable/stock/{symbol}/quote?token={IEX_CLOUD_API_TOKEN}'
data = requests.get(api_url).json()
data
---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
Input In [7], in <cell line: 3>()
      1 symbol='AAPL'
      2 api_url = f'https://sandbox.iexapis.com/stable/stock/{symbol}/quote?token={IEX_CLOUD_API_TOKEN}'
----> 3 data = requests.get(api_url).json()
      4 data

File /usr/local/Caskroom/miniconda/base/envs/algorithmic-trading-python/lib/python3.8/site-packages/requests/models.py:888, in Response.json(self, **kwargs)
    886 if encoding is not None:
    887     try:
--> 888         return complexjson.loads(
    889             self.content.decode(encoding), **kwargs
    890         )
    891     except UnicodeDecodeError:
    892         # Wrong UTF codec detected; usually because it's not UTF-8
    893         # but some other 8-bit codec.  This is an RFC violation,
    894         # and the server didn't bother to tell us what codec *was*
    895         # used.
    896         pass

File /usr/local/Caskroom/miniconda/base/envs/algorithmic-trading-python/lib/python3.8/json/__init__.py:357, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    352     del kw['encoding']
    354 if (cls is None and object_hook is None and
    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

File /usr/local/Caskroom/miniconda/base/envs/algorithmic-trading-python/lib/python3.8/json/decoder.py:337, in JSONDecoder.decode(self, s, _w)
    332 def decode(self, s, _w=WHITESPACE.match):
    333     """Return the Python representation of ``s`` (a ``str`` instance
    334     containing a JSON document).
    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):

File /usr/local/Caskroom/miniconda/base/envs/algorithmic-trading-python/lib/python3.8/json/decoder.py:355, in JSONDecoder.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)

"

(algorithmic-trading-python) ➜  algorithmic-trading-python git:(master) ✗ pip li
st
Package              Version
-------------------- ---------
appnope              0.1.3
argon2-cffi          21.3.0
argon2-cffi-bindings 21.2.0
asttokens            2.0.7
attrs                22.1.0
backcall             0.2.0
beautifulsoup4       4.11.1
bleach               5.0.1
certifi              2022.6.15
cffi                 1.15.1
chardet              3.0.4
debugpy              1.6.2
decorator            5.1.1
defusedxml           0.7.1
entrypoints          0.4
executing            0.9.1
fastjsonschema       2.16.1
idna                 2.8
importlib-resources  5.9.0
ipykernel            6.10.0
ipython              8.4.0
ipython-genutils     0.2.0
ipywidgets           7.7.1
jedi                 0.18.1
Jinja2               3.1.2
jsonschema           4.9.1
jupyter              1.0.0
jupyter-client       7.2.2
jupyter-console      6.1.0
jupyter-core         4.10.0
jupyterlab-pygments  0.1.2
jupyterlab-widgets   1.1.1
MarkupSafe           2.1.1
matplotlib-inline    0.1.3
mistune              0.8.4
nbclient             0.5.13
nbconvert            6.4.4
nbformat             5.4.0
nest-asyncio         1.5.5
notebook             6.4.12
numpy                1.17.4
packaging            21.3
pandas               0.25.3
pandocfilters        1.5.0
parso                0.8.3
pexpect              4.8.0
pickleshare          0.7.5
pip                  22.1.2
pkgutil_resolve_name 1.3.10
prometheus-client    0.14.1
prompt-toolkit       3.0.30
psutil               5.9.1
ptyprocess           0.7.0
pure-eval            0.2.2
pycparser            2.21
Pygments             2.12.0
pyparsing            3.0.9
pyrsistent           0.18.1
python-dateutil      2.8.2
pytz                 2022.1
pyzmq                23.2.0
qtconsole            5.3.1
QtPy                 2.1.0
requests             2.22.0
scipy                1.5.2
Send2Trash           1.8.0
setuptools           61.2.0
six                  1.16.0
soupsieve            2.3.1
stack-data           0.3.0
terminado            0.15.0
testpath             0.6.0
tornado              6.2
traitlets            5.3.0
urllib3              1.25.11
wcwidth              0.2.5
webencodings         0.5.1
wheel                0.37.1
widgetsnbextension   3.6.1
XlsxWriter           1.2.2
zipp                 3.8.1
(algorithmic-trading-python) ➜  algorithmic-trading-python git:(master) ✗ python
 --version
Python 3.8.13

Sorry for the question as I’m not familiar with all the courses that freecodecamp offers. Can you provide a link to the course you are working on?

of course, Algorithmic Trading Using Python - Full Course - YouTube . I would like to thank you for the help, :pray: GitHub - nickmccullum/algorithmic-trading-python: The repository for freeCodeCamp's YouTube course, Algorithmic Trading in Python

Very interesting class. I haven’t listened to enough of it to understand which step you’re on yet but it looks like others may have run into the same issue and reported it on github

Please take a look to see if anything there will give you ideas on how to proceed.
(and if you can’t find the same issue reported there, you can probably open one)

the issue was simple, made my own key and reset the key in the secrets.py. It took a little figuring out of the website iexcloud… if any of you need help, all help. TY for this course

1 Like

Thanks for the offer. Would be great to get the steps from you listed here in how you recovered from the issue.

Ran into another issue, all let you know after I get this all figured out.

1 Like

ok, found out what’s going on, I think. I don’t have a remedy for this, can you please help me.

Looping Through The Tickers in Our List of Stocks

Using the same logic that we outlined above, we can pull data for all S&P 500 stocks and store their data in the DataFrame using a for loop.

final_dataframe = pd.DataFrame(columns = my_columns)

for stock in stocks['Ticker'][:5]:
    api_url = f'https://sandbox.iexapis.com/stable/stock/{stock}/quote?token={IEX_CLOUD_API_TOKEN}'
    data = requests.get(api_url).json()
    final_dataframe = final_dataframe.append(
        pd.Series(
        [
            stock,
            data['latestPrice'],
            data['marketCap'],
            'N/A'
        ],
        index = my_columns),
        ignore_index = True
    )
    
    











#for symbols in stocks['Ticker']:
#    api_url = f'https://sandbox.iexapis.com/stable/stock/{symbol}/quote?token={IEX_CLOUD_API_TOKEN}'
#    data = requests.get(api_url).json
#    final_dataframe = final_dataframe.append(
#                                        pd.Series([symbols, 
#                                                   data['latestPrice'], 
#                                                   data['marketCap'], 
#                                                   'N/A'], 
#                                                  index = my_columns), 
#                                        ignore_index = True)




And

symbol_groups = list(chunks(stocks['Ticker'], 100))
symbol_strings = []
for i in range(0 , len(symbol_groups)):
    symbol_strings.append(','.join(symbol_groups[i]))
    print(symbol_strings[i])

final_dataframe = pd.DataFrame(columns = my_columns)

for symbol_string in symbol_strings[:1]:
    batch_api_call_url = f'https://sandbox.iexapis.com/stable/stock/market/batch/?types=quote&symbols={symbol_string}&token={IEX_CLOUD_API_TOKEN}'
    data = requests.get(batch_api_call_url).json
    #for symbol in symbol_string.split(','):
    #    final_dataframe = final_dataframe.append(
    #        pd.Series(
    #        [
    #            symbol,
    #            data[symbol]['quote']['latestPrice'],
    #            data[symbol]['quote']['marketCap'],
    #            'N/A'
    #        ],
    #        index = my_columns),
    #        ignore_index = True
    #    )
        
final_dataframe        

Im fallowing the lesson but the API is running different. For instance “for stock in stocks[‘Ticker’][:5]:” will work but as soon as I remove the [:5] it won’t.

Also the refactoring of the code

for symbols in stocks['Ticker'][:5]:
    api_url = f'https://sandbox.iexapis.com/stable/stock/{symbol}/quote?token={IEX_CLOUD_API_TOKEN}'
    data = requests.get(api_url).json
    final_dataframe = final_dataframe.append(
                                        pd.Series([symbols, 
                                                   data['latestPrice'], 
                                                   data['marketCap'], 
                                                   'N/A'], 
                                                  index = my_columns), 
                                        ignore_index = True)


Throws a error. As far as what he is saying and showing and giving in final section, it should.

Another thing is the batch section. Once again,

symbol_groups = list(chunks(stocks['Ticker'], 100))
symbol_strings = []
for i in range(0 , len(symbol_groups)):
    symbol_strings.append(','.join(symbol_groups[i]))
    print(symbol_strings[i])

final_dataframe = pd.DataFrame(columns = my_columns)

for symbol_string in symbol_strings[:1]:
    batch_api_call_url = f'https://sandbox.iexapis.com/stable/stock/market/batch/?types=quote&symbols={symbol_string}&token={IEX_CLOUD_API_TOKEN}'
    data = requests.get(batch_api_call_url).json
    for symbol in symbol_string.split(','):
        final_dataframe = final_dataframe.append(
            pd.Series(
            [
                symbol,
                data[symbol]['quote']['latestPrice'],
                data[symbol]['quote']['marketCap'],
                'N/A'
            ],
            index = my_columns),
            ignore_index = True
        )
        
final_dataframe        
A,AAL,AAP,AAPL,ABBV,ABC,ABMD,ABT,ACN,ADBE,ADI,ADM,ADP,ADSK,AEE,AEP,AES,AFL,AIG,AIV,AIZ,AJG,AKAM,ALB,ALGN,ALK,ALL,ALLE,ALXN,AMAT,AMCR,AMD,AME,AMGN,A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UV,LVS,LW,LYB,LYV,MA,MAA,MAR,MAS,MCD,MCHP
MCK,MCO,MDLZ,MDT,MET,MGM,MHK,MKC,MKTX,MLM,MMC,MMM,MNST,MO,MOS,MPC,MRK,MRO,MS,MSCI,MSFT,MSI,MTB,MTD,MU,MXIM,MYL,NBL,NCLH,NDAQ,NEE,NEM,NFLX,NI,NKE,NLOK,NLSN,NOC,NOV,NOW,NRG,NSC,NTAP,NTRS,NUE,NVDA,NVR,NWL,NWS,NWSA,O,ODFL,OKE,OMC,ORCL,ORLY,OTIS,OXY,PAYC,PAYX,PBCT,PCAR,PEAK,PEG,PEP,PFE,PFG,PG,PGR,PH,PHM,PKG,PKI,PLD,PM,PNC,PNR,PNW,PPG,PPL,PRGO,PRU,PSA,PSX,PVH,PWR,PXD,PYPL,QCOM,QRVO,RCL,RE,REG,REGN,RF,RHI,RJF,RL,RMD,ROK
ROL,ROP,ROST,RSG,RTX,SBAC,SBUX,SCHW,SEE,SHW,SIVB,SJM,SLB,SLG,SNA,SNPS,SO,SPG,SPGI,SRE,STE,STT,STX,STZ,SWK,SWKS,SYF,SYK,SYY,T,TAP,TDG,TDY,TEL,TFC,TFX,TGT,TIF,TJX,TMO,TMUS,TPR,TROW,TRV,TSCO,TSN,TT,TTWO,TWTR,TXN,TXT,TYL,UA,UAA,UAL,UDR,UHS,ULTA,UNH,UNM,UNP,UPS,URI,USB,V,VAR,VFC,VIAC,VLO,VMC,VNO,VRSK,VRSN,VRTX,VTR,VZ,WAB,WAT,WBA,WDC,WEC,WELL,WFC,WHR,WLTW,WM,WMB,WMT,WRB,WRK,WST,WU,WY,WYNN,XEL,XLNX,XOM,XRAY,XRX,XYL
YUM,ZBH,ZBRA,ZION,ZTS
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [115], in <cell line: 9>()
     11     data = requests.get(batch_api_call_url).json
     12     for symbol in symbol_string.split(','):
     13         final_dataframe = final_dataframe.append(
     14             pd.Series(
     15             [
     16                 symbol,
---> 17                 data[symbol]['quote']['latestPrice'],
     18                 data[symbol]['quote']['marketCap'],
     19                 'N/A'
     20             ],
     21             index = my_columns),
     22             ignore_index = True
     23         )
     25 final_dataframe

TypeError: 'method' object is not subscriptable

This is a learning thing with me. Do you know of someone who will be able to answer, I would really thank you. I personally think its something g with the API.

If you don’t have a account with iexcloud, use IEX_CLOUD_API_TOKEN = 'Tsk_8613a5b7e6414cf89f2819ca7d948fbd' in secrets.py

TY for everything. I am willing to pay if that will help

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.