### Defining and Calling Basic Function Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Defines a Python function `say_hi` that prints a fixed string "Welcome to QuantConnect". It then calls the function to execute the print statement. ```python def say_hi(): print('Welcome to QuantConnect') say_hi() ``` -------------------------------- ### Instantiating Class Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Creates two instances (objects) of the `stock` class: `apple` and `google`. Each instance is initialized with specific ticker, open, close, and volume data provided to the `__init__` constructor. ```python apple = stock('AAPL', 143.69, 144.09, 20109375) google = stock('GOOG', 898.7, 911.7, 1561616) ``` -------------------------------- ### Using Range Function Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Shows examples of the built-in Python `range` function. It demonstrates `range(stop)`, `range(start, stop)`, and `range(start, stop, step)` to generate sequences of numbers, printing the resulting range objects. ```python print(range(10)) print(range(1,11)) print(range(1,11,2)) ``` -------------------------------- ### Defining and Calling Simple Function Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Defines a Python function `product` that takes two arguments `x` and `y` and returns their product. It then demonstrates calling the function with different arguments and printing the results. ```python def product(x,y): return x*y print(product(2,3)) print(product(5,10)) ``` -------------------------------- ### Slicing a List (Start to End) in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/01 Data Types and Data Structures/01 Data Types and Data Structures.ipynb This snippet demonstrates list slicing using the `[start:]` notation. It extracts a sublist starting from the index `start` and includes all elements until the end of the list. The original list remains unchanged. ```python print(my_list[1:]) ``` -------------------------------- ### Slicing a String (Start to End) in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/01 Data Types and Data Structures/01 Data Types and Data Structures.ipynb This snippet demonstrates string slicing using the `[start:]` notation. It extracts a substring starting from the index `start` and includes all characters until the end of the string. Strings are immutable, so slicing returns a new string. ```python my_str = 'Welcome to QuantConnect' print(my_str[8:]) ``` -------------------------------- ### Slicing a Tuple (Start to End) in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/01 Data Types and Data Structures/01 Data Types and Data Structures.ipynb This snippet demonstrates tuple slicing using the `[start:]` notation. It extracts a subtuple starting from the index `start` and includes all elements until the end of the tuple. Although tuples are immutable, slicing returns a new tuple. ```python my_tuple = ('Welcome','to','QuantConnect') print(my_tuple[1:]) ``` -------------------------------- ### Inspecting Class Instance Attributes with Dir Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Uses the built-in `dir()` function to get a list of names (attributes and methods) defined for an object instance (`apple`). This helps inspect the object's contents, including both defined members and inherited/dynamic ones. ```python dir(apple) ``` -------------------------------- ### Slicing a List (Start to End) in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/01 Data Types and Data Structures/01 Data Types and Data Structures.ipynb This snippet demonstrates list slicing using the `[start:end]` notation. It extracts a sublist starting from the index `start` up to, but not including, the index `end`. The original list remains unchanged. ```python my_list = ['Quant','Connect',1,2,3] print(my_list[1:3]) ``` -------------------------------- ### Defining Simple Class Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Defines a Python class named `stock` to represent stock data. The class has an `__init__` constructor to initialize ticker, open, close, volume, and calculate return. It also includes `update` and `print_return` methods to modify and display data. ```python class stock: def __init__(self, ticker, open, close, volume): self.ticker = ticker self.open = open self.close = close self.volume = volume self.rate_return = float(close)/open - 1 def update(self, open, close): self.open = open self.close = close self.rate_return = float(self.close)/self.open - 1 def print_return(): print(self.rate_return) ``` -------------------------------- ### In-place Sorting List by Key Function Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Demonstrates using the list's `sort()` *method* to sort the `price_list` in-place based on the second element (price) using a `lambda` key. Unlike `sorted()`, this modifies the original list and returns `None`. The sorted list is then printed. ```python price_list = [('AAPL',144.09),('GOOG',911.71),('MSFT',69),('FB',150),('WMT',75.32)] price_list.sort(key = lambda x: x[1]) print(price_list) ``` -------------------------------- ### Accessing Class Attributes and Methods Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Shows how to access an instance's attribute (`apple.ticker`) and call an instance's method (`google.print_return()`). It also demonstrates calling the `update` method to change an instance's data and then calling `print_return` again to show the updated value. ```python apple.ticker google.print_return() google.update(912.8,913.4) google.print_return() ``` -------------------------------- ### Getting Dictionary Keys in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/01 Data Types and Data Structures/01 Data Types and Data Structures.ipynb This snippet demonstrates how to retrieve a view object containing all the keys in a dictionary using the `.keys()` method. This view reflects changes made to the dictionary. ```python print(my_dic.keys()) ``` -------------------------------- ### Applying Lambda Function with Map and Range Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Demonstrates using the `map` function with a `lambda` function to square each number generated by `range(10)`. The result, a map object, is converted to a list. ```python list(map(lambda x: x**2, range(10))) ``` -------------------------------- ### Comment Indicating Start of Three-Stock Analysis Section Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/12 Modern Portfolio Theory/12 Modern Portfolio Theory.ipynb This is a comment in the code indicating the beginning of a subsequent section that will analyze and potentially plot the efficient frontier for a smaller selection of three stocks. ```python ###three stocks version ``` -------------------------------- ### Sorting List Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Demonstrates using the built-in `sorted()` function to sort a list of numbers in ascending order. The original list remains unchanged, and a new sorted list is returned. ```python sorted([5,2,3,4,1]) ``` -------------------------------- ### Creating and Displaying Pandas Series with Default Index in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/04 NumPy and Basic Pandas/04 NumPy and Basic Pandas.ipynb Shows how to create a Pandas Series from a Python list. By default, Pandas assigns a simple integer index starting from 0. ```python price = [143.73, 145.83, 143.68, 144.02, 143.5, 142.62] s = pd.Series(price) s ``` -------------------------------- ### Adding Dynamic Attribute to Class Instance Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Demonstrates that Python allows adding new attributes to an object instance dynamically after it has been created. It adds a `ceo` attribute to the `apple` instance and then accesses it. This attribute is specific to the `apple` instance. ```python apple.ceo = 'Tim Cook' apple.ceo ``` -------------------------------- ### Iterating List Using Range and Index Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Initializes a list of strings `tickers`. It then prints the length of the list using `len()` and iterates through the list using a `for` loop with `range(len(tickers))` to access and print each element by its index. ```python tickers = ['AAPL','GOOG','IBM','FB','F','V', 'G', 'GE'] print('The length of tickers is {}'.format(len(tickers))) for i in range(len(tickers)): print(tickers[i]) ``` -------------------------------- ### Creating 1D NumPy Arrays - Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/11 Linear Algebra/11 Linear Algebra.ipynb Defines three one-dimensional NumPy arrays (vectors) named 'a', 'b', and 'c'. These arrays contain integer values and will be used in subsequent examples for stacking and matrix formation. ```python a = np.array([1,2,3]) b = np.array([2,2,2]) c = np.array([3,1,1]) ``` -------------------------------- ### Applying Function to List with Map Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Uses the built-in Python `map` function to apply the `len()` function to each element in the `tickers` list. It then converts the result (a map object) to a list and prints it, showing the length of each ticker string. ```python tickers = ['AAPL','GOOG','IBM','FB','F','V', 'G', 'GE'] print(list(map(len,tickers))) ``` -------------------------------- ### Slicing a List (Beginning to End) in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/01 Data Types and Data Structures/01 Data Types and Data Structures.ipynb This snippet demonstrates list slicing using the `[:end]` notation. It extracts a sublist starting from the beginning of the list up to, but not including, the index `end`. The original list remains unchanged. ```python print(my_list[:3]) ``` -------------------------------- ### Instantiating Child Class and Accessing Parent Members Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Creates an instance `aa` of the `child` class, initializing only the `name` attribute. It prints the `name`. It then attempts to call inherited `update` and `print_return` methods and access parent attributes. Note that calling parent methods that rely on attributes initialized in the parent's `__init__` (which was overridden) will likely result in errors. ```python aa = child('aa') print(aa.name) aa.update(100,102) print(aa.open) print(aa.close) print(aa.print_return()) ``` -------------------------------- ### Sorting List of Tuples Descending by Key Function Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Similar to the previous snippet, this sorts a list of stock tuples by price (second element). It uses the `sorted()` function with a `lambda` key and sets the `reverse` parameter to `True` to sort the list in descending order. ```python price_list = [('AAPL',144.09),('GOOG',911.71),('MSFT',69),('FB',150),('WMT',75.32)] sorted(price_list, key = lambda x: x[1],reverse = True) ``` -------------------------------- ### Simulating Points on the Efficient Frontier in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/12 Modern Portfolio Theory/12 Modern Portfolio Theory.ipynb This snippet generates a range of target annual returns starting from the risk-free rate up to a value slightly higher than the maximum individual stock return. It then iterates through this range, calling the `min_var_generator` for each target rate to find the corresponding minimum portfolio standard deviation, thus tracing points along the efficient frontier. ```python simu_rate = [x for x in np.arange(rf,max(mean_list)*1.2,0.0001)] simu_var = [] for i in simu_rate: try: res = min_var_generator(i) simu_var.append(res[1]) except: print i ``` -------------------------------- ### Accessing List Elements by Index in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/01 Data Types and Data Structures/01 Data Types and Data Structures.ipynb This snippet demonstrates how to get the number of elements in a list using `len()` and access specific elements using zero-based indexing. It shows how to access the first element (`[0]`) and the last element (`[len(my_list) - 1]`). ```python my_list = ['Quant', 'Connect', 1,2,3] print(len(my_list)) print(my_list[0]) print(my_list[len(my_list) -1]) ``` -------------------------------- ### Calculating Binomial Probabilities for Multiple Outcomes in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/07 Random Variables and Distributions/07 Random Variable and Distributions.ipynb This code iterates from 1 to 10, calculating the estimated binomial probability of getting `i` successes using the previously defined `binomial` simulation function for each value of `i`. The results are stored in a list and then converted into a Pandas Series for better indexing and display. ```python prob = [] for i in range(1,11): prob.append(binomial(i)) prob_s = pd.Series(prob,index = range(1,11)) print prob_s ``` -------------------------------- ### Estimating Binomial Probability via Simulation in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/07 Random Variables and Distributions/07 Random Variable and Distributions.ipynb This function `binomial` estimates the probability of getting exactly `number` successes in 10 trials, where each trial has a 70% success rate. It does this by simulating 10 trials 10,000 times, counting how many simulations result in exactly `number` successes, and dividing by the total number of simulations. ```python def binomial(number): l = [] for i in range(10000): res = [trial() for x in range(10)] l.append(sum(res)) return len([x for x in l if x == number])/float(len(l)) print binomial(8) ``` -------------------------------- ### Initializing QuantLib Pricing Environment Parameters Source: https://github.com/quantconnect/tutorials/blob/master/06 Introduction to Options[]/08 Local Volatility and Stochastic Volatility/08 Local Volatility and Stochastic Volatility.ipynb Sets up the core parameters and objects needed for QuantLib pricing, including day count convention, calendar, calculation date (from data fetch time), spot price, dividend yield, risk-free rate, dividend rate, and constructs flat yield term structures. These are prerequisites for defining financial models. ```python day_count = ql.Actual365Fixed() calendar = ql.UnitedStates() calculation_date = ql.Date(opt._quote_time.day,opt._quote_time.month,opt._quote_time.year) spot = opt.underlying_price ql.Settings.instance().evaluationDate = calculation_date dividend_yield = ql.QuoteHandle(ql.SimpleQuote(0.0)) risk_free_rate = 0.01 dividend_rate = 0.0 flat_ts = ql.YieldTermStructureHandle( ql.FlatForward(calculation_date, risk_free_rate, day_count)) dividend_ts = ql.YieldTermStructureHandle( ql.FlatForward(calculation_date, dividend_rate, day_count)) ``` -------------------------------- ### Initializing Plotting Libraries Python Source: https://github.com/quantconnect/tutorials/blob/master/06 Introduction to Options[]/03 Put-Call Parity and Arbitrage Strategies/02 Put-Call Parity and Arbitrage Strategies.ipynb Imports matplotlib.pyplot for plotting and uses %pylab inline to enable interactive plotting directly within the environment (like a Jupyter notebook). This prepares the environment for generating plots. ```python import matplotlib.pyplot as plt %pylab inline ``` -------------------------------- ### Fetching Financial Data with Quandl in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/09 Simple Linear Regression/09 Simple Linear Regression.ipynb Imports necessary libraries and fetches historical stock data for SPY and AMZN from Quandl, storing the results in pandas DataFrames. Requires Quandl API key configuration if not already set up. ```python import numpy as np import pandas as pd import quandl spy_table = quandl.get('LSE/SPY5') amzn_table = quandl.get('WIKI/AMZN') ``` -------------------------------- ### Importing Necessary Libraries for Option Analysis Source: https://github.com/quantconnect/tutorials/blob/master/06 Introduction to Options[]/08 Local Volatility and Stochastic Volatility/08 Local Volatility and Stochastic Volatility.ipynb Imports standard libraries like pandas and numpy, along with QuantLib and pandas-datareader for financial data and quantitative analysis. These libraries are essential for fetching market data, performing calculations, and utilizing the Heston model. ```python import pandas as pd from numpy import sqrt,mean,log,diff import QuantLib as ql from pandas_datareader.data import Options import pandas_datareader.data as web import datetime ``` -------------------------------- ### Importing Libraries for Portfolio Analysis Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/12 Modern Portfolio Theory/12 Modern Portfolio Theory.ipynb This snippet imports the necessary Python libraries for data manipulation (pandas, numpy), financial data fetching (quandl), optimization (cvxopt, scipy.optimize), plotting (matplotlib), and random number generation (random). These libraries are fundamental prerequisites for running the subsequent portfolio analysis code. ```python import pandas as pd import numpy as np import quandl from cvxopt import solvers from cvxopt import matrix import matplotlib.pyplot as plt from scipy.optimize import minimize import random ``` -------------------------------- ### Using Python Comparison Operators Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/02 Logical Operations and Loops/02 Logical Operations and Loops.ipynb This snippet demonstrates basic comparison operators in Python, evaluating expressions for equality (`==`), inequality (`!=`), greater than or equal to (`>=`), and printing the resulting boolean values (True or False). It shows how to check relationships between numbers. ```python print 1 == 0 print 1 == 1 print 1 != 0 print 5 >= 5 print 5 >= 6 ``` -------------------------------- ### Formatting Strings with format() in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/01 Data Types and Data Structures/01 Data Types and Data Structures.ipynb This snippet demonstrates modern string formatting using the `.format()` method. It allows inserting values into placeholders `{}` within a string. This is a flexible way to build strings from variables. ```python my_time = 'Hour: {}, Minute:{}'.format('09','43') print(my_time) ``` -------------------------------- ### Importing Libraries for Financial Analysis in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/14 Fama-French Multi-Factor Models/14 Fama-French Multi-Factor Models.ipynb This snippet imports all necessary Python libraries required for the script, including `quandl` for data fetching, `pandas` and `numpy` for data manipulation, `statsmodels` for statistical modeling, `matplotlib` and `seaborn` for plotting, `scipy` for statistics and optimization, and `cvxopt` for convex optimization. ```python import quandl import pandas as pd import numpy as np import statsmodels.formula.api as sm import matplotlib.pyplot as plt from scipy.stats.mstats import normaltest import time from cvxopt import matrix import seaborn as sns import statsmodels.tsa.stattools as ts from scipy import stats from scipy.optimize import minimize ``` -------------------------------- ### Zipping Monte Carlo and Market Prices Together Source: https://github.com/quantconnect/tutorials/blob/master/06 Introduction to Options[]/08 Local Volatility and Stochastic Volatility/08 Local Volatility and Stochastic Volatility.ipynb Creates an iterator of tuples, pairing each Monte Carlo calculated price with its corresponding market premium. This is useful for side-by-side comparison or further analysis. ```python zip(heston, premium) ``` -------------------------------- ### Fetching Data and Calculating Population Statistics Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/08 Confidence Interval and Hypothesis Testing/08 Confidence Interval and Hypothesis Testing.ipynb Imports necessary libraries, fetches historical SPY data using Quandl, calculates the daily log returns, and then computes and prints the mean and standard deviation of these returns, treated as population parameters. Requires `quandl`, `pandas`, `numpy`, and `matplotlib` libraries. ```python import matplotlib.pyplot as plt import numpy as np import pandas as pd import quandl spy_table = quandl.get('LSE/SPY5') spy_total = spy_table[['Last Close']] spy_log_return = np.log(spy_total['Last Close']).diff().dropna() print 'Population mean:', np.mean(spy_log_return) print 'Population standard deviation:',np.std(spy_log_return) ``` -------------------------------- ### Generating List using Python List Comprehension Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/02 Logical Operations and Loops/02 Logical Operations and Loops.ipynb This snippet demonstrates creating a new list (`squares`) using a list comprehension in Python. It provides a concise and readable way to generate a list by applying an expression (`x**2`) to each item (`x`) in an iterable (`list`). ```python list = [1,2,3,4,5] squares = [x**2 for x in list] print squares ``` -------------------------------- ### Creating QuantLib Heston Model Calibration Helpers Source: https://github.com/quantconnect/tutorials/blob/master/06 Introduction to Options[]/08 Local Volatility and Stochastic Volatility/08 Local Volatility and Stochastic Volatility.ipynb Iterates through the extracted strike prices for the selected expiry. For each strike, it creates a HestonModelHelper object using the market premium as the implied volatility source. These helpers link market data points to the Heston model and are used during calibration. ```python heston_helpers = [] date = expiration_dates[expiry_index] for j, s in enumerate(strikes): t = (date - calculation_date) p = ql.Period(t, ql.Days) sigma = premium[j] helper = ql.HestonModelHelper(p, calendar, spot, s, ql.QuoteHandle(ql.SimpleQuote(sigma)), flat_ts, dividend_ts) helper.setPricingEngine(engine) heston_helpers.append(helper) ``` -------------------------------- ### Creating and Printing a List in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/01 Data Types and Data Structures/01 Data Types and Data Structures.ipynb This snippet shows how to create a list containing elements of different data types (strings and integers) and then print the entire list to the console. Lists are ordered, mutable collections. ```python my_list = ['Quant', 'Connect', 1,2,3] print(my_list) ``` -------------------------------- ### Retrieving Quandl Data and Calculating Log Returns in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/06 Rate of Return, Mean and Variance/06 Rate of Return, Mean and Variance.ipynb This snippet demonstrates how to fetch historical stock data (AAPL) from Quandl using its API, filter it by date and columns, calculate the log price, and then compute the daily log return using the .diff() method on the log price series. It requires a valid Quandl API key. ```python import numpy as np import quandl quandl.ApiConfig.api_key = 'tAyfv1zpWnyhmDsp91yv' #get quandl data aapl_table = quandl.get('WIKI/AAPL') aapl = aapl_table.loc['2017-3',['Open','Close']] #take log return aapl['log_price'] = np.log(aapl.Close) aapl['log_return'] = aapl.log_price.diff() print(aapl) ``` -------------------------------- ### Downloading Stock Data with Quandl in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/10 Multiple Linear Regression/10 Multiple Linear Regression.ipynb This code snippet sets the Quandl API configuration and downloads historical daily closing prices for several stocks (GOOG, AMZN, EBAY, WMT, AAPL) using the Quandl WIKI dataset. A valid Quandl API key is required for this operation. The data for each ticker is stored in separate pandas DataFrames. ```python quandl.ApiConfig.api_key = 'tAyfv1zpWnyhmDsp91yv' goog_table = quandl.get('WIKI/GOOG') amzn_table = quandl.get('WIKI/AMZN') ebay_table = quandl.get('WIKI/EBAY') wal_table = quandl.get('WIKI/WMT') aapl_table = quandl.get('WIKI/AAPL') ``` -------------------------------- ### Sorting List of Tuples by Key Function Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Sorts a list of tuples, where each tuple represents stock information (ticker, price). It uses the `sorted()` function with a `lambda` function as the `key` argument to sort the list based on the second element of each tuple (the price). ```python price_list = [('AAPL',144.09),('GOOG',911.71),('MSFT',69),('FB',150),('WMT',75.32)] sorted(price_list, key = lambda x: x[1]) ``` -------------------------------- ### Importing Math and Statistics Libraries (Python) Source: https://github.com/quantconnect/tutorials/blob/master/06 Introduction to Options[]/05 Options Pricing Black Scholes Merton Model/05 Option Pricing Black Scholes Merton Model.ipynb Imports required mathematical functions (`log`, `sqrt`, `exp`, `pi`) from the standard `math` module and the `norm` object (providing CDF and PDF for the normal distribution) from the `scipy.stats` library. These imports are essential prerequisites for performing calculations within the Black-Scholes-Merton model. ```python from math import log, sqrt, exp, pi from scipy.stats import norm ``` -------------------------------- ### Simulating Multiple Binomial Trials and Summing Results in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/07 Random Variables and Distributions/07 Random Variable and Distributions.ipynb This code performs 10 simulations of the `trial` function (which has a 70% success rate) and stores the results (0 or 1) in a list. It then calculates and prints the sum of these results, effectively showing the number of successes in 10 trials. ```python res = [trial() for x in range(10)] print sum(res) ``` -------------------------------- ### Initializing Stock Objects and List in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/12 Modern Portfolio Theory/12 Modern Portfolio Theory.ipynb This snippet defines a list of stock ticker symbols and initializes instances of the `stock` class for each ticker. It then appends these `stock` objects to a list called `stocks`, while also creating global variables for each ticker symbol pointing to their respective `stock` objects. ```python tickers = ['KO','JNJ','PFE','NKE','PG','WMT','MMM','IBM'] stocks = [] leng = len(tickers) for i in tickers: vars()[i] = stock(i) stocks.append(vars()[i]) ``` -------------------------------- ### Importing Python Libraries for Financial Analysis and Plotting Source: https://github.com/quantconnect/tutorials/blob/master/06 Introduction to Options[]/07 Historical Volatility and Implied Volatility/07 Historical Volatility and Implied Volatility.ipynb This snippet imports necessary libraries for data manipulation (pandas, numpy), data fetching (quandl, pandas_datareader), statistical calculations (scipy.stats), interpolation (scipy.interpolate), and plotting (matplotlib). It also includes a `%pylab inline` command for interactive plotting in environments like Jupyter notebooks. ```Python import pandas as pd from numpy import sqrt,mean,log,diff import quandl import scipy.stats as stats from scipy import interpolate from scipy.interpolate import Rbf import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib import animation from pandas_datareader.data import Options import pandas_datareader.data as web import datetime %pylab inline ``` -------------------------------- ### Defining Class with Inheritance Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Defines a new class `child` that inherits from the `stock` class. It provides its own `__init__` method, which only initializes a `name` attribute, effectively overriding the parent's `__init__` and not calling it implicitly. Instances will lack attributes defined in the parent's `__init__`. ```python class child(stock): def __init__(self,name): self.name = name ``` -------------------------------- ### Fetching Stock Data and Calculating Metrics from Quandl in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/12 Modern Portfolio Theory/12 Modern Portfolio Theory.ipynb This snippet iterates through the list of initialized `stock` objects. For each stock, it fetches historical adjusted closing price data from Quandl's WIKI dataset, calculates log returns since 2008, and then annualizes the mean return and standard deviation, storing these metrics as attributes of the respective `stock` objects. ```python for i in stocks: table = quandl.get('WIKI/%s'%i.ticker) i.rate = np.log(table['Adj. Close']).diff()['2008':] i.mean = np.mean(i.rate)*252 i.std = np.std(i.rate)*np.sqrt(252) ``` -------------------------------- ### Applying Lambda Function with Map to Multiple Lists Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/03 Functions and Objective-Oriented Programming/03 Functions and Objective-Oriented Programming.ipynb Shows the `map` function applying a `lambda` function that takes two arguments. It processes two lists of equal length element-wise, adding corresponding elements using the `lambda` function. The result is converted to a list. ```python list(map(lambda x, y: x+y, [1,2,3,4,5],[5,4,3,2,1])) ``` -------------------------------- ### Building List with Python For Loop and Append Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/02 Logical Operations and Loops/02 Logical Operations and Loops.ipynb This snippet shows a common pattern for creating a new list (`squares`) by iterating over an existing sequence using a `for` loop and adding processed items (squares of numbers) to the new list using the `append()` method. ```python squares = [] for i in [1,2,3,4,5]: squares.append(i**2) print squares ``` -------------------------------- ### Analyzing NASDAQ Small Cap Returns with Fama-French Factors in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/14 Fama-French Multi-Factor Models/14 Fama-French Multi-Factor Models.ipynb This snippet fetches data for the NASDAQ US Small Cap Index, calculates its log returns, and merges it with the Fama-French factors. It then fits an OLS regression model of the small-cap index returns on the Market, SMB, and HML factors and prints the regression summary. ```python small_table = quandl.get('NASDAQOMX/NQUSS') small = np.log(small_table['Index Value']).diff().dropna() small.name = 'small' small_df = pd.concat([fama_5,small],axis = 1).dropna() small_model = sm.ols(formula = 'small~mkt+SMB+HML',data = small_df).fit() print small_model.summary() ``` -------------------------------- ### Calculating Theoretical Binomial Probabilities using Factorials in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/07 Random Variables and Distributions/07 Random Variable and Distributions.ipynb This snippet calculates the theoretical probability of getting exactly 7 successes and exactly 8 successes in 10 trials with a success probability of 0.7. It uses the binomial probability formula directly, utilizing the `factorial` function from the `math` module. ```python print (float(factorial(10))/(factorial(7)*factorial(10-7)))*(0.7**7)*(0.3**3) print (float(factorial(10))/(factorial(8)*factorial(10-8)))*(0.7**8)*(0.3**2) ``` -------------------------------- ### Solving Linear System Ax=B via linalg.solve - Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/11 Linear Algebra/11 Linear Algebra.ipynb Uses the more efficient and numerically stable `np.linalg.solve` function to find the solution vector 'x' for the linear system Ax=B, using the same matrices 'A' and 'B' defined previously. This is the preferred method for solving linear systems. ```python print(np.linalg.solve(A,B)) ``` -------------------------------- ### Setting Quandl API Key in Python Source: https://github.com/quantconnect/tutorials/blob/master/06 Introduction to Options[]/07 Historical Volatility and Implied Volatility/07 Historical Volatility and Implied Volatility.ipynb This line sets the API key for accessing data from Quandl. A valid API key is required to authenticate requests and retrieve data. ```Python quandl.ApiConfig.api_key = 'NxTUTAQswbKs5ybBbwfK' ``` -------------------------------- ### Instantiating and Using BSM Model (Python) Source: https://github.com/quantconnect/tutorials/blob/master/06 Introduction to Options[]/05 Options Pricing Black Scholes Merton Model/05 Option Pricing Black Scholes Merton Model.ipynb Creates an instance of the `BsmModel` class with specific parameters representing a call option. It then calls the `bsm_price` method on the created instance to calculate the option's theoretical price based on the initialized parameters. This demonstrates how to use the previously defined class to perform a price calculation. ```python a = BsmModel('c', 42, 35, 0.1, 90.0/365, 0.2) a.bsm_price() ``` -------------------------------- ### Calculating Binomial Probability in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/10 Multiple Linear Regression/10 Multiple Linear Regression.ipynb This snippet calculates the probability of getting exactly 7 successes in 10 independent Bernoulli trials, where the probability of success in a single trial is 0.7 and the probability of failure is 0.3. It uses the binomial probability formula, which involves factorials and powers of the success and failure probabilities. This calculation appears unrelated to the financial analysis conducted in the other snippets. ```python print((float(factorial(10))/(factorial(7)*factorial(10-7)))*(0.7**7)*(0.3**3)) ``` -------------------------------- ### Defining QuantLib Heston Process and Analytic Engine Source: https://github.com/quantconnect/tutorials/blob/master/06 Introduction to Options[]/08 Local Volatility and Stochastic Volatility/08 Local Volatility and Stochastic Volatility.ipynb Defines the Heston stochastic process with initial guess parameters for variance, mean reversion, long-term variance, correlation, and vol-of-vol. An analytic Heston model is built upon this process, and an analytic pricing engine is associated with the model, preparing it for calibration or pricing. ```python # dummy parameters initial_var = 0.2; rate_reversion = 0.5; long_term_var = 0.2; corr = -0.75; vol_of_vol = 0.2; # initial_var = 0.2; rate_reversion = 0.15; long_term_var = 0.6; corr = -0.75; vol_of_vol = 0.2; process = ql.HestonProcess(flat_ts, dividend_ts, ql.QuoteHandle(ql.SimpleQuote(spot)), initial_var, rate_reversion, long_term_var, vol_of_vol, corr) model = ql.HestonModel(process) engine = ql.AnalyticHestonEngine(model) ``` -------------------------------- ### Implementing Black-Scholes-Merton Model Class (Python) Source: https://github.com/quantconnect/tutorials/blob/master/06 Introduction to Options[]/05 Options Pricing Black Scholes Merton Model/05 Option Pricing Black Scholes Merton Model.ipynb Defines the `BsmModel` class for calculating European option prices using the BSM formula. The constructor initializes the model with parameters like price, strike, rate, expiry, volatility, and option type. It includes methods for calculating d1, d2, the standard normal CDF (n), its derivative (dn), and the final option price based on the option type ('c' for call, 'p' for put). Requires `math` and `scipy.stats.norm`. ```python class BsmModel: def __init__(self, option_type, price, strike, interest_rate, expiry, volatility, dividend_yield=0): self.s = price # Underlying asset price self.k = strike # Option strike K self.r = interest_rate # Continuous risk fee rate self.q = dividend_yield # Dividend continuous rate self.T = expiry # time to expiry (year) self.sigma = volatility # Underlying volatility self.type = option_type # option type "p" put option "c" call option def n(self, d): # cumulative probability distribution function of standard normal distribution return norm.cdf(d) def dn(self, d): # the first order derivative of n(d) return norm.pdf(d) def d1(self): d1 = (log(self.s / self.k) + (self.r - self.q + self.sigma ** 2 * 0.5) * self.T) / (self.sigma * sqrt(self.T)) return d1 def d2(self): d2 = (log(self.s / self.k) + (self.r - self.q - self.sigma ** 2 * 0.5) * self.T) / (self.sigma * sqrt(self.T)) return d2 def bsm_price(self): d1 = self.d1() d2 = d1 - self.sigma * sqrt(self.T) if self.type == 'c': price = exp(-self.r*self.T) * (self.s * exp((self.r - self.q)*self.T) * self.n(d1) - self.k * self.n(d2)) return price elif self.type == 'p': price = exp(-self.r*self.T) * (self.k * self.n(-d2) - (self.s * exp((self.r - self.q)*self.T) * self.n(-d1))) return price else: print "option type can only be c or p" ``` -------------------------------- ### Performing Basic Arithmetic Operations in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/01 Data Types and Data Structures/01 Data Types and Data Structures.ipynb This snippet demonstrates standard arithmetic operations in Python: addition (`+`), subtraction (`-`), multiplication (`*`), division (`/`), and exponentiation (`**`). It prints the result of each operation with a descriptive label. ```python print("Addition ", 1+1) print("Subtraction ", 5-2) print("Multiplication ", 2*3) print("Division ", 10/2) print('exponent', 2**3) ``` -------------------------------- ### Applying Python Logical Operators Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/02 Logical Operations and Loops/02 Logical Operations and Loops.ipynb This snippet illustrates the use of logical operators (`and`, `or`) in Python to combine boolean expressions. It evaluates compound conditions based on the truthiness of individual comparisons and prints the final boolean outcome. ```python print 2 > 1 and 3 > 2 print 2 > 1 and 3 < 2 print 2 > 1 or 3 < 2 print 2 < 1 and 3 < 2 ``` -------------------------------- ### Creating and Displaying Pandas Series with Custom Index in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/04 NumPy and Basic Pandas/04 NumPy and Basic Pandas.ipynb Illustrates creating a Pandas Series and assigning a custom list of labels as its index. This allows accessing elements using these defined labels. ```python s = pd.Series(price,index = ['a','b','c','d','e','f']) s ``` -------------------------------- ### Importing Libraries for Financial Analysis in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/10 Multiple Linear Regression/10 Multiple Linear Regression.ipynb This snippet imports the necessary Python libraries required for financial data analysis, including numerical operations (numpy), data manipulation (pandas), data downloading (quandl), plotting (matplotlib.pyplot), and statistical modeling (statsmodels.formula.api). These libraries provide the tools for subsequent data processing, regression, and visualization tasks. ```python import numpy as np import pandas as pd import quandl import matplotlib.pyplot as plt import statsmodels.formula.api as sm ``` -------------------------------- ### Organizing Sample Statistics in Pandas Series Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/08 Confidence Interval and Hypothesis Testing/08 Confidence Interval and Hypothesis Testing.ipynb Recalculates the mean and standard deviation for the 10-day and 1000-day samples of `spy_log_return` and stores these four values in a pandas Series with descriptive labels. This snippet demonstrates structuring related statistics together. ```python mean_10 = np.mean(spy_log_return.tail(10)) std_10 = np.std(spy_log_return.tail(10)) mean_1000 = np.mean(spy_log_return.tail(1000)) std_1000 = np.std(spy_log_return.tail(1000)) s = pd.Series([mean_10,std_10,mean_1000,std_1000],index = ['mean_10', 'std_10','mean_1000','std_1000']) print s ``` -------------------------------- ### Creating a Dictionary in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/01 Data Types and Data Structures/01 Data Types and Data Structures.ipynb This snippet shows how to create a dictionary using curly braces `{}` with key-value pairs. Keys must be unique and immutable, while values can be of any data type. Dictionaries are unordered collections. ```python my_dic = {'AAPL':'AAPLE', 'FB':'FaceBook', 'GOOG':'Alphabet'} ``` -------------------------------- ### Stacking Vectors into Matrix Rows - Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/11 Linear Algebra/11 Linear Algebra.ipynb Creates a new 2D array (matrix) named 'matrix2' by directly passing a list of the 1D arrays 'a', 'b', and 'c' to `np.array`. This results in the vectors being stacked as rows. The resulting matrix is printed. ```python matrix2 = np.array([a,b,c]) print(matrix2) ``` -------------------------------- ### Defining a Binomial Trial Simulation in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/07 Random Variables and Distributions/07 Random Variable and Distributions.ipynb This function `trial` simulates a single trial with a 70% probability of success. It randomly chooses a number from 1 to 10 and returns 1 if the number is 7 or less (success), and 0 otherwise (failure). This simulates a Bernoulli trial with p=0.7. ```python def trial(): number = [1,2,3,4,5,6,7,8,9,10] a = random.choice(number) if a<= 7: return 1 else: return 0 ``` -------------------------------- ### Splitting Strings by Delimiter in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/01 Data Types and Data Structures/01 Data Types and Data Structures.ipynb This snippet demonstrates using the `.split()` method to break a string into a list of substrings based on a specified delimiter (a space and a colon in this case). It shows how to extract date, time, and hour components from a timestamp string. ```python Time = '2016-04-01 09:43:00' splited_list = Time.split(' ') date = splited_list[0] time = splited_list[1] print(date, time) hour = time.split(':')[0] print(hour) ``` -------------------------------- ### Performing Linear Regression with Statsmodels in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/09 Simple Linear Regression/09 Simple Linear Regression.ipynb Imports the statsmodels library for statistical modeling and performs a linear regression (OLS) to model the relationship between AMZN and SPY daily log returns using a formula string. It then prints the comprehensive summary table generated by the fitted model. ```python import statsmodels.formula.api as sm model = sm.ols(formula = 'amzn~spy',data = df).fit() print(model.summary()) ``` -------------------------------- ### Fetching SPY Options Data using pandas-datareader Source: https://github.com/quantconnect/tutorials/blob/master/06 Introduction to Options[]/08 Local Volatility and Stochastic Volatility/08 Local Volatility and Stochastic Volatility.ipynb Instantiates an Options object from pandas_datareader to fetch option chain data for the SPY ticker from Yahoo Finance. This object will be used to access expiry dates, call/put data, strikes, and premiums. ```python opt = Options('spy', 'yahoo') ``` -------------------------------- ### Running Monte Carlo for All Strikes in Option Chain Source: https://github.com/quantconnect/tutorials/blob/master/06 Introduction to Options[]/08 Local Volatility and Stochastic Volatility/08 Local Volatility and Stochastic Volatility.ipynb Iterates through all extracted strike prices and uses the 'mc_heston' function with calibrated parameters to calculate a Monte Carlo price for each corresponding call option. The results are stored in the 'heston' list. ```python heston = [] for i in range(len(strikes)): heston.append(mc_heston('c',spot,strikes[i],t/365.0,initial_var,long_term_var,rate_reversion,vol_of_vol,corr,0.01,100,100)) ``` -------------------------------- ### Printing Calibrated Heston Model Parameters Source: https://github.com/quantconnect/tutorials/blob/master/06 Introduction to Options[]/08 Local Volatility and Stochastic Volatility/08 Local Volatility and Stochastic Volatility.ipynb Retrieves the calibrated parameters from the Heston model after the optimization process and prints them to the console using Python 2 syntax. This shows the result of the calibration. ```python long_term_var, rate_reversion, vol_of_vol, corr, initial_var = model.params() print "long_term_var = %f, rate_reversion = %f, vol_of_vol = %f, corr = %f, initial_var = %f" % (long_term_var, rate_reversion, vol_of_vol, corr, initial_var) ``` -------------------------------- ### Stacking Vectors into Matrix Columns - Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/11 Linear Algebra/11 Linear Algebra.ipynb Uses the `np.column_stack` function to combine the 1D arrays 'a', 'b', and 'c' into the columns of a new 2D array (matrix) named 'matrix'. It then prints the resulting matrix and confirms its type. ```python matrix = np.column_stack((a,b,c)) print(matrix) print(type(matrix)) ``` -------------------------------- ### Visualizing Binomial Probability Distribution with Matplotlib in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/07 Random Variables and Distributions/07 Random Variable and Distributions.ipynb This code generates a bar plot using Matplotlib to visualize the estimated binomial probabilities calculated in a previous step. It plots the probabilities against the number of successes (from 1 to 10), adds a grid, and displays the plot. ```python plt.figure(figsize = (20,10)) plt.bar(range(1,11),prob) plt.grid() plt.show() ``` -------------------------------- ### Solving Linear System Ax=B via Inverse - Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/11 Linear Algebra/11 Linear Algebra.ipynb Defines a new 3x3 matrix 'A' and a 3x1 column vector 'B' representing a linear system Ax=B. It calculates the inverse of 'A' and finds the solution vector 'x' by computing the matrix product of the inverse of A and B. ```python A = np.array([[2,1,-1],[-3,-1,2],[-2,1,2]]) B = np.array([[8],[-11],[-3]]) inv_A = np.linalg.inv(A) print(np.dot(inv_A,B)) ``` -------------------------------- ### Creating and Printing NumPy Array in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/04 NumPy and Basic Pandas/04 NumPy and Basic Pandas.ipynb Demonstrates how to create a one-dimensional NumPy array from a Python list. It then prints the resulting array and its data type to the console. ```python price_list = [143.73, 145.83, 143.68, 144.02, 143.5, 142.62] price_array = np.array(price_list) print(price_array, type(price_array)) ``` -------------------------------- ### Running Monte Carlo Heston Simulation for a Single Option Source: https://github.com/quantconnect/tutorials/blob/master/06 Introduction to Options[]/08 Local Volatility and Stochastic Volatility/08 Local Volatility and Stochastic Volatility.ipynb Executes the 'mc_heston' function to price a specific call option (at strike index 20) using the calibrated Heston parameters, spot price, and calculated time to maturity. It performs the simulation with 100 repetitions and 1000 time steps. ```python mc_heston('c',spot,strikes[20],t/365.0,initial_var,long_term_var,rate_reversion,vol_of_vol,corr,0.01,100,1000) ``` -------------------------------- ### Fetching Financial Factors and SPY Data from Quandl in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/14 Fama-French Multi-Factor Models/14 Fama-French Multi-Factor Models.ipynb This code fetches the Fama-French 5-Factor Daily dataset and the SPY ETF daily data from Quandl. It adjusts the Fama-French factors by dividing by 100 to convert percentages to decimals and renames the 'Mkt-RF' column to 'mkt' for easier reference in formulas. ```python fama_5 = quandl.get('KFRENCH/FACTORS5_D') fama_5 = fama_5/100 fama_5 = fama_5.rename(columns = {'Mkt-RF':'mkt'}) spy = quandl.get('LSE/SPY5') ``` -------------------------------- ### Visualizing Returns Scatter Plot with Matplotlib in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/09 Simple Linear Regression/09 Simple Linear Regression.ipynb Imports the matplotlib plotting library and creates a scatter plot to visualize the relationship between the daily log returns of SPY and AMZN. Axes are labeled appropriately to indicate which return series is plotted on each axis. ```python import matplotlib.pyplot as plt plt.figure(figsize = (15,10)) plt.scatter(df.spy,df.amzn) plt.xlabel('spx_return') plt.ylabel('amzn_return') ``` -------------------------------- ### Performing Monte Carlo Simulation of Random Portfolios in Python Source: https://github.com/quantconnect/tutorials/blob/master/05 Introduction to Financial Python[]/12 Modern Portfolio Theory/12 Modern Portfolio Theory.ipynb This snippet runs a Monte Carlo simulation to generate a large number of random portfolio weights using a Dirichlet distribution. For each random set of weights, it calculates the expected return and standard deviation of the resulting portfolio based on the previously calculated stock means and covariance matrix. ```python #Simulation# monte_rate, monte_std = [],[] for i in range(100000): w = np.random.dirichlet(np.ones(leng),size=1) monte_rate.append(np.dot(w,mean_list)) monte_std.append(np.sqrt(np.dot(np.dot(w,cov_matrix),w.reshape(8,1)))*np.sqrt(252)) ```