Support
Quality
Security
License
Reuse
kandi has reviewed ticker and discovered the below as its top functions. This is intended to give you an instant insight into ticker implemented functionality, and help decide if they suit your requirements.
There are some breaking API changes introduced in ticker 2.0. Please refer to the [2.0 migration doc](https://github.com/robinhood/ticker/blob/master/2_0_migration.md).
Getting started
implementation 'com.robinhood.ticker:ticker:2.0.2'
Usage
<com.robinhood.ticker.TickerView
android:id="@+id/tickerView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Customization
android:gravity="center"
android:textColor="@color/colorPrimary"
android:textSize="16sp"
app:ticker_animationDuration="1500"
app:ticker_preferredScrollingDirection="any"
License
Copyright 2016 Robinhood Markets, Inc.
How to unlist a list and keep the names of the top level as a new variable in R
data:table::rbindlist(my_list, idcol = "Ticker")
library(tidyverse)
my_list %>%
enframe() %>%
unnest_wider(value) %>%
unnest(cols = c(date, Value))
# A tibble: 30 x 3
name date Value
<chr> <date> <int>
1 Ticker1 2021-01-01 1
2 Ticker1 2021-01-02 2
3 Ticker1 2021-01-03 3
4 Ticker1 2021-01-04 4
5 Ticker1 2021-01-05 5
6 Ticker1 2021-01-06 6
7 Ticker1 2021-01-07 7
8 Ticker1 2021-01-08 8
9 Ticker1 2021-01-09 9
10 Ticker1 2021-01-10 10
# ... with 20 more rows
-----------------------
data:table::rbindlist(my_list, idcol = "Ticker")
library(tidyverse)
my_list %>%
enframe() %>%
unnest_wider(value) %>%
unnest(cols = c(date, Value))
# A tibble: 30 x 3
name date Value
<chr> <date> <int>
1 Ticker1 2021-01-01 1
2 Ticker1 2021-01-02 2
3 Ticker1 2021-01-03 3
4 Ticker1 2021-01-04 4
5 Ticker1 2021-01-05 5
6 Ticker1 2021-01-06 6
7 Ticker1 2021-01-07 7
8 Ticker1 2021-01-08 8
9 Ticker1 2021-01-09 9
10 Ticker1 2021-01-10 10
# ... with 20 more rows
-----------------------
library(dplyr)
bind_rows(my_list, .id = "Ticker")
# A tibble: 30 x 3
Ticker date Value
<chr> <date> <int>
1 Ticker1 2021-01-01 1
2 Ticker1 2021-01-02 2
3 Ticker1 2021-01-03 3
4 Ticker1 2021-01-04 4
5 Ticker1 2021-01-05 5
6 Ticker1 2021-01-06 6
7 Ticker1 2021-01-07 7
8 Ticker1 2021-01-08 8
9 Ticker1 2021-01-09 9
10 Ticker1 2021-01-10 10
# ... with 20 more rows
-----------------------
library(dplyr)
bind_rows(my_list, .id = "Ticker")
# A tibble: 30 x 3
Ticker date Value
<chr> <date> <int>
1 Ticker1 2021-01-01 1
2 Ticker1 2021-01-02 2
3 Ticker1 2021-01-03 3
4 Ticker1 2021-01-04 4
5 Ticker1 2021-01-05 5
6 Ticker1 2021-01-06 6
7 Ticker1 2021-01-07 7
8 Ticker1 2021-01-08 8
9 Ticker1 2021-01-09 9
10 Ticker1 2021-01-10 10
# ... with 20 more rows
-----------------------
do.call(rbind, lapply(my_list, data.frame))
# date Value
# Ticker1.1 2021-01-01 1
# Ticker1.2 2021-01-02 2
# Ticker1.3 2021-01-03 3
# Ticker1.4 2021-01-04 4
# Ticker1.5 2021-01-05 5
# ...
do.call(rbind,
lapply(names(my_list), function(i){
data.frame(Ticker = i, my_list[[ i ]])
}))
# Ticker date Value
# 1 Ticker1 2021-01-01 1
# 2 Ticker1 2021-01-02 2
# 3 Ticker1 2021-01-03 3
# 4 Ticker1 2021-01-04 4
# 5 Ticker1 2021-01-05 5
# ...
-----------------------
do.call(rbind, lapply(my_list, data.frame))
# date Value
# Ticker1.1 2021-01-01 1
# Ticker1.2 2021-01-02 2
# Ticker1.3 2021-01-03 3
# Ticker1.4 2021-01-04 4
# Ticker1.5 2021-01-05 5
# ...
do.call(rbind,
lapply(names(my_list), function(i){
data.frame(Ticker = i, my_list[[ i ]])
}))
# Ticker date Value
# 1 Ticker1 2021-01-01 1
# 2 Ticker1 2021-01-02 2
# 3 Ticker1 2021-01-03 3
# 4 Ticker1 2021-01-04 4
# 5 Ticker1 2021-01-05 5
# ...
Error: Property 'body' cannot be accessed on 'Response?' because it is potentially null
if (statusCode == 200) {
return Text(
"${BTCPrice.fromJson(jsonDecode(snapshot.data!.body)).eur}"); // adding ! on data
}
final response = await http.get(Uri.https('blockhain.info', 'ticker'));
final response = await http.get(Uri.parse('https://blockchain.info/ticker'));
-----------------------
if (statusCode == 200) {
return Text(
"${BTCPrice.fromJson(jsonDecode(snapshot.data!.body)).eur}"); // adding ! on data
}
final response = await http.get(Uri.https('blockhain.info', 'ticker'));
final response = await http.get(Uri.parse('https://blockchain.info/ticker'));
-----------------------
if (statusCode == 200) {
return Text(
"${BTCPrice.fromJson(jsonDecode(snapshot.data!.body)).eur}"); // adding ! on data
}
final response = await http.get(Uri.https('blockhain.info', 'ticker'));
final response = await http.get(Uri.parse('https://blockchain.info/ticker'));
HTML DOM id Array Property & Adding to Stage JavaScript (Array)
<html>
<script type="text/javascript" src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
body { margin: 0; }
#gameCanvas { background-color: lightblue; }
.canvasHolder1 { position: relative; }
.ui { position: absolute; top: 0; left: 0; pointer-events: none;}
.ui-element { position: relative; display: inline-block; margin-left: 4px; }
</style>
<body onload="startGame();">
<div class="canvasHolder1">
<div id="ship">β΅ </div>
<div class="ui"></div>
<canvas id="gameCanvas" width="300" height="300">Not supported</canvas>
</div>
<script type="text/javascript">
const stage = new createjs.Stage("gameCanvas");
const ship = document.getElementById("ship");
const ui = document.querySelector(".ui");
const canvas = document.getElementById("gameCanvas");
const canvasHolder = document.querySelector('.canvasHolder1');
var divs = [];
const texts = [ 'My Ship', 'Pos X', 'Pos Y', 'Other' ];
for (i = 0; i <= 3; i++) {
const newDiv = document.createElement("type");
newDiv.id = `q${i}`;
newDiv.className = `ui-element`;
newDiv.innerHTML = texts[i];
ui.appendChild(newDiv);
divs.push(newDiv);
}
const textXPosition = divs[1];
const textYPosition = divs[2];
const textProgress = divs[3];
canvas.addEventListener('mousemove', (evt) => {
textXPosition.innerHTML = evt.pageX;
textYPosition.innerHTML = evt.pageY;
});
var objectArray = [];
objectArray.push(new createjs.DOMElement(divs[0]));
const myFirstText = objectArray[0];
const myFirstTextWidth = parseInt(myFirstText.htmlElement.offsetWidth);
var shipJS = new createjs.DOMElement(ship);
function applyPosition(posObject) {
shipJS.x = posObject.x;
shipJS.y = posObject.y;
myFirstText.x = posObject.x - (myFirstTextWidth / 2);
myFirstText.y = posObject.y - 15;
}
const shipPosition = {
x: canvas.width / 3,
y: 50
};
applyPosition(shipPosition);
let looperCount = -1;
const step = 0.02;
const distance = canvas.width / 3;
function handleTick(event) {
if (looperCount >= 1) { looperCount = -1; }
looperCount += step;
const progress = Math.PI * looperCount;
textProgress.innerHTML = parseInt(((looperCount + 1) / 2) * 100 )+'%';
applyPosition({
x: (Math.cos(progress) * distance) + (distance * 1.5),
y: (Math.sin(progress) * distance) + (distance * 1.5)
});
stage.update();
}
function startGame() {
stage.addChild(shipJS);
stage.addChild(myFirstText);
createjs.Ticker.addEventListener("tick", handleTick);
}
</script>
</body>
</html>
Generate a progressive bar chart within table (like in Excel)?
library(gt)
# remotes::install_github("jthomasmock/gtExtras")
library(gtExtras)
df <- structure(list(ticker = c("AAPL", "MSFT", "AMZN", "NVDA"),
high = c("182.94", "349.67", "3,773.08", "346.47"),
current = c(170.7, 308, 2885, 231.4)))
df <- as.data.frame(df)
df$high <- gsub(",", "", df$high)
df$high <- as.numeric(df$high)
df$Off_by <- round((df$high - df$current) /df$current, 3)
gt::gt(df) %>%
gtExtras::gt_plt_bar(column = Off_by, keep_column = TRUE, color = "red", scale_type = "percent")
-----------------------
library(kableExtra)
library(tidyverse)
df <- structure(list(ticker = c("AAPL", "MSFT", "AMZN", "NVDA"), high = c("182.94",
"349.67", "3,773.08", "346.47"), current = c(170.7, 308, 2885,
231.4), Off_by = c(-7, -14, -31, -50)), class = "data.frame", row.names = c(NA,
-4L))
## Need a hacky factor for making the bars long enough to cover the labels
hack <- 2.5
## that's for the gradient, inspired by Alan https://stackoverflow.com/a/61777415/7941188
grad_df <- data.frame(
xintercept = seq(-100 * hack, 0, length.out = 2000),
alpha = seq(0.3, 0, length.out = 2000)
)
inline_bars <-
df %>%
## need to make sure the plots are in the right order
mutate(ticker = fct_inorder(ticker)) %>%
group_split(ticker) %>%
map(~ ggplot(.x, aes(x = Off_by * hack, y = "")) +
geom_col(fill = "darkred") +
geom_text(aes(x = 0, label = paste0(Off_by, "%")),
hjust = 1, color = "white",
## the size is chosen because you will have 50points, and this will just nearly
## fill an inch (your chosen file size)
size = 5 * 50 / 14
) +
## important to have the same limits for every plot
coord_cartesian(xlim = c(-100, 0), clip = "off") +
## for the gradient
geom_vline(
data = grad_df, mapping = aes(xintercept = xintercept, alpha = alpha),
color = "white"
) +
theme_void() +
theme(legend.position = "none"))
map(1:4, function(i) {
ggsave(
filename = paste0(df$ticker[i], ".png"),
plot = inline_bars[[i]], height = 1, dpi = 300
)
})
ls_inline_plots <- file.path(getwd(), paste0(df$ticker, ".png"))
df %>%
## remove cell content for the plot
mutate(Off_by = "") %>%
kbl(booktabs = TRUE) %>%
kable_paper(full_width = FALSE) %>%
column_spec(4, image = spec_image(ls_inline_plots, width = 200, height = 50)) %>%
## RStudio preview does not always show the images, but the final html file shows them
cat(., file = "tbl.html")
Vectorize for loop and return x day high and low
# number of days
N = 8
df.join(df.rolling(f'{N+1}d', min_periods=1)
.agg({'High': lambda s: s.le(s.iloc[-1])[::-1].cumprod().sum()-1,
'Low': lambda s: s.ge(s.iloc[-1])[::-1].cumprod().sum()-1,
})
.add_prefix(f'{N}_days_')
)
Open High Low Close 8_days_High 8_days_Low
date
2020-03-19 1.1904 1.1937 1.1832 1.1832 0.0 0.0
2020-03-20 1.1843 1.1879 1.1769 1.1772 0.0 1.0
2020-03-21 1.1755 1.1767 1.1662 1.1672 0.0 2.0
2020-03-22 1.1686 1.1721 1.1611 1.1721 0.0 3.0
2020-03-23 1.1732 1.1819 1.1690 1.1819 2.0 0.0
2020-03-24 1.1836 1.1928 1.1807 1.1922 4.0 0.0
2020-03-25 1.1939 1.1939 1.1864 1.1936 6.0 0.0
2020-03-26 1.1967 1.2141 1.1964 1.2114 7.0 0.0
2020-03-27 1.2118 1.2144 1.2039 1.2089 7.0 0.0
2020-03-28 1.2080 1.2099 1.2018 1.2041 0.0 1.0
2020-03-29 1.2033 1.2033 1.1853 1.1880 0.0 4.0
2020-03-30 1.1876 1.1887 1.1806 1.1879 0.0 6.0
2020-03-31 1.1921 1.1972 1.1873 1.1939 1.0 0.0
2020-04-01 1.1932 1.1997 1.1914 1.1914 2.0 0.0
2020-04-02 1.1902 1.1924 1.1781 1.1862 0.0 7.0
-----------------------
# number of days
N = 8
df.join(df.rolling(f'{N+1}d', min_periods=1)
.agg({'High': lambda s: s.le(s.iloc[-1])[::-1].cumprod().sum()-1,
'Low': lambda s: s.ge(s.iloc[-1])[::-1].cumprod().sum()-1,
})
.add_prefix(f'{N}_days_')
)
Open High Low Close 8_days_High 8_days_Low
date
2020-03-19 1.1904 1.1937 1.1832 1.1832 0.0 0.0
2020-03-20 1.1843 1.1879 1.1769 1.1772 0.0 1.0
2020-03-21 1.1755 1.1767 1.1662 1.1672 0.0 2.0
2020-03-22 1.1686 1.1721 1.1611 1.1721 0.0 3.0
2020-03-23 1.1732 1.1819 1.1690 1.1819 2.0 0.0
2020-03-24 1.1836 1.1928 1.1807 1.1922 4.0 0.0
2020-03-25 1.1939 1.1939 1.1864 1.1936 6.0 0.0
2020-03-26 1.1967 1.2141 1.1964 1.2114 7.0 0.0
2020-03-27 1.2118 1.2144 1.2039 1.2089 7.0 0.0
2020-03-28 1.2080 1.2099 1.2018 1.2041 0.0 1.0
2020-03-29 1.2033 1.2033 1.1853 1.1880 0.0 4.0
2020-03-30 1.1876 1.1887 1.1806 1.1879 0.0 6.0
2020-03-31 1.1921 1.1972 1.1873 1.1939 1.0 0.0
2020-04-01 1.1932 1.1997 1.1914 1.1914 2.0 0.0
2020-04-02 1.1902 1.1924 1.1781 1.1862 0.0 7.0
-----------------------
@numba.njit
def count_smaller(arr):
current = arr[-1]
count = 0
for i in range(arr.shape[0]-2, -1, -1):
if arr[i] > current:
break
count += 1
return count
@numba.njit
def count_greater(arr):
current = arr[-1]
count = 0
for i in range(arr.shape[0]-2, -1, -1):
if arr[i] < current:
break
count += 1
return count
df["x_day_high"] = df.High.expanding().apply(count_smaller, engine='numba', raw=True)
df["x_day_low"] = df.Low.expanding().apply(count_greater, engine='numba', raw=True)
def count_consecutive_true(bool_arr):
return bool_arr[::-1].cumprod().sum()
def count_smaller(arr):
return count_consecutive_true(arr <= arr[-1]) - 1
def count_greater(arr):
return count_consecutive_true(arr >= arr[-1]) - 1
df["x_day_high"] = df.High.expanding().apply(count_smaller, raw=True)
df["x_day_low"] = df.Low.expanding().apply(count_greater, raw=True)
-----------------------
@numba.njit
def count_smaller(arr):
current = arr[-1]
count = 0
for i in range(arr.shape[0]-2, -1, -1):
if arr[i] > current:
break
count += 1
return count
@numba.njit
def count_greater(arr):
current = arr[-1]
count = 0
for i in range(arr.shape[0]-2, -1, -1):
if arr[i] < current:
break
count += 1
return count
df["x_day_high"] = df.High.expanding().apply(count_smaller, engine='numba', raw=True)
df["x_day_low"] = df.Low.expanding().apply(count_greater, engine='numba', raw=True)
def count_consecutive_true(bool_arr):
return bool_arr[::-1].cumprod().sum()
def count_smaller(arr):
return count_consecutive_true(arr <= arr[-1]) - 1
def count_greater(arr):
return count_consecutive_true(arr >= arr[-1]) - 1
df["x_day_high"] = df.High.expanding().apply(count_smaller, raw=True)
df["x_day_low"] = df.Low.expanding().apply(count_greater, raw=True)
How to make labels appear when clicking on a step plot subplot point in matplotlib (or possibly plotly)?
import pandas as pd
import numpy as np
import matplotlib as mtpl
from matplotlib import pyplot as plt
import matplotlib.ticker as ticker
annotations = []
data = {
# 'Name': ['Status', 'Status', 'HMI', 'Allst', 'Drvr', 'CurrTUBand', 'RUSource', 'RUReqstrPriority', 'RUReqstrSystem', 'RUResReqstStat', 'CurrTUBand', 'DSP', 'SetDSP', 'SetDSP', 'DSP', 'RUSource', 'RUReqstrPriority', 'RUReqstrSystem', 'RUResReqstStat', 'Status', 'Delay', 'Status', 'Delay', 'HMI', 'Status', 'Status', 'HMI', 'DSP'],
# 'Value': [4, 4, 2, 1, 1, 1, 0, 7, 0, 4, 1, 1, 3, 0, 3, 0, 7, 0, 4, 1, 0, 1, 0, 1, 4, 4, 2, 3],
# 'Gage': ['H1', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H1', 'H1', 'H3', 'H3', 'H3', 'H1', 'H3', 'H3', 'H3'],
# 'Id_Par': [0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 0, 0, 22, 22, 28, 28, 28, 28, 0, 0, 38, 38, 0, 0, 0, 0, 0]
'Name': ['Lamp_D_Rq', 'Status', 'Status', 'HMI', 'Lck_D_RqDrv3', 'Lck_D_RqDrv3', 'Lck_D_RqDrv3', 'Lck_D_RqDrv3', 'Lamp_D_Rq', 'Lamp_D_Rq', 'Lamp_D_Rq', 'Lamp_D_Rq'],
'Value': [0, 4, 4, 2, 1, 1, 2, 2, 1, 1, 3, 3],
'Gage': ['F1', 'H1', 'H3', 'H3', 'H3', 'F1', 'H3', 'F1', 'F1', 'H3', 'F1', 'H3'],
'Id_Par': [0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0]
}
signals_df = pd.DataFrame(data)
def plot_signals(signals_df):
print(signals_df)
# Count signals by parallel
signals_df['Count'] = signals_df.groupby('Id_Par').cumcount().add(1).mask(signals_df['Id_Par'].eq(0), 0)
# Subtract Parallel values from the index column
signals_df['Sub'] = signals_df.index - signals_df['Count']
id_par_prev = signals_df['Id_Par'].unique()
id_par = np.delete(id_par_prev, 0)
signals_df['Prev'] = [1 if x in id_par else 0 for x in signals_df['Id_Par']]
signals_df['Final'] = signals_df['Prev'] + signals_df['Sub']
# Convert and set Subtract to index
signals_df.set_index('Final', inplace=True)
# Get individual names and variables for the chart
names_list = [name for name in signals_df['Name'].unique()]
num_names_list = len(names_list)
num_axisx = len(signals_df["Name"])
# Matplotlib's categorical feature to convert x-axis values to string
x_values = [-1, ]
x_values += (list(set(signals_df.index)))
x_values = [str(i) for i in sorted(x_values)]
# Creation Graphics
fig, ax = plt.subplots(nrows=num_names_list, figsize=(10, 10), sharex=True)
plt.xticks(np.arange(0, num_axisx), color='SteelBlue', fontweight='bold')
# Loop to build the different graphs
for pos, name in enumerate(names_list):
print("name: %s" % name)
print("pos: %s" % pos)
# Creating a dummy plot and then remove it
dummy, = ax[pos].plot(x_values, np.zeros_like(x_values))
dummy.remove()
# Get names by values and gage data
data = signals_df[signals_df["Name"] == name]["Value"]
data_gage = signals_df[signals_df["Name"] == name]["Gage"]
# Get values axis-x and axis-y
x_ = np.hstack([-1, data.index.values, len(signals_df) - 1])
y_ = np.hstack([0, data.values, data.iloc[-1]])
y_gage = np.hstack(["", "-", data_gage.values])
# print(y_gage)
# Plotting the data by position
steps = ax[pos].plot(x_.astype('str'), y_, drawstyle='steps-post', marker='*', markersize=8, color='k', linewidth=2)
ax[pos].set_ylabel(name, fontsize=8, fontweight='bold', color='SteelBlue', rotation=30, labelpad=35)
ax[pos].yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
ax[pos].yaxis.set_tick_params(labelsize=6)
ax[pos].grid(alpha=0.4, color='SteelBlue')
# Labeling the markers with Values and Gage
xy_temp = []
for i in range(len(y_)):
if i == 0:
xy = [x_[0].astype('str'), y_[0]]
xy_temp.append(xy)
else:
xy = [x_[i - 1].astype('str'), y_[i - 1]]
xy_temp.append(xy)
# Creating values in text inside the plot
ax[pos].text(x=xy[0], y=xy[1], s=str(xy[1]), color='k', fontweight='bold', fontsize=12)
for val_gage, xy in zip(y_gage, xy_temp):
print("val_gage: %s" % val_gage)
annot = ax[pos].annotate(val_gage, xy=xy, xytext=(-20, 20), textcoords="offset points",
bbox=dict(boxstyle="round", fc="w"),
arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)
annotations.append(annot)
# Function for storing and showing the clicked values
def update_annot(ind):
print("Enter update_annot")
coord = steps[0].get_offsets()[ind["ind"][0]]
annot.xy = coord
text = "{}, {}".format(" ".join(list(map(str, ind["ind"]))),
" ".join([y_gage[n] for n in ind["ind"]]))
annot.set_text(text)
annot.get_bbox_patch().set_alpha(0.4)
def on_click(event):
print("Enter on_click")
vis = annot.get_visible()
# make the first three annotations visible
for i in range(0, 3):
print('elem visible')
annotations[i].set_visible(True)
print(event.inaxes)
print(ax[pos])
print(event.inaxes == ax[pos])
if event.inaxes == ax[pos]:
cont, ind = steps[0].contains(event)
print (ind)
if cont:
update_annot(ind)
annot.set_visible(True)
fig.canvas.draw_idle()
else:
if vis:
annot.set_visible(False)
fig.canvas.draw_idle()
fig.canvas.mpl_connect("button_press_event",on_click)
plt.show()
plot_signals(signals_df)
-----------------------
import plotly.express as px
import plotly.graph_objs as go
import pandas as pd
import numpy as np
data = {
"Name": [
"Lamp_D_Rq", "Status", "Status", "HMI",
"Lck_D_RqDrv3", "Lck_D_RqDrv3", "Lck_D_RqDrv3",
"Lck_D_RqDrv3", "Lamp_D_Rq", "Lamp_D_Rq",
"Lamp_D_Rq", "Lamp_D_Rq",
],
"Value": [0, 4, 4, 2, 1, 1, 2, 2, 1, 1, 3, 3],
"Gage": [
"F1", "H1", "H3", "H3", "H3",
"F1", "H3", "F1", "F1", "H3",
"F1", "H3",
],
"Id_Par": [0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0],
}
signals_df = pd.DataFrame(data)
fig = px.line(
signals_df,
y="Value",
x="Sub",
color="Name",
hover_data=["Gage"],
custom_data=["Gage"],
markers=True,
height=500,
render_mode="svg")
fig.update_traces(line={"shape": 'hv'})
fig.update_traces(
hovertemplate="<br>".join([
"Gage: %{customdata[0]}",
])
)
fig.show(config={'displaylogo': False})
-----------------------
import plotly.express as px
import plotly.graph_objs as go
import pandas as pd
import numpy as np
data = {
"Name": [
"Lamp_D_Rq", "Status", "Status", "HMI",
"Lck_D_RqDrv3", "Lck_D_RqDrv3", "Lck_D_RqDrv3",
"Lck_D_RqDrv3", "Lamp_D_Rq", "Lamp_D_Rq",
"Lamp_D_Rq", "Lamp_D_Rq",
],
"Value": [0, 4, 4, 2, 1, 1, 2, 2, 1, 1, 3, 3],
"Gage": [
"F1", "H1", "H3", "H3", "H3",
"F1", "H3", "F1", "F1", "H3",
"F1", "H3",
],
"Id_Par": [0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0],
}
signals_df = pd.DataFrame(data)
fig = px.line(
signals_df,
y="Value",
x="Sub",
color="Name",
hover_data=["Gage"],
custom_data=["Gage"],
markers=True,
height=500,
render_mode="svg")
fig.update_traces(line={"shape": 'hv'})
fig.update_traces(
hovertemplate="<br>".join([
"Gage: %{customdata[0]}",
])
)
fig.show(config={'displaylogo': False})
Confidence Interval 3 dimensional plot
import plotly.graph_objects as go
import numpy as np
x = np.arange(0.1,1.1,0.01)
y = np.linspace(-np.pi,np.pi,100)
X,Y = np.meshgrid(x,y)
result = []
for i,j in zip(X,Y):
result.append(np.log(i)+np.sin(j))
upper_bound = np.array(result)+1
lower_bound = np.array(result)-1
fig = go.Figure(data=[
go.Surface(z=result),
go.Surface(z=upper_bound, showscale=False, opacity=0.3,colorscale='purp'),
go.Surface(z=lower_bound, showscale=False, opacity=0.3,colorscale='purp'),
])
fig.show()
f-string in yaxis.set_major_formatter
ax.yaxis.set_major_formatter(c + '{x:1.2f}')
ax.yaxis.set_major_formatter(f'{c}{{x:1.2f}}')
-----------------------
ax.yaxis.set_major_formatter(c + '{x:1.2f}')
ax.yaxis.set_major_formatter(f'{c}{{x:1.2f}}')
Pandas conditional formatting not displaying background colors. (no errors)
return 'background-color: %s' % background_color
import numpy as np
def color_negative_red(subset_df):
# Create Styles based on multiple conditions with np.select
return np.select(
[subset_df < 0, subset_df > 0],
['background-color: red', 'background-color: green'],
default=''
)
# Select Subset of columns
cols = df.columns[df.columns.str.endswith('%')]
# This can also be hard-coded
# cols = ['Daily%', 'WTD%', 'MTD%', 'QTD%', 'YTD%']
(
df.style.apply(
color_negative_red, subset=cols, axis=None
).format(
# This can be used to set general number styles without a fmt string
precision=2, thousands=",", subset='Close'
).format(
# Apply percent format to subset of cols
'{:,.2f}%', subset=cols
).hide_index() # To remove the "row numbers" hide the index
)
df = pd.DataFrame({'Stock': ['SPY', 'TLT', 'XLY', 'XLF', 'XLV', 'XLK', 'XLP', 'XLI', 'XLB', 'XLE', 'XLU', 'XLRE', 'XLC'], 'Close': [453.0799865722656, 148.17999267578125, 183.52000427246094, 38.06999969482422, 136.85000610351562, 159.36000061035156, 72.83000183105469, 104.58999633789062, 85.37000274658203, 48.619998931884766, 69.48999786376953, 48.72999954223633, 85.47000122070312], 'Daily%': [-0.024275881759957655, -0.9094561130207558, -0.05990339673614984, -0.6264726438619272, 0.10973603410557096, 0.39690348375861295, -0.12341791024475374, -0.6081982311376585, -0.66325305868224, -0.5726024238382843, -0.8277463016708558, 0.0, 0.0], 'WTD%': [0.18795205211694732, -1.1144566965053964, 0.1692033989594774, -0.9882992472694656, 1.078371165114885, -0.2128968969240593, 1.0124873403369272, -0.20038807991586702, -0.5706939905500718, -0.22573488894909668, 1.2678447717357961, 2.8059028977694966, 0.19929444649862676], 'MTD%': [0.28331093711392863, -0.47686662420427856, -0.06534258200082742, -0.28811055388244855, 1.1829989674792052, 0.2894944817725163, 0.26156723981653324, 0.4610467051436526, -0.023418015235201397, 1.9500950554754906, 0.07199801354481171, 0.4742258602810889, -0.6740288326379547], 'QTD%': [5.262178352321592, 2.7814348045817643, 2.2053947247214483, 2.9475396594933923, 7.6965502732190245, 7.741191714387993, 4.4008021800644235, 1.4156880862558818, 3.1536980944675, -11.293563740764009, 8.714017294090489, 9.481018602199223, 4.781171436152855], 'YTD%': [22.855819321112786, -5.941348869649508, 15.117304215482205, 30.914717313288243, 21.15981390085853, 24.597340663914796, 9.157674608158786, 21.039222202640808, 19.065559804985433, 28.082192056143985, 13.69437021949676, 37.73317713704715, 28.56497729371572]})
-----------------------
return 'background-color: %s' % background_color
import numpy as np
def color_negative_red(subset_df):
# Create Styles based on multiple conditions with np.select
return np.select(
[subset_df < 0, subset_df > 0],
['background-color: red', 'background-color: green'],
default=''
)
# Select Subset of columns
cols = df.columns[df.columns.str.endswith('%')]
# This can also be hard-coded
# cols = ['Daily%', 'WTD%', 'MTD%', 'QTD%', 'YTD%']
(
df.style.apply(
color_negative_red, subset=cols, axis=None
).format(
# This can be used to set general number styles without a fmt string
precision=2, thousands=",", subset='Close'
).format(
# Apply percent format to subset of cols
'{:,.2f}%', subset=cols
).hide_index() # To remove the "row numbers" hide the index
)
df = pd.DataFrame({'Stock': ['SPY', 'TLT', 'XLY', 'XLF', 'XLV', 'XLK', 'XLP', 'XLI', 'XLB', 'XLE', 'XLU', 'XLRE', 'XLC'], 'Close': [453.0799865722656, 148.17999267578125, 183.52000427246094, 38.06999969482422, 136.85000610351562, 159.36000061035156, 72.83000183105469, 104.58999633789062, 85.37000274658203, 48.619998931884766, 69.48999786376953, 48.72999954223633, 85.47000122070312], 'Daily%': [-0.024275881759957655, -0.9094561130207558, -0.05990339673614984, -0.6264726438619272, 0.10973603410557096, 0.39690348375861295, -0.12341791024475374, -0.6081982311376585, -0.66325305868224, -0.5726024238382843, -0.8277463016708558, 0.0, 0.0], 'WTD%': [0.18795205211694732, -1.1144566965053964, 0.1692033989594774, -0.9882992472694656, 1.078371165114885, -0.2128968969240593, 1.0124873403369272, -0.20038807991586702, -0.5706939905500718, -0.22573488894909668, 1.2678447717357961, 2.8059028977694966, 0.19929444649862676], 'MTD%': [0.28331093711392863, -0.47686662420427856, -0.06534258200082742, -0.28811055388244855, 1.1829989674792052, 0.2894944817725163, 0.26156723981653324, 0.4610467051436526, -0.023418015235201397, 1.9500950554754906, 0.07199801354481171, 0.4742258602810889, -0.6740288326379547], 'QTD%': [5.262178352321592, 2.7814348045817643, 2.2053947247214483, 2.9475396594933923, 7.6965502732190245, 7.741191714387993, 4.4008021800644235, 1.4156880862558818, 3.1536980944675, -11.293563740764009, 8.714017294090489, 9.481018602199223, 4.781171436152855], 'YTD%': [22.855819321112786, -5.941348869649508, 15.117304215482205, 30.914717313288243, 21.15981390085853, 24.597340663914796, 9.157674608158786, 21.039222202640808, 19.065559804985433, 28.082192056143985, 13.69437021949676, 37.73317713704715, 28.56497729371572]})
-----------------------
return 'background-color: %s' % background_color
import numpy as np
def color_negative_red(subset_df):
# Create Styles based on multiple conditions with np.select
return np.select(
[subset_df < 0, subset_df > 0],
['background-color: red', 'background-color: green'],
default=''
)
# Select Subset of columns
cols = df.columns[df.columns.str.endswith('%')]
# This can also be hard-coded
# cols = ['Daily%', 'WTD%', 'MTD%', 'QTD%', 'YTD%']
(
df.style.apply(
color_negative_red, subset=cols, axis=None
).format(
# This can be used to set general number styles without a fmt string
precision=2, thousands=",", subset='Close'
).format(
# Apply percent format to subset of cols
'{:,.2f}%', subset=cols
).hide_index() # To remove the "row numbers" hide the index
)
df = pd.DataFrame({'Stock': ['SPY', 'TLT', 'XLY', 'XLF', 'XLV', 'XLK', 'XLP', 'XLI', 'XLB', 'XLE', 'XLU', 'XLRE', 'XLC'], 'Close': [453.0799865722656, 148.17999267578125, 183.52000427246094, 38.06999969482422, 136.85000610351562, 159.36000061035156, 72.83000183105469, 104.58999633789062, 85.37000274658203, 48.619998931884766, 69.48999786376953, 48.72999954223633, 85.47000122070312], 'Daily%': [-0.024275881759957655, -0.9094561130207558, -0.05990339673614984, -0.6264726438619272, 0.10973603410557096, 0.39690348375861295, -0.12341791024475374, -0.6081982311376585, -0.66325305868224, -0.5726024238382843, -0.8277463016708558, 0.0, 0.0], 'WTD%': [0.18795205211694732, -1.1144566965053964, 0.1692033989594774, -0.9882992472694656, 1.078371165114885, -0.2128968969240593, 1.0124873403369272, -0.20038807991586702, -0.5706939905500718, -0.22573488894909668, 1.2678447717357961, 2.8059028977694966, 0.19929444649862676], 'MTD%': [0.28331093711392863, -0.47686662420427856, -0.06534258200082742, -0.28811055388244855, 1.1829989674792052, 0.2894944817725163, 0.26156723981653324, 0.4610467051436526, -0.023418015235201397, 1.9500950554754906, 0.07199801354481171, 0.4742258602810889, -0.6740288326379547], 'QTD%': [5.262178352321592, 2.7814348045817643, 2.2053947247214483, 2.9475396594933923, 7.6965502732190245, 7.741191714387993, 4.4008021800644235, 1.4156880862558818, 3.1536980944675, -11.293563740764009, 8.714017294090489, 9.481018602199223, 4.781171436152855], 'YTD%': [22.855819321112786, -5.941348869649508, 15.117304215482205, 30.914717313288243, 21.15981390085853, 24.597340663914796, 9.157674608158786, 21.039222202640808, 19.065559804985433, 28.082192056143985, 13.69437021949676, 37.73317713704715, 28.56497729371572]})
Remove the requirement to loop through numpy array
import numpy as np
import pandas as pd
def genMockDataFrame(days,startPrice,colName,startDate,seed=None):
''' identical to the example provided '''
periods = days*24
np.random.seed(seed)
steps = np.random.normal(loc=0, scale=0.0018, size=periods)
steps[0]=0
P = startPrice+np.cumsum(steps)
P = [round(i,4) for i in P]
fxDF = pd.DataFrame({
'ticker':np.repeat( [colName], periods ),
'date':np.tile( pd.date_range(startDate, periods=periods, freq='H'), 1 ),
'price':(P)})
fxDF.index = pd.to_datetime(fxDF.date)
fxDF = fxDF.price.resample('D').ohlc()
fxDF.columns = [i.title() for i in fxDF.columns]
return fxDF
# create the base dataframe according to the former SoFunc
df = genMockDataFrame(10,1.1904,'eurusd','19/3/2020',seed=157)
df["Upper_Band"] = 1.1928
df.loc["2020-03-27"]["Upper_Band"] = 1.2118
df.loc["2020-03-26"]["Upper_Band"] = 1.2200
# create a df out of the cluster array
clusters = np.array([1.1929 , 1.2118 ])
clusters_df = pd.DataFrame({"clust": clusters})
# perform the merge, then filter and finally clean up
result_df = (
pd
.merge(df.reset_index(), clusters_df, how="cross") # for each entry in cluster, make a copy of df
.loc[lambda z: (z.Low <= z.clust) & (z.High >= z.clust) & (z.High >= z.Upper_Band), :] # filter the copies down
.drop(columns=["clust"]) # not needed in result
.assign(Level=1.0) # to match your result; not really needed
.set_index("date") # bring back the old index
)
print(result_df)
QUESTION
How to unlist a list and keep the names of the top level as a new variable in R
Asked 2022-Apr-14 at 12:15is there a simple way to unlist a list and keep the names of one level as a new variable?
Working example:
# Input list
my_list <- list(Ticker1 = list(date = seq.Date(as.Date('2021-01-01'), as.Date('2021-01-10'), by = 'day'), Value = 1:10),
Ticker2 = list(date = seq.Date(as.Date('2021-01-01'), as.Date('2021-01-10'), by = 'day'), Value = 11:20),
Ticker3 = list(date = seq.Date(as.Date('2021-01-01'), as.Date('2021-01-10'), by = 'day'), Value = 21:30))
# Desired data frame
my_df_goal <- as.data.frame(list(Ticker = c(rep("Ticker1", 10), rep("Ticker2", 10), rep("Ticker3", 10)),
date = rep(seq.Date(as.Date('2021-01-01'), as.Date('2021-01-10'), by = 'day'), 3),
Value = 1:30))
There are similar questions regarding unlisting on stackoverflow, but I wasn't able to solve my problem.
One way would probably be
my_df <- as.data.frame(rlist::list.flatten(my_list))
# Same result:
my_df2 <- as.data.frame(unlist(my_list,recursive = F))
#Edit: just noticed that you do not need to unlist first to get the same result:
my_df3 <- as.data.frame(my_list)
and then try to extract the Ticker from the new variable name. But I hope there is an easier solution.
I also tried my_df4 <- reshape2::melt(my_list)
, but this is not helpful. I have a feeling that the purrr
package may have this functionality, but I am not familiar with the package.
I am happy about any help!
Thanks a lot
ANSWER
Answered 2022-Apr-14 at 11:47Use data.table::rbindlist
:
data:table::rbindlist(my_list, idcol = "Ticker")
Or, in the tidyverse
:
library(tidyverse)
my_list %>%
enframe() %>%
unnest_wider(value) %>%
unnest(cols = c(date, Value))
# A tibble: 30 x 3
name date Value
<chr> <date> <int>
1 Ticker1 2021-01-01 1
2 Ticker1 2021-01-02 2
3 Ticker1 2021-01-03 3
4 Ticker1 2021-01-04 4
5 Ticker1 2021-01-05 5
6 Ticker1 2021-01-06 6
7 Ticker1 2021-01-07 7
8 Ticker1 2021-01-08 8
9 Ticker1 2021-01-09 9
10 Ticker1 2021-01-10 10
# ... with 20 more rows
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported
Save this library and start creating your kit
Explore Related Topics
Save this library and start creating your kit