Python For Finance Cookbook - Code Repository

Overview

Python For Finance Cookbook - Code Repository

Python For Finance Cookbook
published: January 31st, 2020

Paperback: 432 pages
Publisher: Packt Publishing
Language: English

Links

Table of Contents

  1. Financial Data and Preprocessing
  2. Technical Analysis in Python
  3. Time Series Modeling
  4. Multi-Factor Models
  5. Modeling Volatility with GARCH Class Models
  6. Monte Carlo Simulations in Finance
  7. Asset Allocation in Python
  8. Identifying Credit Default with Machine Learning
  9. Advanced Machine Learning Models in Finance
  10. Deep Learning in Finance

Eryk Lewinson. Python For Finance Cookbook. Packt Publishing, 2020.

@book{Lewinson2019,  
address = {Birmingham, UK},  
author = {Lewinson, Eryk},  
edition = {1},  
isbn = {9781789618518},   
publisher = {Packt Publishing},  
title = {{Python For Finance Cookbook}},  
year = {2020}  
}
Comments
  • Chapter 6: Code line

    Chapter 6: Code line "S_0 = adj_close[train.index[-1].date()]"

    Hello,

    when I type the following code line, I get the below error message:

    S_0 = adj_close[train.index[-1].date()]

    However, when I remove the part ".date()" the code works fine. Did anyone experience the same behaviour?

    Thanks

    KeyError Traceback (most recent call last) in 25 T = len(test) 26 N = len(test) ---> 27 S_0 = adj_close[train.index[-1].date()] 28 N_SIM = 1000 29 mu = train.mean()

    ~\Miniconda3\lib\site-packages\pandas\core\series.py in getitem(self, key) 880 881 elif key_is_scalar: --> 882 return self._get_value(key) 883 884 if (

    ~\Miniconda3\lib\site-packages\pandas\core\series.py in _get_value(self, label, takeable) 989 990 # Similar to Index.get_value, but we do not fall back to positional --> 991 loc = self.index.get_loc(label) 992 return self.index._get_values_for_loc(self, loc, label) 993

    ~\Miniconda3\lib\site-packages\pandas\core\indexes\datetimes.py in get_loc(self, key, method, tolerance) 620 else: 621 # unrecognized type --> 622 raise KeyError(key) 623 624 try:

    KeyError: datetime.date(2019, 6, 28)

    opened by randommarko 7
  • issue generating images/ch6_im2.png (Geometric Brownian Motion)

    issue generating images/ch6_im2.png (Geometric Brownian Motion)

    cc @erykml

    I was following along with the code in chapt. 6, but the plot of the simulations seemed off; maybe I had a typo I couldn't spot.

    I downloaded the jupyter notebook for chpt 6 and reran it and got similar results.

    Screenshot from 2020-07-24 21-10-21

    were my results. This pretty much matches what I get from the python notebook.

    (Also, I recommended this book to our local library, and I see on their website it's on order (though I already have my hardcopy) :sunglasses: )

    opened by nickdesaulniers 6
  • Code for Chapter 2 SMA-Signal results in error [ERRNO] No such file or Directory; 'APPL'

    Code for Chapter 2 SMA-Signal results in error [ERRNO] No such file or Directory; 'APPL'

    I am on a Windows unit. When I run the code from page 52 in Jupyter Notebook I get the error "No such file or directory". I am using the following Packages: Python==3.7.6 Anaconda Navigator==1.9.12 Backtrader==1.9.74.123 Cufflinks==0.17.3 Notebook==6.0.3 Numpy==1.18.1 Pandas==1.0.1 YFinance==0.1.54 BT Signal.pdf

    help wanted 
    opened by CarterFitz 3
  • Chapter 01 Not defined error

    Chapter 01 Not defined error

    df = df_all_dates.join(df[['adj_close']], how='left')
    .fillna(method='ffill')
    .asfreq('M')

    This is the line with the error. It says df is not defined.

    opened by bhatz829-zz 2
  • Fix : adj_close has to be divided by the previous day

    Fix : adj_close has to be divided by the previous day

    The line of code , df['log_rtn'] = np.log(df.adj_close/df.adj_close.shift(1)) , means adj_close divided by the next day. But in the book, Log return is log(Pt/ P(t-1)). So It has to be df['log_rtn'] =np.log(df.adj_close/df.adj_close.shift(-1))

    opened by DavidKimDY 2
  • Chapter 7.2 While plotting the

    Chapter 7.2 While plotting the "Efficient Frontier" facing IndexError: list index out of range

    `marks = ['o', "s", "x", "+"]

    fig, ax = plt.subplots()

    pf_results.plot(kind='scatter', x='volatility', y='returns', c='sharpe_ratio', cmap='RdYlGn', edgecolors='black', ax=ax) ax.set(xlabel='Volatility', ylabel='Expected Returns', title='Efficient Frontier') ax.plot(pf_vol_ef, pf_returns_ef, 'b--')

    for asset_index in range(n_assets): ax.scatter(x=np.sqrt(cov_mat.iloc[asset_index, asset_index]), y=avg_returns[asset_index], marker=marks[asset_index], s=150, color='black', label=assets[asset_index]) ax.legend() plt.tight_layout() plt.show();`

    Refer the attached image image

    opened by rajesh1994 2
  • performance_evaluation_report(learn) wont' run

    performance_evaluation_report(learn) wont' run

    Trying to run this code from chapter 10 and receiving and error.

    performance_evaluation_report(learn)

    AttributeError                            Traceback (most recent call last)
    <ipython-input-28-8b0585476687> in <module>()
    ----> 1 performance_evaluation_report(learn)
    
    <ipython-input-6-a6983da9cfee> in performance_evaluation_report(model, show_plot, labels, show_pr_curve)
         35     y_pred_prob = preds_valid.numpy()[:, 1]
         36 
    ---> 37     cm = metrics.confusion_matrix(y_test, y_pred)
         38     tn, fp, fn, tp = cm.ravel()
         39 
    
    AttributeError: module 'fastai.metrics' has no attribute 'confusion_matrix'
    
    opened by JeremyWhittaker 2
  • cufflinks go offline

    cufflinks go offline

    Hi, I really like your book! Great concise examples with modern libraries.

    Working through chpt 2 building the dashboard, it seems that I need to add cf.go_offline() otherwise the plot is never generated, and the call to qf.iplot() hangs in some retry loop that's trying to send an HTTP request to plotly. I suspect this API changed since the book was published?

    opened by nickdesaulniers 2
  • Chapter 2 Plot error

    Chapter 2 Plot error

    Hi, in chapter two, I follow your code but when I try to use "Plot"

    # plot results
    cerebro.plot(iplot=True, volume=False)
    

    I got following error

    ReferenceError: IPython is not defined
        at eval (eval at runCodeHere (vscode-resource://file///c%3A/Users/mojTaba/.vscode/extensions/ms-python.python-2020.3.69010/out/datascience-ui/notebook/vendors~nteract_transforms.bundle.js:2:11583), <anonymous>:764:1)
        at runCodeHere (vscode-resource://file///c%3A/Users/mojTaba/.vscode/extensions/ms-python.python-2020.3.69010/out/datascience-ui/notebook/vendors~nteract_transforms.bundle.js:2:11583)
        at t.value (vscode-resource://file///c%3A/Users/mojTaba/.vscode/extensions/ms-python.python-2020.3.69010/out/datascience-ui/notebook/vendors~nteract_transforms.bundle.js:2:12015)
        at Di (vscode-resource://file///c%3A/Users/mojTaba/.vscode/extensions/ms-python.python-2020.3.69010/out/datascience-ui/notebook/commons.initial.bundle.js:2:1299316)
        at Li (vscode-resource://file///c%3A/Users/mojTaba/.vscode/extensions/ms-python.python-2020.3.69010/out/datascience-ui/notebook/commons.initial.bundle.js:2:1302238)
        at vscode-resource://file///c%3A/Users/mojTaba/.vscode/extensions/ms-python.python-2020.3.69010/out/datascience-ui/notebook/commons.initial.bundle.js:2:1315318
        at Object.t.unstable_runWithPriority (vscode-resource://file///c%3A/Users/mojTaba/.vscode/extensions/ms-python.python-2020.3.69010/out/datascience-ui/notebook/commons.initial.bundle.js:2:6091)
        at Sl (vscode-resource://file///c%3A/Users/mojTaba/.vscode/extensions/ms-python.python-2020.3.69010/out/datascience-ui/notebook/commons.initial.bundle.js:2:1315252)
        at Cl (vscode-resource://file///c%3A/Users/mojTaba/.vscode/extensions/ms-python.python-2020.3.69010/out/datascience-ui/notebook/commons.initial.bundle.js:2:1315028)
        at wl (vscode-resource://file///c%3A/Users/mojTaba/.vscode/extensions/ms-python.python-2020.3.69010/out/datascience-ui/notebook/commons.initial.bundle.js:2:1314373)
    

    All other parts work as expected.

    opened by shayegh 2
  • 'unzip' and 'rm' are not recognized commands

    'unzip' and 'rm' are not recognized commands

    In using the code for chapter 4 cell #15 the shell commands '!unzip' and '!rm' give an error "not recognized as an internal or external command". Do you know of a solution. I am not that familiar with shell commands.

    download the zip file from Prof. French's website

    !wget http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/F-F_Research_Data_Factors_CSV.zip

    unpack the zip

    !unzip -a F-F_Research_Data_Factors_CSV.zip

    remove the zip

    !rm F-F_Research_Data_Factors_CSV.zip --2020-05-04 17:21:39-- http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/F-F_Research_Data_Factors_CSV.zip Resolving mba.tuck.dartmouth.edu... 129.170.171.144 Connecting to mba.tuck.dartmouth.edu|129.170.171.144|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 12389 (12K) [application/x-zip-compressed] Saving to: `F-F_Research_Data_Factors_CSV.zip.7'

     0K .......... ..                                         100% 34.4M=0s
    

    2020-05-04 17:21:39 (34.4 MB/s) - `F-F_Research_Data_Factors_CSV.zip.7' saved [12389/12389]

    'unzip' is not recognized as an internal or external command, operable program or batch file. 'rm' is not recognized as an internal or external command, operable program or batch file.

    opened by CarterFitz 1
  • File not found error

    File not found error

    Hello!

    Below is the code error that I receive when running the last block of code for the 'Backtesting a strategy based on simple moving average' section of chapter 2 (Signal section) of Python for Finance Cookbook.

    The input is:

    print(f'Starting Portfolio Value: {cerebro.broker.getvalue():.2f}') cerebro.run() print(f'Final Portfolio Value: {cerebro.broker.getvalue():.2f}')

    The output is:

    Starting Portfolio Value: 1000.00

    FileNotFoundError Traceback (most recent call last) /var/folders/ys/kp32whkx5bn9nwysmmsrhb5w0000gn/T/ipykernel_57259/3974036464.py in 1 print(f'Starting Portfolio Value: {cerebro.broker.getvalue():.2f}') ----> 2 cerebro.run() 3 print(f'Final Portfolio Value: {cerebro.broker.getvalue():.2f}')

    /opt/anaconda3/lib/python3.9/site-packages/backtrader/cerebro.py in run(self, **kwargs) 1125 # let's skip process "spawning" 1126 for iterstrat in iterstrats: -> 1127 runstrat = self.runstrategies(iterstrat) 1128 self.runstrats.append(runstrat) 1129 if self._dooptimize:

    /opt/anaconda3/lib/python3.9/site-packages/backtrader/cerebro.py in runstrategies(self, iterstrat, predata) 1208 if self._exactbars < 1: # datas can be full length 1209 data.extend(size=self.params.lookahead) -> 1210 data._start() 1211 if self._dopreload: 1212 data.preload()

    /opt/anaconda3/lib/python3.9/site-packages/backtrader/feed.py in _start(self) 201 202 def _start(self): --> 203 self.start() 204 205 if not self._started:

    /opt/anaconda3/lib/python3.9/site-packages/backtrader/feeds/yahoo.py in start(self) 353 354 # Prepared a "path" file - CSV Parser can take over --> 355 super(YahooFinanceData, self).start() 356 357

    /opt/anaconda3/lib/python3.9/site-packages/backtrader/feeds/yahoo.py in start(self) 92 93 def start(self): ---> 94 super(YahooFinanceCSVData, self).start() 95 96 if not self.params.reverse:

    /opt/anaconda3/lib/python3.9/site-packages/backtrader/feed.py in start(self) 672 else: 673 # Let an exception propagate to let the caller know --> 674 self.f = io.open(self.p.dataname, 'r') 675 676 if self.p.headers:

    FileNotFoundError: [Errno 2] No such file or directory: 'BA'

    I used a different stock to run the code. It keeps referring to the line 'cerebro.run()' and I've looked to see if there's another way to run the code but I've come up short. Advice?

    System Mac OS Monterey Python 3.9.7

    opened by deemcgee 0
Owner
Packt
Providing books, eBooks, video tutorials, and articles for IT developers, administrators, and users.
Packt
Repository for learning Python (Python Tutorial)

Repository for learning Python (Python Tutorial) Languages and Tools ?? Overview ?? Repository for learning Python (Python Tutorial) Languages and Too

Swiftman 2 Aug 22, 2022
SCTYMN is a GitHub repository that includes some simple scripts(currently only python scripts) that can be useful.

Simple Codes That You Might Need SCTYMN is a GitHub repository that includes some simple scripts(currently only python scripts) that can be useful. In

CodeWriter21 2 Jan 21, 2022
Main repository for the Sphinx documentation builder

Sphinx Sphinx is a tool that makes it easy to create intelligent and beautiful documentation for Python projects (or other documents consisting of mul

null 5.1k Jan 2, 2023
Main repository for the Sphinx documentation builder

Sphinx Sphinx is a tool that makes it easy to create intelligent and beautiful documentation for Python projects (or other documents consisting of mul

null 5.1k Jan 4, 2023
Generate a single PDF file from MkDocs repository.

PDF Generate Plugin for MkDocs This plugin will generate a single PDF file from your MkDocs repository. This plugin is inspired by MkDocs PDF Export P

null 198 Jan 3, 2023
Canonical source repository for PyYAML

PyYAML - The next generation YAML parser and emitter for Python. To install, type 'python setup.py install'. By default, the setup.py script checks

The YAML Project 2k Jan 1, 2023
This repository outlines deploying a local Kubeflow v1.3 instance on microk8s and deploying a simple MNIST classifier using KFServing.

Zero to Inference with Kubeflow Getting Started This repository houses all of the tools, utilities, and example pipeline implementations for exploring

Ed Henry 3 May 18, 2022
Repository for tutorials, examples and starter scripts for using the MTU HPC cluster

MTU-HPC-Starter Repository for tutorials, examples and starter scripts for using the MTU HPC cluster Connecting to the MTU HPC cluster Within the coll

null 1 Jan 31, 2022
Run `black` on python code blocks in documentation files

blacken-docs Run black on python code blocks in documentation files. install pip install blacken-docs usage blacken-docs provides a single executable

Anthony Sottile 460 Dec 23, 2022
Source Code for 'Practical Python Projects' (video) by Sunil Gupta

Apress Source Code This repository accompanies %Practical Python Projects by Sunil Gupta (Apress, 2021). Download the files as a zip using the green b

Apress 2 Jun 1, 2022
Tutorial for STARKs with supporting code in python

stark-anatomy STARK tutorial with supporting code in python Outline: introduction overview of STARKs basic tools -- algebra and polynomials FRI low de

null 121 Jan 3, 2023
Python code for working with NFL play by play data.

nfl_data_py nfl_data_py is a Python library for interacting with NFL data sourced from nflfastR, nfldata, dynastyprocess, and Draft Scout. Includes im

null 82 Jan 5, 2023
A collection and example code of every topic you need to know about in the basics of Python.

The Python Beginners Guide: Master The Python Basics Tonight This guide is a collection of every topic you need to know about in the basics of Python.

Ahmed Baari 1 Dec 19, 2021
Quick tutorial on orchest.io that shows how to build multiple deep learning models on your data with a single line of code using python

Deep AutoViML Pipeline for orchest.io Quickstart Build Deep Learning models with a single line of code: deep_autoviml Deep AutoViML helps you build te

Ram Seshadri 6 Oct 2, 2022
Some of the best ways and practices of doing code in Python!

Pythonicness ❤ This repository contains some of the best ways and practices of doing code in Python! Features Properly formatted codes (PEP 8) for bet

Samyak Jain 2 Jan 15, 2022
Example Python code for running the mango-explorer marketmaker

?? Mango Explorer ?? Introduction This guide will show you how to load and run a customisable marketmaker that runs on Mango Markets using the mango-e

Blockworks Foundation 2 Apr 11, 2022
Near Zero-Overhead Python Code Coverage

Slipcover: Near Zero-Overhead Python Code Coverage by Juan Altmayer Pizzorno and Emery Berger at UMass Amherst's PLASMA lab. About Slipcover Slipcover

PLASMA @ UMass 325 Dec 28, 2022
The source code that powers readthedocs.org

Welcome to Read the Docs Purpose Read the Docs hosts documentation for the open source community. It supports Sphinx docs written with reStructuredTex

Read the Docs 7.4k Dec 25, 2022
Documentation of the QR code found on new Austrian ID cards.

Austrian ID Card QR Code This document aims to be a complete documentation of the format used in the QR area on the back of new Austrian ID cards (Per

Gabriel Huber 9 Dec 12, 2022