can someone help me with this error?
Is there an error in my pyalgo file?
What type of other address I have to put into tpqoa call?
Thanks
CODE
pyalgo.cfg
[oanda]
account_id = "101-012-21240417-001"
access_token = 'hidden'
account_type = practice
CODE
import oandapyV20
import pandas as pd
import tpqoa
api = tpqoa.tpqoa('../pyalgo.cfg')
api.get.instruments()[:15]
Output
KeyError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_5064/836215391.py in <module>
2 import pandas as pd
3 import tpqoa
----> 4 api = tpqoa.tpqoa('../pyalgo.cfg')
5 from oandapyV20 import API
6 import oandapyV20.endpoints.pricing as pricing
~\anaconda3\envs\PythonPC\lib\site-packages\tpqoa\tpqoa.py in __init__(self, conf_file)
111 self.config = configparser.ConfigParser()
112 self.config.read(conf_file)
--> 113 self.access_token = self.config['oanda']['access_token']
114 self.account_id = self.config['oanda']['account_id']
115 self.account_type = self.config['oanda']['account_type']
~\anaconda3\envs\PythonPC\lib\configparser.py in __getitem__(self, key)
958 def __getitem__(self, key):
959 if key != self.default_section and not self.has_section(key):
--> 960 raise KeyError(key)
961 return self._proxies[key]
962
KeyError: 'oanda'
you have indented the account_id, access_token and account_type.
unindent them then run it.
Related
Previously, this same code was running perfectly. However, I encountered this error recently "TypeError: string indices must be integers".
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pandas_datareader.data as web
import datetime
start=datetime.datetime(2015,6,1)
end=datetime.datetime(2022,6,30)
sbin=web.DataReader('SBIN.BO','yahoo',start,end)
tatamotors=web.DataReader('TATAMOTORS.BO','yahoo',start,end)
reliance=web.DataReader('RELIANCE.BO','yahoo',start,end)
I have tried this code by considering other stock aslo. But same result obtained. After running the above code, the error occured as follows:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [3], in <cell line: 1>()
----> 1 sbin=web.DataReader('SBIN.BO','yahoo',start,end)
2 tatamotors=web.DataReader('TATAMOTORS.BO','yahoo',start,end)
3 reliance=web.DataReader('RELIANCE.BO','yahoo',start,end)
File C:\ProgramData\Anaconda3\lib\site-packages\pandas\util\_decorators.py:207, in deprecate_kwarg.<locals>._deprecate_kwarg.<locals>.wrapper(*args, **kwargs)
205 else:
206 kwargs[new_arg_name] = new_arg_value
--> 207 return func(*args, **kwargs)
File C:\ProgramData\Anaconda3\lib\site-packages\pandas_datareader\data.py:370, in DataReader(name, data_source, start, end, retry_count, pause, session, api_key)
367 raise NotImplementedError(msg)
369 if data_source == "yahoo":
--> 370 return YahooDailyReader(
371 symbols=name,
372 start=start,
373 end=end,
374 adjust_price=False,
375 chunksize=25,
376 retry_count=retry_count,
377 pause=pause,
378 session=session,
379 ).read()
381 elif data_source == "iex":
382 return IEXDailyReader(
383 symbols=name,
384 start=start,
(...)
390 session=session,
391 ).read()
File C:\ProgramData\Anaconda3\lib\site-packages\pandas_datareader\base.py:253, in _DailyBaseReader.read(self)
251 # If a single symbol, (e.g., 'GOOG')
252 if isinstance(self.symbols, (string_types, int)):
--> 253 df = self._read_one_data(self.url, params=self._get_params(self.symbols))
254 # Or multiple symbols, (e.g., ['GOOG', 'AAPL', 'MSFT'])
255 elif isinstance(self.symbols, DataFrame):
File C:\ProgramData\Anaconda3\lib\site-packages\pandas_datareader\yahoo\daily.py:153, in YahooDailyReader._read_one_data(self, url, params)
151 try:
152 j = json.loads(re.search(ptrn, resp.text, re.DOTALL).group(1))
--> 153 data = j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]
154 except KeyError:
155 msg = "No data fetched for symbol {} using {}"
TypeError: string indices must be integers.
Please help me in solving this issue.
There is a long-standing gh-issue that discusses your problem. As the corresponding PR hasn't been merged as of today, I would recommend to use the yfinance override instead:
import datetime
import pandas_datareader.data as web
import yfinance as yf
yf.pdr_override()
start=datetime.datetime(2015, 6, 1)
end=datetime.datetime(2022, 6, 30)
sbin = web.DataReader('SBIN.BO', start, end)
tatamotors = web.DataReader('TATAMOTORS.BO', start, end)
reliance = web.DataReader('RELIANCE.BO', start, end)
Output for SBIN:
Open High Low Close Adj Close Volume
Date
2015-06-01 00:00:00+05:30 279.000000 281.950012 277.600006 278.149994 265.453278 1331528
2015-06-02 00:00:00+05:30 278.500000 279.500000 265.500000 266.250000 254.096466 3382530
2015-06-03 00:00:00+05:30 267.149994 268.000000 255.100006 257.549988 245.793579 2706069
I am stuck in the following error in pymc3 and at a loss.
TypeError: float() argument must be a string or a number, not 'FreeRV'
The below is my code. I pick up this code from here. (Sorry, this is Japanese). However it does not work in my environment:
Google Colab, Python: 3.7.13, pymc3: 3.11.4
import numpy as np
import matplotlib
import matplotlib.pylab as plt
%matplotlib inline
from tqdm import tqdm
import pymc3 as pm
# generate time-series data
np.random.seed(0)
y = np.cumsum(np.random.normal(size=100))
# Infer parameters in time-series data
N = len(y)
T = 1000
with pm.Model() as model:
muZero = pm.Normal(name='muZero', mu=0.0, tau=1.0)
sigmaW = pm.InverseGamma(name='sigmaW', alpha=1.0, beta=1.0)
mu = [0]*N
mu[0] = pm.Normal(name='mu0', mu=muZero, tau=1/sigmaW)
for n in range(1, N):
mu[n] = pm.Normal(name='mu'+str(n), mu=mu[n-1], tau=1/sigmaW)
sigmaV = pm.InverseGamma(name='sigmaV', alpha=1.0, beta=1.0)
y_pre = pm.Normal('y_pre', mu=mu, tau=1/sigmaV, observed=y) # I got error here
start = pm.find_MAP()
step = pm.NUTS()
trace = pm.sample(T, step, start=start)
Here is the full discription of my error.
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/pymc3/theanof.py in floatX(X)
82 try:
---> 83 return X.astype(theano.config.floatX)
84 except AttributeError:
AttributeError: 'list' object has no attribute 'astype'
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
TypeError: float() argument must be a string or a number, not 'FreeRV'
The above exception was the direct cause of the following exception:
ValueError Traceback (most recent call last)
4 frames
<ipython-input-30-c3709f545993> in <module>()
26
27 sigmaV = pm.InverseGamma(name='sigmaV', alpha=1.0, beta=1.0)
---> 28 y_pre = pm.Normal('y_pre', mu=mu, tau=1/sigmaV, observed=y) # I got error here
29 start = pm.find_MAP()
30 step = pm.NUTS()
/usr/local/lib/python3.7/dist-packages/pymc3/distributions/distribution.py in __new__(cls, name, *args, **kwargs)
119 dist = cls.dist(*args, **kwargs, shape=shape)
120 else:
--> 121 dist = cls.dist(*args, **kwargs)
122 return model.Var(name, dist, data, total_size, dims=dims)
123
/usr/local/lib/python3.7/dist-packages/pymc3/distributions/distribution.py in dist(cls, *args, **kwargs)
128 def dist(cls, *args, **kwargs):
129 dist = object.__new__(cls)
--> 130 dist.__init__(*args, **kwargs)
131 return dist
132
/usr/local/lib/python3.7/dist-packages/pymc3/distributions/continuous.py in __init__(self, mu, sigma, tau, sd, **kwargs)
485 self.tau = tt.as_tensor_variable(tau)
486
--> 487 self.mean = self.median = self.mode = self.mu = mu = tt.as_tensor_variable(floatX(mu))
488 self.variance = 1.0 / self.tau
489
/usr/local/lib/python3.7/dist-packages/pymc3/theanof.py in floatX(X)
84 except AttributeError:
85 # Scalar passed
---> 86 return np.asarray(X, dtype=theano.config.floatX)
87
88
ValueError: setting an array element with a sequence.
I tried using tweepy's pagination based on the code provided in it's documentation:
```
import tweepy
auth = tweepy.AppAuthHandler("Consumer Key here", "Consumer Secret here")
api = tweepy.API(auth)
for status in tweepy.Cursor(api.search_tweets, "Tweepy",
count=100).items(250):
print(status.id)
```
However, I get the following error:
```
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_16136/3940301818.py in <module>
----> 1 for status in tweepy.Cursor(api.search_tweets, "Tweepy",
2 count=100).items(250):
3 print(status.id)
C:\ProgramData\Anaconda3\lib\site-packages\tweepy\cursor.py in __next__(self)
84
85 def __next__(self):
---> 86 return self.next()
87
88 def next(self):
C:\ProgramData\Anaconda3\lib\site-packages\tweepy\cursor.py in next(self)
290 self.page_index += 1
291 self.num_tweets += 1
--> 292 return self.current_page[self.page_index]
293
294 def prev(self):
KeyError: 0
```
Can someone explain and rectify the error please?
With the current version of Tweepy 4.8.0, the AuthHandler syntax has changed.
Update Tweepy:
pip install Tweepy -U
and the following should work:
import tweepy
auth = tweepy.OAuth2AppHandler("Consumer Key here", "Consumer Secret here")
api = tweepy.API(auth)
for status in tweepy.Cursor(api.search_tweets, "Tweepy",
count=100).items(250):
print(status.id)
import os
import pandas as pd
from ast import literal_eval
from cdqa.utils.filters import filter_paragraphs
from cdqa.pipeline import QAPipeline
df = pd.read_csv('./data/House_copy.csv', converters={'paragraphs': literal_eval}).astype(str)
df = filter_paragraphs(df)
df.head()
cdqa_pipeline = QAPipeline(reader='./models/bert_qa.joblib')
cdqa_pipeline.fit_retriever(df=df)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-30-cf7aa8b65439> in <module>
1 cdqa_pipeline = QAPipeline(reader='./models/bert_qa.joblib')
----> 2 cdqa_pipeline.fit_retriever(df=df)
~/cdQA/cdqa/pipeline/cdqa_sklearn.py in fit_retriever(self, df)
109 )
110 else:
--> 111 self.metadata = self._expand_paragraphs(df)
112
113 self.retriever.fit(self.metadata)
~/cdQA/cdqa/pipeline/cdqa_sklearn.py in _expand_paragraphs(df)
230 {
231 col: np.repeat(df[col].values, df[lst_col].str.len())
--> 232 for col in df.columns.drop(lst_col)
233 }
234 ).assign(**{lst_col: np.concatenate(df[lst_col].values)})[df.columns]
~/cdQA/cdqa/pipeline/cdqa_sklearn.py in <dictcomp>(.0)
230 {
231 col: np.repeat(df[col].values, df[lst_col].str.len())
--> 232 for col in df.columns.drop(lst_col)
233 }
234 ).assign(**{lst_col: np.concatenate(df[lst_col].values)})[df.columns]
~/opt/anaconda3/envs/sklearn-dev/lib/python3.7/site-packages/pandas/core/generic.py in __getattr__(self, name)
5174 or name in self._accessors
5175 ):
-> 5176 return object.__getattribute__(self, name)
5177 else:
5178 if self._info_axis._can_hold_identifiers_and_holds_name(name):
~/opt/anaconda3/envs/sklearn-dev/lib/python3.7/site-packages/pandas/core/accessor.py in __get__(self, obj, cls)
173 # we're accessing the attribute of the class, i.e., Dataset.geo
174 return self._accessor
--> 175 accessor_obj = self._accessor(obj)
176 # Replace the property with the accessor object. Inspired by:
177 # http://www.pydanny.com/cached-property.html
~/opt/anaconda3/envs/sklearn-dev/lib/python3.7/site-packages/pandas/core/strings.py in __init__(self, data)
1915
1916 def __init__(self, data):
-> 1917 self._inferred_dtype = self._validate(data)
1918 self._is_categorical = is_categorical_dtype(data)
1919
~/opt/anaconda3/envs/sklearn-dev/lib/python3.7/site-packages/pandas/core/strings.py in _validate(data)
1962
1963 if inferred_dtype not in allowed_types:
-> 1964 raise AttributeError("Can only use .str accessor with string " "values!")
1965 return inferred_dtype
1966
AttributeError: Can only use .str accessor with string values!
I am creating a QA system and I am modifying the existing code in cdQA package. I created a similar csv file that has some text in it.
There is nothing showing in the table after df.head().
I keep getting the .str accessor error and I don't know if my dataset is the problem.
can anyone please assist?
Thank you!
import matplotlib.pyplot as plt
When I enter the code above, I get the following error
#( conda install matplotlib/ python 3.5.2/ anaconda 3.4.2 / window10)
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-19-eff513f636fd> in <module>()
----> 1 import matplotlib.pyplot as plt
C:\Users\kimjimin\Anaconda3\lib\site-packages\matplotlib\pyplot.py in <module>()
36 from matplotlib.cbook import deprecated, warn_deprecated
37 from matplotlib import docstring
---> 38 from matplotlib.backend_bases import FigureCanvasBase
39 from matplotlib.figure import Figure, figaspect
40 from matplotlib.gridspec import GridSpec
C:\Users\kimjimin\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in <module>()
51 import numpy as np
52
---> 53 from matplotlib import (
54 backend_tools as tools, cbook, colors, textpath, tight_bbox, transforms,
55 widgets, get_backend, is_interactive, rcParams)
C:\Users\kimjimin\Anaconda3\lib\site-packages\matplotlib\backend_tools.py in <module>()
389
390
--> 391 class ToolQuitAll(ToolBase):
392 """Tool to call the figure manager destroy method"""
393
C:\Users\kimjimin\Anaconda3\lib\site-packages\matplotlib\backend_tools.py in ToolQuitAll()
393
394 description = 'Quit all figures'
--> 395 default_keymap = rcParams['keymap.quit_all']
396
397 def trigger(self, sender, event, data=None):
C:\Users\kimjimin\Anaconda3\lib\site-packages\matplotlib\__init__.py in __getitem__(self, key)
904 val = alt_val(val)
905 elif key in _deprecated_set and val is not None:
--> 906 if key.startswith('backend'):
907 warnings.warn(self.msg_backend_obsolete.format(key),
908 mplDeprecation)
KeyError: 'keymap.quit_all'