Algorithmic Trading Python

Algorithmic Trading with Python

Algorithmic trading (also called automated trading, black-box trading, or algo-trading) uses a computer program that follows a defined set of instructions (an algorithm) to place a trade.
Momentum investing is a trading strategy in which investors buy securities that are rising and sell them when they look to have peaked.
The goal is to work with volatility by finding buying opportunities in short-term uptrends and then sell when the securities start to lose momentum.Then, the investor takes the cash and looks for the next short-term uptrend, or buying opportunity, and repeats the process.
In this blog, we will show you show to do a simple momentum investing algorithmic trading using Python. First we import the list of SP 500 stock list using Pandas

stocks = pd.read_csv('https://raw.githubusercontent.com/tertiarycourses/datasets/master/sp_500_stocks.csv')

Next we use the batch IEX Cloud API to retrieve the one year price return data

def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    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])

my_columns = ['Ticker', 'Price', 'One-Year Price Return', 'Number of Shares to Buy']


def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    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])

my_columns = ['Ticker', 'Price', 'One-Year Price Return', 'Number of Shares to Buy']

The result is shown below

Then we remove those low momentum stocks

final_dataframe.sort_values('One-Year Price Return', ascending = False, inplace = True)
final_dataframe = final_dataframe[:51]
final_dataframe.reset_index(drop = True, inplace = True)
final_dataframe

We can now input our portfolio an compute the number for share to buy for each stock using momentum investing strategy.

def portfolio_input():
    global portfolio_size
    portfolio_size = input("Enter the value of your portfolio:")

    try:
        val = float(portfolio_size)
    except ValueError:
        print("That's not a number! \n Try again:")
        portfolio_size = input("Enter the value of your portfolio:")

portfolio_input()
print(portfolio_size)

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

The result is shown below


References:

Relevant Courses

September 21, 2021