algorithmic-trading-python
algorithmic-trading-python copied to clipboard
Calculating Momentum Percentiles
Hi Nick,
First off let me say this video series has been amazing and very informative! Keep up the excellent work!
I'm having an issue with trying to run these lines of code:
time_periods = [ 'One-Year', 'Six-Month', 'Three-Month', 'One-Month' ]
for row in hqm_dataframe.index: for time_period in time_periods: hqm_dataframe.loc[row, f'{time_period} Return Percentile'] = stats.percentileofscore(hqm_dataframe[f'{time_period} Price Return'], hqm_dataframe.loc[row, f'{time_period} Price Return'])/100
for time_period in time_periods: print(hqm_dataframe[f'{time_period} Return Percentile'])
hqm_dataframe
and I'm getting the following error:
TypeError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\scipy\stats\stats.py in percentileofscore(a, score, kind) 2015 2016 if kind == 'rank': -> 2017 left = np.count_nonzero(a < score) 2018 right = np.count_nonzero(a <= score) 2019 pct = (right + left + (1 if right > left else 0)) * 50.0/n
TypeError: '<' not supported between instances of 'NoneType' and 'float'
I even copy and pasted yours from the finished files and I'm getting the same error. At this point I am stuck. Is there something I am missing here because I have tried everything I know how to do. Any guidance would greatly be appreciated here.
Cheers!
I've noticed that IEX is sending back None on some of year1ChangePercent values. I'm thinking Scipy.stats.percentileofscore does not like the None value. I'm looking into how to replace None values with a zero. Or if someone else has a better solutions please share.
You can try to add
`for symbol_string in symbol_strings: batch_api_call_url = f'{sandbox_base_url}/stock/market/batch/?types=stats,quote&symbols={symbol_string}&token={IEX_CLOUD_API_TOKEN}' data = requests.get(batch_api_call_url).json() for symbol in symbol_string.split(','): hqm_dataframe = hqm_dataframe.append( pd.Series([symbol, data[symbol]['quote']['latestPrice'], 'N/A', data[symbol]['stats']['year1ChangePercent'], 'N/A', data[symbol]['stats']['month6ChangePercent'], 'N/A', data[symbol]['stats']['month3ChangePercent'], 'N/A', data[symbol]['stats']['month1ChangePercent'], 'N/A', 'N/A' ], index=hqm_columns), ignore_index=True)
hqm_dataframe.replace(to_replace=[None], value=0, inplace=True)`
I've tried the above knlklabacka, and it works, many thanks.
Hold on knlklabacka, it's not working. What am I adding?
this line: hqm_dataframe.replace(to_replace=[None], value=0, inplace=True)
If so where? at the end of the code?
I have add a link to my page that show the code for this iex_2.py
Let me know if that helps? The page is just partial code. Once my laptop is done updating and rebooting I can add the whole page.
I updated my page if you want to take a look. I see that there is another answer to this question also. Take a look at #2
Man, I have no idea what I did wrong here, here is what I have so far:
hqm_columns = [ 'Ticker', 'Price', 'Number of Shares to Buy', 'One-Year Price Return', 'One-Year Return Percentile', 'Six-Month Price Return', 'Six-Month Return Percentile', 'Three-Month Price Return', 'Three-Month Return Percentile', 'One-Month Price Return', 'One-Month Return Percentile' ]
hqm_dataframe = pd.DataFrame(columns = hqm_columns)
for symbol_string in symbol_strings: batch_api_call_url = f'{sandbox_base_url}/stock/market/batch/?types=stats,quote&symbols={symbol_string}&token={IEX_CLOUD_API_TOKEN}' data = requests.get(batch_api_call_url).json() for symbol in symbol_string.split(','): hqm_dataframe = hqm_dataframe.append( pd.Series([symbol, data[symbol]['quote']['latestPrice'], 'N/A', data[symbol]['stats']['year1ChangePercent'], 'N/A', data[symbol]['stats']['month6ChangePercent'], 'N/A', data[symbol]['stats']['month3ChangePercent'], 'N/A', data[symbol]['stats']['month1ChangePercent'], 'N/A', 'N/A' ], index=hqm_columns), ignore_index=True)
End For Loop
Replace [None] Values with a zero
hqm_dataframe.replace(to_replace=[None], value=0, inplace=True)
but I'm getting this error:
NameError Traceback (most recent call last)
NameError: name 'sandbox_base_url' is not defined
This might be better.
and Im getting the following error also.
you can either create a variable sandbox_base_url at the top of your page or hard code the url in place of {sandbox_base_url}
sandbox_base_url = 'https://sandbox.iexapis.com/stable'
If you are using Jupyter just replace this line
batch_api_call_url = f'https://sandbox.iexapis.com/stable/stock/market/batch/?types=stats,quote&symbols={symbol_string}&token={IEX_CLOUD_API_TOKEN}'
This line before the loop will clear out any rows that have null data in any column:
hqm_dataframe.dropna(inplace=True)
@subnivean Can you please provide and example? I'm putting it before the loop and I'm still getting an error. :'(
I think we're looking at different loops. I'm suggesting you replace your hqm_dataframe.replace(to_replace=[None], value=0, inplace=True)
with hqm_dataframe.dropna(inplace=True)
.
hqm_dataframe.replace(to_replace=[None], value=0, inplace=True)
this or hqm_dataframe.dropna(inplace=True)
should work
Hello guys, thank you for your support, Is this the right way to right it:
symbol_groups = list(chunks(stocks['Ticker'], 100)) symbol_strings = [] for i in range(0, len(symbol_groups)): symbol_strings.append(','.join(symbol_groups[i]))
final_dataframe = pd.DataFrame(columns = my_columns) final_dataframe.dropna(inplace=True) for symbol_string in symbol_strings:
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,
float(0 if data[symbol]['quote']['latestPrice'] is None else data[symbol]['quote']['latestPrice']),
data[symbol]['quote']['marketCap'],
'N/A'],
index = my_columns),
ignore_index = True)
final_dataframe.dropna(inplace=True)
final_dataframe
I am still getting the following error:
KeyError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_22676/1236221161.py in
KeyError: 'WLTW'
Can you help please?
@abdulkaderkhouja
when you load the csv Ticker file in stocks value, filter out the stocks name that IEX Sandbox no longer provide with
stocks = stocks[~stocks['Ticker'].isin(['DISCA', 'HFC', 'VIAC', 'WLTW'])]