Coder Social home page Coder Social logo

algorithmic-trading-python's Introduction

Algorithmic Trading in Python

This repository

Course Outline

  • Section 1: Algorithmic Trading Fundamentals
    • What is Algorithmic Trading?
    • The Differences Between Real-World Algorithmic Trading and This Course
  • Section 2: Course Configuration & API Basics
    • How to Install Python
    • Cloning The Repository & Installing Our Dependencies
    • Jupyter Notebook Basics
    • The Basics of API Requests
  • Section 3: Building An Equal-Weight S&P 500 Index Fund
    • Theory & Concepts
    • Importing our Constituents
    • Pulling Data For Our Constituents
    • Calculating Weights
    • Generating Our Output File
    • Additional Project Ideas
  • Section 4: Building A Quantitative Momentum Investing Strategy
    • Theory & Concepts
    • Pulling Data For Our Constituents
    • Calculating Weights
    • Generating Our Output File
    • Additional Project Ideas
  • Section 5: Building A Quantitative Value Investing Strategy
    • Theory & Concepts
    • Importing our Constituents
    • Pulling Data For Our Constituents
    • Calculating Weights
    • Generating Our Output File
    • Additional Project Ideas

algorithmic-trading-python's People

Contributors

nickmccullum 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

algorithmic-trading-python's Issues

downloading secrets.py

When I click on download the file, a new tab opens with only one line written in it:
IEX_CLOUD_API_TOKEN = 'Tpk_059b97af715d417d9f49f50b51b1c448'
What should I do?

Getting error 403,Tried replacing token with a new one, used try except clause

final_dataframe = pd.DataFrame(columns = mycolumns)

for stock in stocks['Ticker']:
api_url = f'https://sandbox.iexapis.com/stable/stock/{stock}/quote/?token=sk_b92781ff259841bead23d3012a9f8cf3'
data = requests.get(api_url)

if data.status_code == 200:
    data = data.json()
    final_dataframe = final_dataframe.append(
        pd.Series(
            [stock, data['latestPrice'], data['marketCap'], 'N/A'], 
            index = mycolumns
        ), 
        ignore_index = True
    )
else:
    print(f'An error occurred, status code: {data.status_code}')

002_quantitative_momentum_strategy

Hi, please note that the code

hqm_dataframe.sort_values(by = 'HQM Score', ascending = False)
hqm_dataframe = hqm_dataframe[:51]

does not work as expected. You need to add inplace = True
hqm_dataframe.sort_values(by = 'HQM Score', ascending = False, inplace = True)
otherwise you are taking the fist 51 elements in alphabetical order.

PS Shouldn't you just take the first 50 elements with
hqm_dataframe = hqm_dataframe[:50]
instead of 51 (they start from 0)

In batch api --> JSONDecodeError

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_col)

for symbol_string in symbol_strings:
batch_api_call_url = f'https://cloud.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 data:
if data[symbol]['quote']:
final_dataframe = final_dataframe.append(
pd.Series([symbol,
data[symbol]['quote']['latestPrice'],
data[symbol]['quote']['marketCap'],
'N/A'],
index=my_col),
ignore_index=True)

final_dataframe
Screenshot 2023-03-20 104621
Screenshot 2023-03-20 104719

Loading file to Jupyter Error

Hi Nick,

First of all, thank you for the Youtube video, it is really AWESOME.

I was try to follow your steps but get stuck to load the equal weighted S&P 500 file into Jupyter. The error shows as below:

"Unreadable Notebook: C:\Users****\Notebooks\001_equal_weight_S&P_500.ipynb NotJSONError("Notebook does not appear to be JSON: '\n\n\n\n\n\n\n<html lang...")"

Any idea what is wrong with the file? or if its my Jupyter issue?

Thanks,
Steven

Problem with 'None' values in One-Year, Six-Month, Three-Month, One-Month Price Returns

If any of the values in the One-Year, Six-Month, Three-Month, One-Month Price Returns is 'None' then the 'percentileofscore' function will error because it cannot match a float against a NoneType.

To fix this I added the following in the creation of the data series for each price return column. xxx is the time period:

float(0 if data[symbol]['stats']['xxxChangePercent'] is None else data[symbol]['stats']['xxxChangePercent'])

I am not sure if there is a better solution.

requests.get(api_url) ISSUE

Hi Nick,

I was trying to follow your code under 'Algorithmic Trading Using Python - Full Course'.

However, I came across an error when I was trying to request data from api_url as per the attached screenshot.

Could you pleaes let me know why this happened?
0L4S){LG9K5`GC})}J7_8

Regards,

Scott

Question on downloading secret.py file

How can we download the secret.py file, I only got the link of IEX_CLOUD_API_TOKEN = 'Tpk_059b97af715d417d9f49f50b51b1c448' and the result is like this. I appreciate your help first.
Screenshot 2022-05-13 031810

KeyError: 'WLTW'

Here is my code:

def chunks(lst, n): for i in range(0, len(lst), n): yield lst[i:i + n]

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:
batch_api_call_url = f'https://sandbox.iexapis.com/stable/stock/market/batch?symbols={symbol_string}&types=quote&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

Here is the error code:

(Cannot paste the pic here for some reason)

But i get a KeyError: 'WLTW'

I have no idea how to fix this, and i can't find any result on google. Please help.

JSONDecodeError

Hello! I am facing JSON Decode Error when running the below code.

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:
batch_api_call_url = f'https://sandbox.iexapis.com/stable/stock/market/batch?symbols={symbol_string}&types=quote&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

I was surprised to see the response of the batch api's

Out of 6 batch api responses, I'm getting 403 in random for some 3 responses every time I run the code. I'm confused.

Help me out

I keep getting JSONDecodeError

My code from the section "Looping Through The Tickers in Our List of Stocks":
Screen Shot 2022-01-19 at 21 15 14

The error:
Screen Shot 2022-01-19 at 21 15 49

I don't understand what is wrong with my code, i wrote exactly like code from the Algorithmic Trading in Python Course.

And when i print the final_dataframe, the output only shows 484 stocks, and not 505 as in the .csv document? Why is that?

Screen Shot 2022-01-19 at 21 20 05

S&P 500 stocks: getting 600 stocks after the batch_api_call_url instead of 505 and last stock is CME and not ZTS

Hi,
after executing the piece of code where we use the batch_api_call_url my final_dataframe contains only the first 100 stocks, but repeats them 6 times so i end up with 600 stocks with the last one being CME. It seems as if the final_dataframe.append function is not doing a proper job.

`for symbol_string in symbol_strings:
batch_api_call_url = f'https://sandbox.iexapis.com/stable/stock/market/batch?symbols={symbol_string}&types=quote&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`

Please advise,

Best, Stefan

001_equal_weight_S&P_500.ipynb

Hi Nick,
I am beginner of anything programming. I tried this file by myself for learning purpose and after saving excel file (recommended stock) it gives 'NA' rather than any value on ticker 506, column 'number of shares to buy'.

error when trying to open the jupyter notebooks

Hi, I received this error when I downloaded the jupyter notebooks and tried to open it: Unreadable Notebook: directoryname\001_equal_weight_S&P_500.ipynb NotJSONError("Notebook does not appear to be JSON: '\n\n\n\n\n\n\n\n<html la..."). May I know how to rectify it?

KeyError: 'WLTW'

A symbol from the list may need to be updated for the iex sandbox

append method is deprecated

I get this error

FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
final_dataframe = final_dataframe.append(

Have tried several things now with the pd.concat without luck. It's in "Looping Through The Tickers in Our List of Stocks"

final_dataframe = pd.DataFrame(columns = my_columns) for stock in stocks["Ticker"][:4]: 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([symbol, data['latestPrice'], data['marketCap'], 'N/A'], index = my_columns), ignore_index = True)

Error in batch API call section

I'm getting this error--the finished code is throwing a different error when I C&P it in. Any ideas? Thanks everyone and apologies if this is a noob question! The course is great and I'm a former code writer jumping in the deep end to learn some Python.

data_error_msg

Key Error: DISCA

I think there is something wrong with pulling the DISCA ticker data. When I remove the [:1] limit for looping to take all tickers at a time, it shows error with Key Error : DISCA.

Number of Shares to Buy is extremely low on my recommended_trades.xlsx

The Number of Shares to Buy i get when my code has run is extremely low compared to what is displayed on the algorithmic trading video. I dont understand why?

My recommended_trades.xlsx file:
Screen Shot 2022-01-26 at 18 44 03

And my code:
`portfolio_size = input("Enter the value of your portfolio:")
try:
val = float(portfolio_size)
#print(val)
except ValueError:
print("That's not a number \nPlease try again:")
portfolio_size = input("Enter the value of your portfolio:")
val = float(portfolio_size)

position_size = val/len(final_dataframe.index)

for i in range(0, len(final_dataframe.index)):
final_dataframe.loc[i,'Number of Shares to Buy'] = math.floor(position_size/final_dataframe.loc[i,"Stock Price"])
final_dataframe`

My output:
Screen Shot 2022-01-26 at 19 00 32

The Algorithmic Trading in Python video by nickmcullum:
Screen Shot 2022-01-26 at 18 45 09

Testing Sandbox Deprecated

I am getting a 403 error when making API call for AAPL around minute 41 of the video. Is this because it is deprecated? Is there a work around?

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)
in
8 for row in hqm_dataframe.index:
9 for time_period in time_periods:
---> 10 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
11
12 for time_period in time_periods:

~\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!

Loop indexing fail

"Calculating the Number of Shares to Buy" section in 001_equal_weight_S&P_500.ipynb loop does not loop over whole dataframe. Loving the course btw!

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.