How to use inside_container method in testcontainers-python

Best Python code snippet using testcontainers-python_python

app.py

Source:app.py Github

copy

Full Screen

1import pandas as pd2import numpy as np3from datetime import date as dt4import yfinance as yf5import dash6from dash import dcc7from dash import html8from dash.dependencies import Output, Input, State9import plotly.graph_objects as go10import plotly.io as pio11from dateutil.relativedelta import relativedelta12import sklearn13from xgboost import XGBRegressor14pio.templates.default = "simple_white"15# ---------- interactive components16asset_text = dcc.Textarea(id='asset_text',17 placeholder='Select an asset:',18 value='AAPL')19pick_year = dcc.DatePickerSingle(id='date-picker',20 min_date_allowed=dt(1900, 8, 5),21 max_date_allowed=dt.today(),22 initial_visible_month=dt(2015, 1, 1),23 date=dt(2015, 1, 1)24 )25indicator_radio = dcc.RadioItems(id='radio-indicators',26 options=[{'label': 'Moving Average: 20 days', 'value': 'MA20'},27 {'label': 'Moving Average: 50 days', 'value': 'MA50'},28 {'label': 'Moving Average: 200 days', 'value': 'MA200'},29 {'label': 'Exponential Moving Average: 20 days', 'value': 'EMA20'},30 {'label': 'Exponential Moving Average: 50 days', 'value': 'EMA50'},31 {'label': 'Exponential Moving Average: 200 days', 'value': 'EMA200'},32 {'label': 'MACD', 'value': 'MACD'},33 {'label': 'Boolinger Bands', 'value': 'BB'},34 {'label': 'Stochastic Oscillator', 'value': 'SO'}],35 value='MA20',36 labelStyle={'display': 'block'}37 )38predicted_days_radio = dcc.RadioItems(id='predictions_days',39 options=[{'label': '1 day', 'value': 1},40 {'label': '2 days', 'value': 2},41 {'label': '5 days', 'value': 5},42 {'label': '10 days', 'value': 10},43 {'label': '30 days', 'value': 30}],44 labelStyle={'display': 'block'},45 value=546 )47# ---------- app48app = dash.Dash(__name__)49server = app.server50# ---------- app layout51app.layout = html.Div([52 html.Div([53 html.H1('Asset Analysis', style={'textAlign': 'center', 'background-color': '#f9f9f9'})54 ], className='pretty_container'),55 html.Div([56 html.Div([57 html.Div([58 html.H4('Choose an asset:', style={'textAlign': 'left', 'background-color': '#ffffff'}),59 asset_text,60 html.Br(),61 html.H4('Choose an initial date:', style={'textAlign': 'left', 'background-color': '#ffffff'}),62 pick_year,63 ], className='inside_container'),64 html.Div([65 html.Button('Submit', id='submit_button', className='Button'),66 ], className='inside_container'),67 html.Div([68 html.Br(),69 html.Br(),70 html.Img(src=app.get_asset_url('1stmenu.png'), style={'width': '100%',71 'position': 'bottom',72 'opacity': '80%'}),73 ])74 ], style={'width': '24%'}, className='pretty_container'),75 html.Div([76 html.Div([77 html.Div([78 html.H4(id='title_1st', style={'background-color': '#ffffff'}),79 html.H5(id='company_name', style={'background-color': '#ffffff'})80 ], style={'width': '20%'}, className='inside_container'),81 html.Div([82 html.H4(id='title_2nd', style={'background-color': '#ffffff'}),83 html.H5(id='sector_name', style={'background-color': '#ffffff'})84 ], style={'width': '20%'}, className='inside_container'),85 html.Div([86 html.H4(id='title_3rd', style={'background-color': '#ffffff'}),87 html.H5(id='beta_value', style={'background-color': '#ffffff'})88 ], style={'width': '20%'}, className='inside_container'),89 html.Div([90 html.H4(id='title_4th', style={'background-color': '#ffffff'}),91 html.H5(id='fcf_value', style={'background-color': '#ffffff'})92 ], style={'width': '20%'}, className='inside_container'),93 html.Div([94 html.H4(id='title_5th', style={'background-color': '#ffffff'}),95 html.H5(id='return_on_equity_value', style={'background-color': '#ffffff'})96 ], style={'width': '20%'}, className='inside_container'),97 ], style={'height': '20%', 'display': 'flex'}),98 html.Div([99 html.Div([100 dcc.Graph(id='history_line_plot')101 ], style={'width': '76%'}, className='inside_container'),102 html.Div([103 html.Div([104 html.Label('1-Year Change:', style={'background-color': '#ffffff'}),105 dcc.Graph(id='1year_change_value', style={'background-color': '#ffffff'})106 ], style={'width': '85%', 'height': '18%'}, className='inside_container'),107 html.Div([108 html.Label('6-Month Change:', style={'background-color': '#ffffff'}),109 dcc.Graph(id='6month_change_value', style={'background-color': '#ffffff'})110 ], style={'width': '85%', 'height': '18%'}, className='inside_container'),111 html.Div([112 html.Label('1-Month Change:', style={'background-color': '#ffffff'}),113 dcc.Graph(id='1month_change_value', style={'background-color': '#ffffff'})114 ], style={'width': '85%', 'height': '18%'}, className='inside_container'),115 html.Div([116 html.Label('Today Change:', style={'background-color': '#ffffff'}),117 dcc.Graph(id='today_change_value', style={'background-color': '#ffffff'})118 ], style={'width': '85%', 'height': '17%'}, className='inside_container')119 ], style={'width': '19%'})120 ], style={'height': '80%', 'display': 'flex'})121 ], style={'width': '75%'}, className='pretty_container'),122 ], style={'display': 'flex'}),123 html.Div([124 html.Div([125 html.Div([126 html.H4('Choose an Indicator:', style={'textAlign': 'left', 'background-color': '#ffffff'}),127 indicator_radio,128 ], className='inside_container'),129 html.Div([130 html.H5(id='indicator_explanation', style={'background-color': '#ffffff'})131 ], className='inside_container'),132 ], style={'width': '24%'}, className='pretty_container'),133 html.Div([134 dcc.Graph(id='indicator_line_graph', className='inside_container')135 ], style={'width': '75%'}, className='pretty_container'),136 ], style={'display': 'flex'}),137 html.Div([138 html.Div([139 html.Div([140 html.H4('Choose Prediction Days:', style={'textAlign': 'left', 'background-color': '#ffffff'}),141 predicted_days_radio142 ], className='inside_container'),143 html.Div([144 html.Img(src=app.get_asset_url('ToTheMoon.png'), style={'width': '100%',145 'position': 'bottom',146 'opacity': '80%'}),147 ]),148 ], style={'width': '27%'}, className='pretty_container'),149 html.Div([150 html.Div([151 dcc.Graph(id='predictions_line_graph', className='inside_container')152 ], style={'width': '80%'}),153 html.Div([154 html.Div([155 html.Label('Prediction:', style={'background-color': '#ffffff'}),156 html.H5(id='prediction_value', style={'background-color': '#ffffff'})157 ], style={'width': '150%', 'height': '35%'}, className='inside_container'),158 html.Div([159 html.Label('Change to last Close Price:', style={'background-color': '#ffffff'}),160 dcc.Graph(id='indicator_change', style={'background-color': '#ffffff'})161 ], style={'width': '150%', 'height': '45%'}, className='inside_container'),162 ], style={'width': '10%'})163 ], style={'width': '85%', 'display': 'flex'}, className='pretty_container'),164 ], style={'display': 'flex'}),165 html.Div([166 html.Div([167 html.H2(id='title', style={'background-color': '#ffffff'})168 ], className='inside_container'),169 html.Div([170 html.Div([171 html.H3(id='title1_news', style={'background-color': '#ffffff'}),172 html.Br(),173 html.A('LINK', id='link1_news', target="_blank")174 ], style={'width': '32%'}, className='inside_container'),175 html.Div([176 html.H3(id='title2_news', style={'background-color': '#ffffff'}),177 html.Br(),178 html.A('LINK', id='link2_news', target="_blank")179 ], style={'width': '32%'}, className='inside_container'),180 html.Div([181 html.H3(id='title3_news', style={'background-color': '#ffffff'}),182 html.Br(),183 html.A('LINK', id='link3_news', target="_blank")184 ], style={'width': '32%'}, className='inside_container'),185 ], style={'display': 'flex'}),186 ], className='pretty_container'),187 html.Div([188 html.H3('Authors: Afonso Ramos, Beatriz Gonçalves, Helena Morais, Ricardo Sequeira ',189 style={'background-color': '#f9f9f9'})190 ], className='pretty_container'),191])192# ------------ app callback193##################################194# 1st graph #################195#################################196@app.callback(197 [198 Output("history_line_plot", "figure"),199 ],200 [201 Input("submit_button", "n_clicks")202 ],203 [204 State("asset_text", "value"),205 State("date-picker", "date")206 ]207)208def update_history(n_clicks, asset, date):209 df = yf.download(asset, start=date, end=dt.today())210 fig = go.Figure()211 fig.add_trace(go.Scatter(212 x=df.index,213 y=df.Close,214 name='Close', # Style name/legend entry with html tags215 connectgaps=True # override default to connect the gaps216 ))217 fig.update_layout(218 title={219 'text': f'History Closing Price of {asset} since {date}'},220 xaxis_title="Date",221 yaxis_title="Close Price")222 return [fig]223##################################224# 1st indicator #################225#################################226@app.callback(227 [228 Output("1year_change_value", "figure"),229 Output("6month_change_value", "figure"),230 Output("1month_change_value", "figure"),231 Output("today_change_value", "figure")232 ],233 [234 Input("submit_button", "n_clicks")235 ],236 [237 State("asset_text", "value"),238 State("date-picker", "date")239 ]240)241def update_indicator1(n_clicks, asset, date):242 df = yf.download(asset, start=date, end=dt.today())243 # 1year244 value_1year_ago = float(df.loc[df.index[-365]].Close)245 # 6months246 value_6month_ago = float(df.loc[df.index[-180]].Close)247 # 1month248 value_1month_ago = float(df.loc[df.index[-30]].Close)249 # 1day250 value_1day_ago = float(df.loc[df.index[-2]].Close)251 # Today252 value_today = float(df.loc[df.index[-1]].Close)253 # Figure 1254 fig1 = go.Figure(go.Indicator(255 mode="delta",256 value=df.loc[df.index[-1]].Close,257 delta={'reference': df.loc[df.index[-365]].Close, 'relative': True, 'valueformat': '.2%'}))258 fig1.update_traces(delta_font={'size': 18})259 fig1.update_layout(height=30, width=120)260 if value_today >= value_1year_ago:261 fig1.update_traces(delta_increasing_color='green')262 if value_today < value_1year_ago:263 fig1.update_traces(delta_decreasing_color='red')264 # Figure 2265 fig2 = go.Figure(go.Indicator(266 mode="delta",267 value=df.loc[df.index[-1]].Close,268 delta={'reference': df.loc[df.index[-180]].Close, 'relative': True, 'valueformat': '.2%'}))269 fig2.update_traces(delta_font={'size': 18})270 fig2.update_layout(height=30, width=120)271 if value_today >= value_6month_ago:272 fig2.update_traces(delta_increasing_color='green')273 if value_today < value_6month_ago:274 fig2.update_traces(delta_decreasing_color='red')275 # Figure 3276 fig3 = go.Figure(go.Indicator(277 mode="delta",278 value=df.loc[df.index[-1]].Close,279 delta={'reference': df.loc[df.index[-30]].Close, 'relative': True, 'valueformat': '.2%'}))280 fig3.update_traces(delta_font={'size': 18})281 fig3.update_layout(height=30, width=120)282 if value_today >= value_1month_ago:283 fig3.update_traces(delta_increasing_color='green')284 if value_today < value_1month_ago:285 fig3.update_traces(delta_decreasing_color='red')286 # Figure 4287 fig4 = go.Figure(go.Indicator(288 mode="delta",289 value=df.loc[df.index[-1]].Close,290 delta={'reference': df.loc[df.index[-2]].Close, 'relative': True, 'valueformat': '.2%'}))291 fig4.update_traces(delta_font={'size': 18})292 fig4.update_layout(height=30, width=120)293 if value_today >= value_1day_ago:294 fig4.update_traces(delta_increasing_color='green')295 if value_today < value_1day_ago:296 fig4.update_traces(delta_decreasing_color='red')297 return fig1, fig2, fig3, fig4298##################################299# 2nd graph #################300#################################301@app.callback(302 [303 Output("indicator_line_graph", "figure"),304 Output("indicator_explanation", "children")305 ],306 [307 Input("submit_button", "n_clicks"),308 Input("radio-indicators", "value")309 ],310 [311 State("asset_text", "value"),312 State("date-picker", "date")313 ]314)315def update_indicators(n_clicks, indicator, asset, date):316 df = yf.download(asset, start=date, end=dt.today())317 if indicator == 'MA20':318 df['MA20'] = df.Close.rolling(20).mean()319 text = 'Moving average is a simple, technical analysis tool. Moving averages are usually calculated to identify\320 the trend direction of a stock or to determine its support and resistance levels. It is a trend-following or \321 lagging—indicator because it is based on past prices.In this case the Moving Average is calculated\322 using the last 20 days.'323 fig = go.Figure()324 fig.add_trace(go.Scatter(325 x=df.index,326 y=df.MA20,327 name='MA20', # Style name/legend entry with html tags328 connectgaps=True # override default to connect the gaps329 ))330 fig.add_trace(go.Scatter(331 x=df.index,332 y=df.Close,333 name='Close', # Style name/legend entry with html tags334 connectgaps=True # override default to connect the gaps335 ))336 fig.update_layout(337 title={338 'text': f'Moving Average of the last 20 days of {asset} since {date}'},339 xaxis_title="Date",340 yaxis_title="Value",341 legend_title="Indicator",342 )343 elif indicator == 'MA50':344 df['MA50'] = df.Close.rolling(50).mean()345 text = 'Moving average is a simple, technical analysis tool. Moving averages are usually calculated to identify\346 the trend direction of a stock or to determine its support and resistance levels. It is a trend-following or \347 lagging—indicator because it is based on past prices.In this case the Moving Average is calculated\348 using the last 50 days.'349 fig = go.Figure()350 fig.add_trace(go.Scatter(351 x=df.index,352 y=df.MA50,353 name='MA50', # Style name/legend entry with html tags354 connectgaps=True # override default to connect the gaps355 ))356 fig.add_trace(go.Scatter(357 x=df.index,358 y=df.Close,359 name='Close', # Style name/legend entry with html tags360 connectgaps=True # override default to connect the gaps361 ))362 fig.update_layout(363 title={364 'text': f'Moving Average of the last 50 days of {asset} since {date}'},365 xaxis_title="Date",366 yaxis_title="Value",367 legend_title="Indicator",368 )369 elif indicator == 'MA200':370 df['MA200'] = df.Close.rolling(200).mean()371 text = 'Moving average is a simple, technical analysis tool. Moving averages are usually calculated to identify\372 the trend direction of a stock or to determine its support and resistance levels. It is a trend-following or \373 lagging—indicator because it is based on past prices.In this case the Moving Average is calculated\374 using the last 200 days.'375 fig = go.Figure()376 fig.add_trace(go.Scatter(377 x=df.index,378 y=df.MA200,379 name='MA200', # Style name/legend entry with html tags380 connectgaps=True # override default to connect the gaps381 ))382 fig.add_trace(go.Scatter(383 x=df.index,384 y=df.Close,385 name='Close', # Style name/legend entry with html tags386 connectgaps=True # override default to connect the gaps387 ))388 fig.update_layout(389 title={390 'text': f'Moving Average of the last 200 days of {asset} since {date}'},391 xaxis_title="Date",392 yaxis_title="Value",393 legend_title="Indicator",394 )395 elif indicator == 'EMA20':396 df['EMA20'] = df.Close.ewm(span=20).mean()397 text = 'Exponential moving averages (EMA) is a weighted average that gives greater importance to the price of a\398 stock in more recent days, making it an indicator that is more responsive to new information. In this case the\399 Exponential Moving Average is calculated using the last 20 days.'400 fig = go.Figure()401 fig.add_trace(go.Scatter(402 x=df.index,403 y=df.EMA20,404 name='EMA20', # Style name/legend entry with html tags405 connectgaps=True # override default to connect the gaps406 ))407 fig.add_trace(go.Scatter(408 x=df.index,409 y=df.Close,410 name='Close', # Style name/legend entry with html tags411 connectgaps=True # override default to connect the gaps412 ))413 fig.update_layout(414 title={415 'text': f'Exponential Moving Average of the last 20 days of {asset} since {date}'},416 xaxis_title="Date",417 yaxis_title="Value",418 legend_title="Indicator",419 )420 elif indicator == 'EMA50':421 df['EMA50'] = df.Close.ewm(span=50).mean()422 text = 'Exponential moving averages (EMA) is a weighted average that gives greater importance to the price of a\423 stock in more recent days, making it an indicator that is more responsive to new information. In this case the\424 Exponential Moving Average is calculated using the last 50 days.'425 fig = go.Figure()426 fig.add_trace(go.Scatter(427 x=df.index,428 y=df.EMA50,429 name='EMA50', # Style name/legend entry with html tags430 connectgaps=True # override default to connect the gaps431 ))432 fig.add_trace(go.Scatter(433 x=df.index,434 y=df.Close,435 name='Close', # Style name/legend entry with html tags436 connectgaps=True # override default to connect the gaps437 ))438 fig.update_layout(439 title={440 'text': f'Exponential Moving Average of the last 50 days of {asset} since {date}'},441 xaxis_title="Date",442 yaxis_title="Value",443 legend_title="Indicator",444 )445 elif indicator == 'EMA200':446 df['EMA200'] = df.Close.ewm(span=200).mean()447 text = 'Exponential moving averages (EMA) is a weighted average that gives greater importance to the price of a\448 stock in more recent days, making it an indicator that is more responsive to new information. In this case the\449 Exponential Moving Average is calculated using the last 200 days.'450 fig = go.Figure()451 fig.add_trace(go.Scatter(452 x=df.index,453 y=df.EMA200,454 name='EMA200', # Style name/legend entry with html tags455 connectgaps=True # override default to connect the gaps456 ))457 fig.add_trace(go.Scatter(458 x=df.index,459 y=df.Close,460 name='Close', # Style name/legend entry with html tags461 connectgaps=True # override default to connect the gaps462 ))463 fig.update_layout(464 title={465 'text': f'Exponential Moving Average of the last 200 days of {asset} since {date}'},466 xaxis_title="Date",467 yaxis_title="Value",468 legend_title="Indicator",469 )470 elif indicator == 'MACD':471 df['MACD'] = (df.Close.ewm(span=12).mean() - df.Close.ewm(span=26).mean())472 df['signal'] = df['MACD'].ewm(span=9).mean()473 text = 'Moving average convergence divergence (MACD) is a trend-following momentum indicator that shows the \474 relationship between two moving averages of a security’s price. The MACD is calculated by subtracting the \475 26-period exponential moving average (EMA) from the 12-period EMA.The result of that calculation is the \476 MACD line. A nine-day EMA of the MACD called the "signal line," is then plotted on top of the MACD line, \477 which can function as a trigger for buy and sell signals. Traders may buy the security when the MACD crosses \478 above its signal line and sell—or short—the security when the MACD crosses below the signal line. '479 fig = go.Figure()480 fig.add_trace(go.Scatter(481 x=df.index,482 y=df.MACD,483 name='MACD', # Style name/legend entry with html tags484 connectgaps=True # override default to connect the gaps485 ))486 fig.add_trace(go.Scatter(487 x=df.index,488 y=df.signal,489 name='signal', # Style name/legend entry with html tags490 connectgaps=True # override default to connect the gaps491 ))492 fig.add_trace(go.Scatter(493 x=df.index,494 y=df.Close,495 name='Close', # Style name/legend entry with html tags496 connectgaps=True # override default to connect the gaps497 ))498 fig.update_layout(499 title={500 'text': f'Moving Average Convergence/Divergence of {asset} since {date}'},501 xaxis_title="Date",502 yaxis_title="Value",503 legend_title="Indicator",504 )505 elif indicator == 'BB':506 df['stddev'] = df.Close.rolling(20).std()507 df['BB_Lower'] = df.Close.rolling(20).mean() - 2 * df['stddev']508 df['BB_Higher'] = df.Close.rolling(20).mean() + 2 * df['stddev']509 text = 'A Bollinger Band technical indicator has bands generally placed two standard deviations away from a \510 simple moving average. In general, a move toward the upper band suggests the asset is becoming overbought, \511 while a move close to the lower band suggests the asset is becoming oversold. Since standard deviation is used \512 as a statistical measure of volatility, this indicator adjusts itself to market conditions.'513 fig = go.Figure()514 fig.add_trace(go.Scatter(515 x=df.index,516 y=df.BB_Lower,517 name='BB_Lower', # Style name/legend entry with html tags518 connectgaps=True # override default to connect the gaps519 ))520 fig.add_trace(go.Scatter(521 x=df.index,522 y=df.BB_Higher,523 name='BB_Higher', # Style name/legend entry with html tags524 connectgaps=True # override default to connect the gaps525 ))526 fig.add_trace(go.Scatter(527 x=df.index,528 y=df.Close,529 name='Close', # Style name/legend entry with html tags530 connectgaps=True # override default to connect the gaps531 ))532 fig.update_layout(533 title={534 'text': f'Boolinger Bands of {asset} since {date}'},535 xaxis_title="Date",536 yaxis_title="Value",537 legend_title="Indicator",538 )539 elif indicator == 'SO':540 df['14-low'] = df.High.rolling(14).min()541 df['14-high'] = df.Low.rolling(14).max()542 df['%K'] = (df['Close'] - df['14-low']) * 100 / (df['14-high'] - df['14-low'])543 df['%D'] = df['%K'].rolling(3).mean()544 text = 'A stochastic oscillator is a momentum indicator comparing a particular closing price of a security to \545 a range of its prices over a certain period of time. The sensitivity of the oscillator to market movements is \546 reducible by adjusting that time period or by taking a moving average of the result. It is used to generate\547 overbought and oversold trading signals, utilizing a 0–100 bounded range of values. Transaction signals are \548 created when the %K crosses through a three-period moving average, which is called the %D.'549 fig = go.Figure()550 fig.add_trace(go.Scatter(551 x=df.index,552 y=df['%D'],553 name='%D', # Style name/legend entry with html tags554 connectgaps=True # override default to connect the gaps555 ))556 fig.add_trace(go.Scatter(557 x=df.index,558 y=df['%K'],559 name='%K', # Style name/legend entry with html tags560 connectgaps=True # override default to connect the gaps561 ))562 fig.add_trace(go.Scatter(563 x=df.index,564 y=df.Close,565 name='Close', # Style name/legend entry with html tags566 connectgaps=True # override default to connect the gaps567 ))568 fig.update_layout(569 title={570 'text': f'Stochastic Oscillator of {asset} since {date}'},571 xaxis_title="Date",572 yaxis_title="Value",573 legend_title="Indicator",574 )575 return fig, text576# -------informations577@app.callback(578 [579 Output("title_1st", "children"),580 Output("company_name", "children"),581 Output("title_2nd", "children"),582 Output("sector_name", "children"),583 Output("title_3rd", "children"),584 Output("beta_value", "children"),585 Output("title_4th", "children"),586 Output("fcf_value", "children"),587 Output("title_5th", "children"),588 Output("return_on_equity_value", "children")589 ],590 [591 Input("submit_button", "n_clicks")592 ],593 [594 State("asset_text", "value"),595 State("date-picker", "date")596 ]597)598def update_information(n_clicks, asset, date):599 ticker = yf.Ticker(asset)600 info = ticker.stats()601 if info.get('price').get('quoteType') == 'CRYPTOCURRENCY':602 title1 = 'Name:'603 name = info.get('summaryProfile').get('name')604 title2 = 'Sector:'605 sector = 'Cryptocurrency'606 title3 = 'Market Cap:'607 marketcap = info.get('price').get('marketCap')608 title4 = 'Volume 24h:'609 volume = info.get('price').get('volume24Hr')610 title5 = 'Start Date:'611 start = info.get('summaryProfile').get('startDate')612 return title1,\613 name,\614 title2,\615 sector, \616 title3,\617 marketcap, \618 title4,\619 volume, \620 title5,\621 start622 elif info.get('price').get('quoteType') == 'EQUITY':623 title1 = 'Company Name:'624 name = info.get('quoteType').get('shortName')625 title2 = 'Sector:'626 sector = info.get('summaryProfile').get('sector')627 title3 = 'Beta:'628 beta = info.get('defaultKeyStatistics').get('beta')629 title4 = 'Free Cash Flow:'630 free_cash_flow = info.get('financialData').get('freeCashflow')631 title5 = 'Return on Equity:'632 return_on_equity = info.get('financialData').get('returnOnEquity')633 if free_cash_flow is None:634 free_cash_flow = 'Unavailable'635 else:636 free_cash_flow = round(free_cash_flow / 1000000, 2)637 if return_on_equity is None:638 return_on_equity = 'Unavailable'639 else:640 return_on_equity = round(return_on_equity * 100, 2)641 return title1,\642 name, \643 title2, \644 sector, \645 title3, \646 beta, \647 title4, \648 f'{free_cash_flow}M $', \649 title5, \650 f'{return_on_equity}%'651 elif info.get('price').get('quoteType') == 'INDEX':652 title1 = 'Name:'653 name = info.get('quoteType').get('shortName')654 title2 = 'Sector:'655 sector = info.get('quoteType').get('quoteType')656 title3 = 'No More Information'657 beta = ''658 title4 = 'No More Information'659 free_cash_flow = ''660 title5 = 'No More Information'661 return_on_equity = ''662 return title1,\663 name, \664 title2, \665 sector, \666 title3, \667 beta, \668 title4, \669 free_cash_flow, \670 title5, \671 return_on_equity672 elif info.get('price').get('quoteType') == 'ETF':673 title1 = 'Name:'674 name = info.get('quoteType').get('shortName')675 title2 = 'Sector:'676 sector = info.get('quoteType').get('quoteType')677 title3 = 'Fund Family:'678 beta = info.get('defaultKeyStatistics').get('fundFamily')679 title4 = 'Category:'680 free_cash_flow = info.get('defaultKeyStatistics').get('category')681 title5 = 'Total Number of Assets:'682 return_on_equity = info.get('defaultKeyStatistics').get('totalAssets')683 return title1,\684 name, \685 title2, \686 sector, \687 title3, \688 beta, \689 title4, \690 free_cash_flow, \691 title5, \692 return_on_equity693# ---------predictions694@app.callback(695 [696 Output("predictions_line_graph", "figure"),697 Output("prediction_value", "children"),698 Output("indicator_change", "figure"),699 ],700 [701 Input("submit_button", "n_clicks"),702 Input("predictions_days", "value")703 ],704 [705 State("asset_text", "value"),706 State("date-picker", "date")707 ]708)709def update_predictions(n_clicks, predict_days, asset, date):710 # transform a time series dataset into a supervised learning dataset711 def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):712 dfs = pd.DataFrame(data)713 cols = list()714 # input sequence (t-n, ... t-1)715 for i in range(n_in, 0, -1):716 cols.append(dfs.shift(i))717 # forecast sequence (t, t+1, ... t+n)718 for i in range(0, n_out):719 cols.append(dfs.shift(-i))720 # put it all together721 agg = pd.concat(cols, axis=1)722 # drop rows with NaN values723 if dropnan:724 agg.dropna(inplace=True)725 return agg.values726 df = yf.download(asset, start='2015-01-01', end=dt.today())727 # load the dataset728 series = df.Close729 values = series.values730 # transform the time series data into supervised learning731 train = series_to_supervised(values, n_in=15)732 # split into input and output columns733 trainX, trainy = train[:, :-1], train[:, -1]734 # fit model735 model = XGBRegressor(objective='reg:squarederror', n_estimators=1000)736 model.fit(trainX, trainy)737 predictions = []738 dates = []739 day = dt.today() - relativedelta(days=1)740 for i in range(predict_days):741 # construct an input for a new prediction742 row = values[-15:].flatten()743 # make a one-step prediction744 yhat = model.predict(np.asarray([row]))745 predictions.append(float(yhat))746 values = list(values)747 yhat = float(yhat)748 values.append(yhat)749 values = np.asarray(values)750 day = day + relativedelta(days=1)751 dates.append(str(day))752 new_df = pd.DataFrame(predictions, dates)753 new_df.columns = ['Predictions']754 rang = 7*predict_days755 fig = go.Figure()756 fig.add_trace(go.Scatter(757 x=df[-rang:].index,758 y=df[-rang:].Close,759 name='Close', # Style name/legend entry with html tags760 connectgaps=True # override default to connect the gaps761 ))762 fig.add_trace(go.Scatter(763 x=new_df.index,764 y=new_df.Predictions,765 name='Predictions',766 connectgaps=True # override default to connect the gaps767 ))768 fig.update_layout(769 title={770 'text': f'Predictions of asset {asset} for the next {predict_days} days.'},771 xaxis_title="Date",772 yaxis_title="Close Price"773 )774 # Figure775 if len(predictions) == 1:776 value_future = float(predictions[0])777 else:778 value_future = float(predictions[-1])779 value_last_day = float(df.Close[-1])780 fig1 = go.Figure(go.Indicator(781 mode="delta",782 value=value_future,783 delta={'reference': value_last_day, 'relative': True, 'valueformat': '.2%'}))784 fig1.update_traces(delta_font={'size': 18})785 fig1.update_layout(height=30, width=120)786 if value_future >= value_last_day:787 fig1.update_traces(delta_increasing_color='green')788 if value_future < value_last_day:789 fig1.update_traces(delta_decreasing_color='red')790 return fig, value_future, fig1791# ------------ news792@app.callback(793 [794 Output("title", "children"),795 Output("title1_news", "children"),796 Output("title2_news", "children"),797 Output("title3_news", "children"),798 Output("link1_news", "href"),799 Output("link2_news", "href"),800 Output("link3_news", "href"),801 ],802 [803 Input("submit_button", "n_clicks"),804 ],805 [806 State("asset_text", "value"),807 ]808)809def update_news(n_clicks,asset):810 news = yf.Ticker(asset).news811 if len(news) > 2:812 return f'Latest Financial News on {asset}',\813 news[0]['title'],\814 news[1]['title'],\815 news[2]['title'],\816 news[0]['link'],\817 news[1]['link'],\818 news[2]['link']819 elif len(news) == 2:820 return f'Latest Financial News on {asset}',\821 news[0]['title'],\822 news[1]['title'],\823 'Unavailable News',\824 news[0]['link'],\825 news[1]['link'],\826 ''827 elif len(news) == 1:828 return f'Latest Financial News on {asset}',\829 news[0]['title'],\830 'Unavailable News',\831 'Unavailable News',\832 news[0]['link'],\833 '',\834 ''835 else:836 return f'Latest Financial News on {asset}',\837 'Unavailable News',\838 'Unavailable News',\839 'Unavailable News',\840 '',\841 '',\842 ''843if __name__ == '__main__':...

Full Screen

Full Screen

kernelchecker.py

Source:kernelchecker.py Github

copy

Full Screen

1from distutils.version import LooseVersion2import platform3import subprocess4import os5__author__ = 'Igor Seletskiy'6__copyright__ = "Cloud Linux Zug GmbH 2016, KernelCare Project"7__credits__ = 'Igor Seletskiy'8__license__ = 'Apache License v2.0'9__maintainer__ = 'Igor Seletskiy'10__email__ = 'i@kernelcare.com'11__status__ = 'Production'12__version__ = '1.0'13# recognizable kernel package names14KERNEL_PREFIXES = ['pve-kernel', 'kernel-xen', 'vzkernel', 'kernel', 'linux']15DPKG_DISTRO = ['ubuntu', 'debian']16RPM_DISTRO = ['redhat', 'centos', 'cloudlinux', 'fedora']17def check_output(args):18 """19 Execute command, and return output stream. Provided for convenience/compatiblity with python 2.420 :param args: command to execute21 :return: output stream22 """23 return subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]24class RpmHandler:25 def __init__(self, current_version):26 if 'stab' in current_version:27 self.kernel_name = 'vzkernel'28 else:29 self.kernel_name = 'kernel'30 def get_installed(self):31 result = []32 for version in check_output(33 ['rpm', '--queryformat=%{VERSION}-%{RELEASE}\n', '-qq', self.kernel_name]).split('\n'):34 version = RpmHandler.strip_version(version)35 if version:36 result.append(version)37 return result38 def get_available(self):39 yum_output = check_output(40 ['yum', 'list', 'updates', self.kernel_name]).split('\n')41 result = []42 for line in yum_output:43 if line.startswith(self.kernel_name):44 result.append(RpmHandler.strip_version(line.split()[1]))45 return result46 @staticmethod47 def strip_version(version):48 parts = version.split('.')49 result = parts[0]50 parts.pop(0)51 for part in parts:52 if part and part[0].isdigit():53 result += '.'+part54 else:55 break56 if ':' in result:57 result = result.split(':')[1]58 return result59class DpkgHandler:60 def __init__(self, current_version):61 parts = current_version.split('-')62 self.pkg_version = parts[0]63 self.pkg_prefix = 'linux-image-'+parts[0]64 self.pkg_suffix = parts[-1]65 self.is_rt = '-rt-' in current_version66 def extract_version(self, line):67 if len(line):68 pkg_name = line.split()[0]69 return pkg_name[len(self.pkg_prefix)-len(self.pkg_version):]70 else:71 return None72 def get_versions(self, command):73 out = check_output(command)74 result = []75 for line in out.split('\n'):76 ver = self.extract_version(line)77 if ver:78 if self.is_rt:79 if '-rt-' in ver: 80 result.append(ver)81 elif '-rt-' not in ver:82 result.append(ver)83 return result84 def get_installed(self):85 return self.get_versions(['dpkg-query', '-W', self.pkg_prefix+'-*-'+self.pkg_suffix])86 def get_available(self):87 check_output(['apt-get', 'update'])88 return self.get_versions(['apt-cache', 'search', self.pkg_prefix+'-.*-'+self.pkg_suffix+'$'])89class UnknownHandler:90 def __init__(self):91 pass92 @staticmethod93 def get_installed():94 return []95 @staticmethod96 def get_available():97 return []98class KernelChecker:99 """100 This class performs checks to determine if kernel update & reboot needed101 """102 kernelcare = None103 def __init__(self):104 self.current_version = platform.release()105 self.inside_container = False106 self.distro_type = KernelChecker.get_distro_type()107 if 'stab' in self.current_version:108 self.inside_container = KernelChecker.inside_vz_container()109 else:110 self.inside_container = KernelChecker.inside_lxc_container()111 if self.distro_type == "rpm":112 handler = RpmHandler(self.current_version)113 self.current_version = handler.strip_version(self.current_version)114 elif self.distro_type == "dpkg":115 handler = DpkgHandler(self.current_version)116 pass117 else:118 handler = UnknownHandler()119 pass120 self.installed_versions = handler.get_installed()121 self.available_versions = handler.get_available()122 self.latest_version = self.get_latest()123 self.needs_update = self.latest_version != self.current_version124 self.latest_installed = self.latest_version in self.installed_versions125 self.latest_available = self.latest_version in self.available_versions126 self.check_kernelcare()127 @staticmethod128 def get_kernel_hash():129 try:130 # noinspection PyCompatibility131 from hashlib import sha1132 except ImportError:133 from sha import sha as sha1134 f = open('/proc/version', 'rb')135 try:136 return sha1(f.read()).hexdigest()137 finally:138 f.close()139 @staticmethod140 def is_kernelcare_supported_kernel():141 url = 'http://patches.kernelcare.com/'+KernelChecker.get_kernel_hash()+'/version'142 import urllib2143 try:144 urllib2.urlopen(url)145 return True146 except:147 return False148 def check_kernelcare(self):149 """150 checks if kernelcare (http://kernelcare.com) is installed, and kernel is patched151 :return: tupple ( INSTALLED, UP2DATE, SUPPORTED )152 """153 supported = KernelChecker.is_kernelcare_supported_kernel()154 kcare_bin = '/usr/bin/kcarectl'155 if os.path.exists(kcare_bin):156 p = subprocess.Popen([kcare_bin, '--check'], stderr=subprocess.PIPE, stdout=subprocess.PIPE)157 self.kernelcare = (True, p.wait() == 1, supported)158 else:159 self.kernelcare = (False, False, supported)160 @staticmethod161 def get_version(fullname):162 for prefix in KERNEL_PREFIXES:163 if fullname.startswith(prefix):164 return fullname[len(prefix)+1:]165 return None166 def get_latest(self):167 """168 Figures out latest kernel version169 :return: latest version from all versions170 """171 latest = '0'172 all = [self.current_version] + self.installed_versions + self.available_versions173 for k in all:174 if LooseVersion(latest) < LooseVersion(k):175 latest = k176 return latest177 @staticmethod178 def get_distro_type():179 import platform180 try:181 name = platform.dist()[0]182 except AttributeError:183 name = platform.linux_distribution()[0]184 if name.lower() in RPM_DISTRO:185 return "rpm"186 elif name.lower() in DPKG_DISTRO:187 return "dpkg"188 elif os.path.exists('/usr/bin/rpm'):189 return "rpm"190 elif os.path.exists('/usr/bin/dpkg'):191 return "dpkg"192 return "unknown"193 @staticmethod194 def inside_vz_container():195 """196 determines if we are inside Virtuozzo container197 :return: True if inside container, false otherwise198 """199 return os.path.exists('/proc/vz/veinfo') and not os.path.exists('/proc/vz/version')200 @staticmethod201 def inside_lxc_container():202 return '/lxc/' in open('/proc/1/cgroup').read()203 def get_data(self):204 return (self.latest_version, self.current_version, self.distro_type,205 self.needs_update, self.latest_installed,206 self.latest_available, self.inside_container,207 self.kernelcare[0], self.kernelcare[1], self.kernelcare[2])208 def tojson(self):209 result = '{ "latest" : "%s", ' \210 '"current" : "%s", ' \211 '"distro" : "%s", ' \212 '"needs_update" : %r, ' \213 '"latest_installed" : %r, ' \214 '"latest_available" : %r, ' \215 '"inside_container" : %r,' \216 '"kernelcare" : { "installed" : %r, "up2date" : %r, "supported" : %r } }' % self.get_data()217 return result218 def toyaml(self):219 result = 'latest : %s\n' \220 'current : %s\n' \221 'distro : %s\n' \222 'needs_update : %r\n' \223 'latest_installed : %r\n' \224 'latest_available : %r\n' \225 'inside_container : %r\n' \226 'kernelcare :\n ' \227 'installed : %r\n up2date : %r\n supported : %r\n' % self.get_data()228 return result229def main():230 """231 if --json or -j argument provided, print results in json, otherwise in yaml format232 :return: 0233 """234 kchecker = KernelChecker()235 import sys236 if len(sys.argv) > 1 and (sys.argv[1] == '--json' or sys.argv[1] == '-j'):237 print(kchecker.tojson())238 else:239 print(kchecker.toyaml())240if __name__ == "__main__":...

Full Screen

Full Screen

run.py

Source:run.py Github

copy

Full Screen

1# Base imports2import subprocess3from typing import List, Optional, Union4# Project imports5from docker import common6def run_with_compose(7 arguments: List[str],8 deps: Optional[bool] = False,9 inside_container: Optional[bool] = False10) -> int:11 """Runs a command, using the project's Docker Compose .yaml file."""12 if inside_container:13 compose_arguments = 'run --rm' if deps else 'run --rm --no-deps'14 command = f"{common.COMPOSE_COMMAND} {compose_arguments} {' '.join(arguments)}"15 else:16 command = f"{common.COMPOSE_COMMAND} {' '.join(arguments)}"17 print(command)18 return subprocess.call(command, shell=True)19def run_local(command: str, str_output: Optional[bool] = False) -> Union[int, str]:20 """Runs a command locally and captures output."""21 print(command)22 if str_output:23 process = subprocess.Popen(24 command,25 shell=True,26 stdout=subprocess.PIPE,27 universal_newlines=True28 )29 return process.communicate()[0].replace("\n", " ")...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run testcontainers-python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful