Use following code to obtain data: from pandas_datareader import…
Question Answered step-by-step Use following code to obtain data: from pandas_datareader import… Use following code to obtain data:from pandas_datareader import data as webimport osimport pandas as pddef get_stock(ticker, start_date, end_date, s_window, l_window):try:df = web.get_data_yahoo(ticker, start=start_date, end=end_date)df[‘Return’] = df[‘Adj Close’].pct_change()df[‘Return’].fillna(0, inplace = True)df[‘Date’] = df.indexdf[‘Date’] = pd.to_datetime(df[‘Date’])df[‘Month’] = df[‘Date’].dt.monthdf[‘Year’] = df[‘Date’].dt.year df[‘Day’] = df[‘Date’].dt.dayfor col in [‘Open’, ‘High’, ‘Low’, ‘Close’, ‘Adj Close’]:df[col] = df[col].round(2)df[‘Weekday’] = df[‘Date’].dt.strftime(“%A”) df[‘Week_Number’] = df[‘Date’].dt.strftime(‘%U’)df[‘Year_Week’] = df[‘Date’].dt.strftime(‘%Y-%U’)df[‘Short_MA’] = df[‘Adj Close’].rolling(window=s_window, min_periods=1).mean()df[‘Long_MA’] = df[‘Adj Close’].rolling(window=l_window, min_periods=1).mean() col_list = [‘Date’, ‘Year’, ‘Month’, ‘Day’, ‘Weekday’, ‘Week_Number’, ‘Year_Week’, ‘Open’, ‘High’, ‘Low’, ‘Close’, ‘Volume’, ‘Adj Close’,’Return’, ‘Short_MA’, ‘Long_MA’]num_lines = len(df)df = df[col_list]print(‘read ‘, num_lines, ‘ lines of data for ticker: ‘ , ticker)return dfexcept Exception as error:print(error)return Nonetry_ticker=’SPY’input_dir = ##enter input directoryoutput_file = os.path.join(input_dir, ticker + ‘.csv’)df = get_stock(ticker, start_date=’2014-01-01′, end_date=’2019-12-31′, s_window=14, l_window=50)df.to_csv(output_file, index=False)print(‘wrote ‘ + str(len(df)) + ‘ lines to file: ‘ + output_file)except Exception as e:print(e)print(‘failed to get Yahoo stock data for ticker: ‘, ticker) ADD true table (run this code)df_spy = pd.read_csv(##input dir path)print(df_spy.head())df_spy[“True Label”] = df_spy.apply(lambda x:”+” if x[“Return”]>=0 else “-“,axis=1)print(df_spy.head()) QUESTIONS1. compute ensemble labels for year 4 and 5 for both your stock and S&P-500.2. for both S&P-500 and your ticker, what percentage of labels in year 4 and 5 do you compute correctly by using ensemble?3. Did you improve your accuracy on predicting “−” labels by using ensemble compared to W = 2, 3, 4?4. Did you improve your accuracy on predicting “+” labels by using ensemble compared to W = 2, 3, 4? Computer Science Engineering & Technology Python Programming CS 677 Share QuestionEmailCopy link Comments (0)


