packtpublishing / python-for-finance-cookbook Goto Github PK
View Code? Open in Web Editor NEWPython for Finance Cookbook, published by Packt
Python for Finance Cookbook, published by Packt
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)
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?
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.
!wget http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/F-F_Research_Data_Factors_CSV.zip
!unzip -a F-F_Research_Data_Factors_CSV.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.
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.
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
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:
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
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.
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) ๐ )
`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();`
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'
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.
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?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.