迭代,如果字典 A 中的值大于字典 B,则放入字典 C?
Iterate and If value in dictionary A is larger than dictionary B then put in dictionary C?
此代码获取股票的当前价格及其当前的 21 天 EMA。
import yfinance as yf
import numpy as np
import bs4
import stockquotes
import pandas as pd
symbol_name = ['F', 'XOM']
symbol_data = {}
for symbol in symbol_name:
ticker = stockquotes.Stock(symbol)
today_price = ticker.current_price
symbol_data[symbol] = today_price
print(symbol_data)
ema_data = {}
for x in symbol_name:
symbol = yf.Ticker(x)
quote = symbol.history(period='1mo',interval='1d')
quote = quote.sort_index()
ema = 21
quote['ewm'] = quote['Close'].ewm(span=ema,min_periods=0,adjust=False,ignore_na=False).mean()
ema_quote = quote['ewm'].iloc[-1]
ema_data[x] = ema_quote
print(ema_data)
输出:
{'F': 6.82, 'XOM': 40.01}
{'F': 6.912368574990924, 'XOM': 42.168230541483716}
我的问题是如何编写以下代码:
If a one of the stock's EMA is lower than it's current price then put it into a new dictionary.
有人可以指导我如何获得这个吗?
dict1 = {'F': 6.82, 'XOM': 40.01}
dict2 = {'F': 6.912368574990924, 'XOM': 42.168230541483716}
dict3 = {}
for key in dict1.keys():
if dict1.get(key) < dict2.get(key):
dict3[key] = dict2.get(key)
输出:
{'F': 6.912368574990924, 'XOM': 42.168230541483716}
这应该有效:
for key in symbol_name:
if ema_data[key] < symbol_data[key]:
new_dict[key] = symbol_data[key]
此代码获取股票的当前价格及其当前的 21 天 EMA。
import yfinance as yf
import numpy as np
import bs4
import stockquotes
import pandas as pd
symbol_name = ['F', 'XOM']
symbol_data = {}
for symbol in symbol_name:
ticker = stockquotes.Stock(symbol)
today_price = ticker.current_price
symbol_data[symbol] = today_price
print(symbol_data)
ema_data = {}
for x in symbol_name:
symbol = yf.Ticker(x)
quote = symbol.history(period='1mo',interval='1d')
quote = quote.sort_index()
ema = 21
quote['ewm'] = quote['Close'].ewm(span=ema,min_periods=0,adjust=False,ignore_na=False).mean()
ema_quote = quote['ewm'].iloc[-1]
ema_data[x] = ema_quote
print(ema_data)
输出:
{'F': 6.82, 'XOM': 40.01}
{'F': 6.912368574990924, 'XOM': 42.168230541483716}
我的问题是如何编写以下代码:
If a one of the stock's EMA is lower than it's current price then put it into a new dictionary.
有人可以指导我如何获得这个吗?
dict1 = {'F': 6.82, 'XOM': 40.01}
dict2 = {'F': 6.912368574990924, 'XOM': 42.168230541483716}
dict3 = {}
for key in dict1.keys():
if dict1.get(key) < dict2.get(key):
dict3[key] = dict2.get(key)
输出:
{'F': 6.912368574990924, 'XOM': 42.168230541483716}
这应该有效:
for key in symbol_name:
if ema_data[key] < symbol_data[key]:
new_dict[key] = symbol_data[key]