我有一个算法可以基于简单移动平均线购买股票,但是我试图将一个百分比分配给一个动态列表。Python:为列表中的每个元素分配百分比
例如,该算法允许购买四个股票,一个是第一个星期,所以创建一个包含四个元素的列表:["apple", "google", "tesla", "AMD"]
。
下周它购买六只股票并创建一个六只股票名单:["apple", "google", "tesla", "AMD", "intel", "qualcomm"]
。
我想要做的是动态分配一个百分比给列表中等于100%的每个元素。因此,在第一周,苹果公司将分配50%,谷歌25%,特斯拉15%,AMD 10%。
在第二周,Apple可能会分配50%,谷歌25%,特斯拉16.5%,AMD 5%,英特尔2.5%,高通1%。
在最后的结果中,我想给算法一个数字列表,并为每个元素分配一个从高到低的百分比,但仍等于100%。
在这里我我当前的代码:
from quantopian.pipeline.factors import VWAP
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume
from quantopian.pipeline.filters.morningstar import Q1500US
import numpy as np
import pandas as pd
import math
def initialize(context):
"""
Called once at the start of the algorithm.
"""
# Sets default slippage and commission fees to simulate real trading.
set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1.00))
set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1))
set_asset_restrictions(security_lists.restrict_leveraged_etfs)
# Creates a function that runs at the beginning of each week.
schedule_function(start_of_week, date_rules.week_start(), time_rules.market_open(hours=1))
# Rebalance every day, 1 hour after market open.
schedule_function(my_rebalance, date_rules.week_end(), time_rules.market_open(hours=1))
# Record tracking variables at the end of each day.
schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close())
#Creates a function that runs at the beginning of everyday.
schedule_function(start_of_day, date_rules.every_day(), time_rules.market_open(hours=1.5))
# Create our dynamic stock selector.
pipe = Pipeline()
attach_pipeline(pipe, name='my_pipeline')
# Construct Volume Factor.
vwap = VWAP(inputs=[USEquityPricing.close, USEquityPricing.volume], window_length=14)
prices_under_5 = (vwap < 5)
pipe.set_screen(prices_under_5)
context.df_long = pd.DataFrame(None, columns=list("ABC"))
context.df_short = pd.DataFrame(None, columns=list("ABC"))
context.long_list = []
context.short_list = []
def start_of_week(context, data):
"""
Called at the begining of every week before market open.
"""
context.df_long = pd.DataFrame(None, columns=list("AB"))
context.df_short = pd.DataFrame(None, columns=list("AB"))
context.long_list = []
context.short_list = []
context.output = pipeline_output('my_pipeline')
# These are the securities that we are interested in trading each day.
context.security_list = context.output.sort_index(axis=0, ascending=True, kind='quicksort')
context.security_list = context.security_list.index
for security in context.security_list:
# Gets Simple Moving Average for 7 days and 100 days
price_hist_8 = data.history(security, 'price', 7, '1d')
mavg8 = price_hist_8.mean()
price_hist_14 = data.history(security, 'price', 100, '1d')
mavg14 = price_hist_14.mean()
current_vol = data.current(securrity, "volume")
if mavg8 > mavg14:
#Calculate percent increase of volume
current_vol = data.current(security, "volume")
hist_vol = data.history(security, "volume", 10, "1d")
difference_increase_vol = current_vol - hist_vol
percent_increase_vol = (difference_increase_vol/hist_vol) * 100
percent_increase_vol = percent_increase_vol[0]
if perecent_increase_vol >= 0:
context.df_long_tbd = pd.DataFrame([[security, mavg8]], columns=list("AB"))
frames = [context.df_long, context.df_long_tbd]
context.df_long = pd.concat(frames)
# Sorts all of the stocks in the "long" Data Frame from steepest incline in simple moving average over 8 days. The "final_long_list" contains all of the top stocks' names.
result_long = context.df_long.sort_values(by=["B", "A"], ascending=False)
context.long_final_list = result_long["A"]
# Total amout of stocks that the algorithim is allowed to buy will be determined on total portfolial value.
# If the total portfolial value is $100,000, the algorithim is only allowed to look at
port_val = context.portfolio.portfolio_value
allowed_to_purchase = round(sqrt(port_val)/10)
for stock in context.long_final_list[:allowed_to_purchase]:
if data.can_trade(stock):
比方说,“allowed_to_purchase”等于10.现在,我想分配给每个股票在我的context.long_final_list十大百分比,高开始和结束低,等于100%。
有没有简单的解决方案或内置函数? “context.long_final_list”是一个熊猫数据框架,熊猫有一个函数吗?
更好地利用字典 – bigbounty
的听起来像是你想要一本字典,而不是一个列表... – alfasin
是否可以在熊猫的数据帧进行? –