QuantConnect Tutorials

repository·master·Indexed 20 days ago

https://github.com/quantconnect/tutorials

A collection of educational tutorials in Jupyter notebook and HTML formats designed to teach financial concepts and their implementation using the LEAN algorithmic trading engine. The repository includes an introduction to financial Python covering data types, logical operations, loops, functions, and object-oriented programming.

Tokens
15.9K
Snippets
60
Records
64
Agent score
72%

What's inside quantconnect-tutorials

  1. Overview of QuantConnect LEAN Tutorials

    master

    This repository contains a collection of WordPress and Jupyter notebook tutorials designed to demonstrate financial concepts using the LEAN engine.

    Structure and Requirements:

    • Tutorials are organized into folders by Category and Tutorial Series.
    • Naming Convention: For a tutorial to display correctly, the Jupyter notebook file and its associated HTML webpage must have matching filenames. The HTML files are processed and displayed via WordPress.
  2. Perform logical operations with and, or, and not

    master

    Combine multiple boolean expressions using logical operators:

    • and: Returns True if both statements are true.
    • or: Returns True if at least one of the statements is true.
    • not: Reverses the result (returns False if the result is true).
    print 2 > 1 and 3 > 2
    print 2 > 1 or 3 < 2
    print not (3 < 2)
  3. Sort lists and iterables

    master

    Python provides two ways to sort data:

    1. sorted(iterable, key=..., reverse=...): Returns a new sorted list from the items in the iterable. Use the key parameter to specify a function (like a lambda) to customize the sort logic (e.g., sorting a list of tuples by a specific index).
    2. list.sort(key=..., reverse=...): Sorts the list in-place, modifying the original list.
    # Sorting a list of tuples by the second element (price)
    price_list = [('AAPL',144.09),('GOOG',911.71),('MSFT',69),('FB',150),('WMT',75.32)]
    sorted_list = sorted(price_list, key = lambda x: x[1])
    
    # Sorting in-place in reverse order
    price_list.sort(key = lambda x: x[1], reverse = True)
  4. Manipulate lists in Python

    master

    Lists are ordered, mutable collections. Common operations include:

    • len(list): Get the number of items.
    • list[index]: Access an item by index (starting at 0).
    • list[index] = value: Update an item at a specific index.
    • list.append(value): Add an item to the end of the list.
    • list.remove(value): Remove the first occurrence of a specific value.
    • list[start:stop]: Slicing to get a sub-section of the list.
    • list[start:]: Slice from a specific index to the end.
    • list[:stop]: Slice from the beginning to a specific index.
    my_list = ['Quant','Connect',1,2,3]
    my_list.append('NewItem')
    my_list[2] = 'go'
    print(my_list[1:3])
  5. Calculate financial returns and differences

    master

    Use .pct_change() to calculate the percentage change between elements (returns) and .diff() to calculate the absolute difference between elements.

    # Calculate percentage change (returns)
    returns = aapl_bar.Close.pct_change()
    
    # Calculate absolute difference
    diff = last_day.diff()
  6. Calculate Historical Volatility from Price Data

    master

    To calculate historical volatility, compute the log returns of adjusted close prices, find the mean return, and then calculate the standard deviation of the squared differences from the mean. Annualize the result by multiplying by the square root of the number of trading days (typically 252).

    # Assuming 'data' is a pandas DataFrame with an 'Adj. Close' column
    close = data['2016-01':'2016-08']['Adj. Close']
    r = diff(log(close))
    r_mean = mean(r)
    diff_square = [(r[i]-r_mean)**2 for i in range(0,len(r))]
    std = sqrt(sum(diff_square)*(1.0/(len(r)-1)))
    vol = std*sqrt(252)
  7. Control loop execution with break and continue

    master

    You can modify the behavior of a loop using these keywords:

    • break: Immediately terminates the loop entirely.
    • continue: Skips the rest of the current iteration and moves to the next item in the sequence.
    stocks = ['AAPL','GOOG','IBM','FB','F','V', 'G', 'GE']
    
    # Using break to stop at 'FB'
    for i in stocks:
        print i
        if i == 'FB':
            break
    
    # Using continue to skip 'FB'
    for i in stocks:
        if i == 'FB':
            continue
        print i
  8. Use list comprehensions for concise list creation

    master

    List comprehensions provide a shorter syntax when you want to create a new list based on the values of an existing list. They can include optional if conditions for filtering.

    • Basic comprehension: [expression for item in iterable]
    • Comprehension with filter: [expression for item in iterable if condition]
    • Nested comprehension: [(x, y) for x in list1 for y in list2 if condition]
    # Basic: squaring numbers
    list = [1,2,3,4,5]
    squares = [x**2 for x in list]
    
    # Filtering: selecting specific stocks
    stocks = ['AAPL','GOOG','IBM','FB','F','V', 'G', 'GE']
    selected = ['AAPL','IBM']
    new_list = [x for x in stocks if x in selected]
    
    # Nested: creating coordinate pairs
    print [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
  9. Concatenate DataFrames and Series

    master

    Use pd.concat() to combine multiple Pandas objects.

    • Use axis=1 to concatenate side-by-side (columns).
    • Use axis=0 to concatenate vertically (rows).
    • Use join='inner' to keep only the indices present in both objects.
    # Concatenate Series side-by-side as columns
    data_frame = pd.concat([s1, s2], axis=1)
    
    # Concatenate DataFrames vertically (stacking rows)
    concat_rows = pd.concat([aapl_bar, df_2017], axis=0)
    
    # Concatenate side-by-side with inner join (intersection of indices)
    concat_inner = pd.concat([aapl_bar, df_volume], axis=1, join='inner')