Git Product home page Git Product logo

python-for-finance-cookbook's Introduction

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}  
}### Download a free PDF

If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.

https://packt.link/free-ebook/9781789618518

python-for-finance-cookbook's People

Contributors

ayaanhoda avatar erykml avatar packt-itservice avatar packtutkarshr avatar utkarsha-packt 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

python-for-finance-cookbook's Issues

'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.

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.

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

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) ๐Ÿ˜Ž )

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)

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

qf.iplot() is Blank in Colab

I'm running

qf.iplot()

from file "chapter_2.ipynb" and it's just displaying a blank window in Google Colab. Is there a fix for this?

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.

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'

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?

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.